# Pow(x, n)

- slug: powx-n
- difficulty: Medium

Implement [pow(x, n)](http://www.cplusplus.com/reference/valarray/pow/), which calculates `x` raised to the power `n` (i.e., `xn`).

**Example 1:**

**Input:** x = 2.00000, n = 10
**Output:** 1024.00000

**Example 2:**

**Input:** x = 2.10000, n = 3
**Output:** 9.26100

**Example 3:**

**Input:** x = 2.00000, n = -2
**Output:** 0.25000
**Explanation:** 2\-2 = 1/22 = 1/4 = 0.25

**Constraints:**

*   `-100.0 < x < 100.0`
*   `-231 <= n <= 231-1`
*   `n` is an integer.
*   `-104 <= xn <= 104`

## A solution in Java

```java
double myPow(double x, int n) {
    if (n == 0) return 1;
    if (n < 0) {
        x = 1 / x;
        n = -n;
    }
    double result = 1;
    double currentProduct = x;
    for (long i = n; i > 0; i /= 2) {
        if ((i % 2) == 1) {
            result *= currentProduct;
        }
        currentProduct *= currentProduct;
    }
    return result;
}
```
The algorithm uses the binary exponentiation technique, which is a faster method of calculating x^n compared to the naive approach. It relies on the process of repeatedly multiplying the current product by itself and updating it after each iteration. The loop iterates through the bits of the exponent n, from the least significant to the most significant. If the current bit of n is 1, the result is multiplied by the current product. At the end of the loop, the current product is updated by squaring it. This process continues until all bits of the exponent have been processed.

The time complexity of the algorithm is O(log(n)) because the loop iterates through the bits of n, and the number of bits in n is proportional to the logarithm of n. The space complexity is O(1), as the space used by the temporary variables does not depend on the size of n.

## A solution in C++

```cpp
double myPow(double x, int n) {
    if (n == 0) return 1;
    if (n < 0) {
        x = 1 / x;
        n = -n;
    }
    double result = 1;
    double currentProduct = x;
    for (long long i = n; i; i /= 2) {
        if ((i % 2) == 1) {
            result = result * currentProduct;
        }
        currentProduct = currentProduct * currentProduct;
    }
    return result;
}
```
The algorithm uses the binary exponentiation technique, which is a faster method of calculating x^n compared to the naive approach. It relies on the process of repeatedly multiplying the current product by itself and updating it after each iteration. The loop iterates through the bits of the exponent n, from the least significant to the most significant. If the current bit of n is 1, the result is multiplied by the current product. At the end of the loop, the current product is updated by squaring it. This process continues until all bits of the exponent have been processed.

The time complexity of the algorithm is O(log(n)) because the loop iterates through the bits of n, and the number of bits in n is proportional to the logarithm of n. The space complexity is O(1), as the space used by the temporary variables does not depend on the size of n.

## A solution in Python

```python
def myPow(x: float, n: int) -> float:
    if n == 0:
        return 1
    if n < 0:
        x = 1 / x
        n = -n
    result = 1
    currentProduct = x
    i = n
    while i:
        if i % 2 == 1:
            result *= currentProduct
        currentProduct *= currentProduct
        i //= 2
    return result
```
The algorithm uses the binary exponentiation technique, which is a faster method of calculating x^n compared to the naive approach. It relies on the process of repeatedly multiplying the current product by itself and updating it after each iteration. The loop iterates through the bits of the exponent n, from the least significant to the most significant. If the current bit of n is 1, the result is multiplied by the current product. At the end of the loop, the current product is updated by squaring it. This process continues until all bits of the exponent have been processed.

The time complexity of the algorithm is O(log(n)) because the loop iterates through the bits of n, and the number of bits in n is proportional to the logarithm of n. The space complexity is O(1), as the space used by the temporary variables does not depend on the size of n.

## A solution in Javascript

```javascript
function myPow(x, n) {
    if (n === 0) return 1;
    if (n < 0) {
        x = 1 / x;
        n = -n;
    }
    let result = 1;
    let currentProduct = x;
    for (let i = n; i > 0; i = Math.floor(i / 2)) {
        if (i % 2 === 1) {
            result *= currentProduct;
        }
        currentProduct *= currentProduct;
    }
    return result;
}
```
The algorithm uses the binary exponentiation technique, which is a faster method of calculating x^n compared to the naive approach. It relies on the process of repeatedly multiplying the current product by itself and updating it after each iteration. The loop iterates through the bits of the exponent n, from the least significant to the most significant. If the current bit of n is 1, the result is multiplied by the current product. At the end of the loop, the current product is updated by squaring it. This process continues until all bits of the exponent have been processed.

The time complexity of the algorithm is O(log(n)) because the loop iterates through the bits of n, and the number of bits in n is proportional to the logarithm of n. The space complexity is O(1), as the space used by the temporary variables does not depend on the size of n.


# N-Queens

- slug: n-queens
- difficulty: Hard

The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.

Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**.

Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.

**Example 1:**

**Input:** n = 4
**Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\]
**Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above

**Example 2:**

**Input:** n = 1
**Output:** \[\[ "Q "\]\]

**Constraints:**

*   `1 <= n <= 9`

## A solution in Java

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

public List<List<String>> solveNQueens(int n) {
    List<List<String>> result = new ArrayList<>();
    solve(result, new ArrayList<>(), n, 0);
    return result;
}

private void solve(List<List<String>> result, List<Integer> current, int n, int col) {
    if (col == n) {
        result.add(generateBoard(current, n));
        return;
    }
    for (int row = 0; row < n; row++) {
        if(isSafe(current, row, col)) {
            current.add(row);
            solve(result, current, n, col + 1);
            current.remove(col);
        }
    }
}

private boolean isSafe(List<Integer> current, int row, int col) {
    for (int i = 0; i < col; i++) {
        int prevRow = current.get(i);
        if (prevRow == row || (Math.abs(col - i) == Math.abs(row - prevRow))) {
            return false;
        }
    }
    return true;
}

private List<String> generateBoard(List<Integer> current, int n) {
    List<String> board = new ArrayList<>();
    for (int row : current) {
        StringBuilder sb = new StringBuilder();
        for (int col = 0; col < n; col++)
            sb.append((col == row) ? "Q" : ".");
        board.add(sb.toString());
    }
    return board;
}
```
The algorithm uses the backtracking approach to solve the N-Queens puzzle. The idea is to place queens one by one in different columns, starting from the leftmost column. When placing a queen, check if that position is safe from all previously placed queens in terms of the horizontal, diagonal, and anti-diagonal directions. If the selected position is safe, move on to the next column and try to place another queen there. If no safe positions are found in the current column, then go back to the previous column and move the queen to another safe position. Repeat this process until all queens are placed in a valid configuration or all possible arrangements have been tried. During the process, whenever we successfully place `n` queens on the board, add that configuration to our result list. Finally, return the list of all unique solutions found.

## A solution in C++

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

bool isSafe(const std::vector<std::string>& board, int row, int col, int n) {
    for (int i = 0; i < col; ++i) {
        if (board[row][i] == 'Q') return false;
    }
    for (int i = row, j = col; i >= 0 && j >= 0; --i, --j) {
        if (board[i][j] == 'Q') return false;
    }
    for (int i = row, j = col; i < n && j >= 0; ++i, --j) {
        if (board[i][j] == 'Q') return false;
    }
    return true;
}

void solve(std::vector<std::vector<std::string>>& result, std::vector<std::string>& board, int n, int col) {
    if (col == n) {
        result.push_back(board);
        return;
    }
    for (int row = 0; row < n; ++row) {
        if (isSafe(board, row, col, n)) {
            board[row][col] = 'Q';
            solve(result, board, n, col + 1);
            board[row][col] = '.';
        }
    }
}

std::vector<std::vector<std::string>> solveNQueens(int n) {
    std::vector<std::vector<std::string>> result;
    std::vector<std::string> board(n, std::string(n, '.'));
    solve(result, board, n, 0);
    return result;
}
```
The algorithm uses the backtracking approach to solve the N-Queens puzzle. The idea is to place queens one by one in different columns, starting from the leftmost column. When placing a queen, check if that position is safe from all previously placed queens in terms of the horizontal, diagonal, and anti-diagonal directions. If the selected position is safe, move on to the next column and try to place another queen there. If no safe positions are found in the current column, then go back to the previous column and move the queen to another safe position. Repeat this process until all queens are placed in a valid configuration or all possible arrangements have been tried. During the process, whenever we successfully place `n` queens on the board, add that configuration to our result list. Finally, return the list of all unique solutions found.

## A solution in Python

```python
def solveNQueens(n):
    def isSafe(board, row, col):
        for i in range(col):
            if board[row][i] == 'Q': return False
        i, j = row, col
        while i >= 0 and j >= 0:
            if board[i][j] == 'Q': return False
            i, j = i - 1, j - 1
        i, j = row, col
        while i < n and j >= 0:
            if board[i][j] == 'Q': return False
            i, j = i + 1, j - 1
        return True

    def solve(result, board, n, col):
        if col == n:
            result.append(board.copy())
            return
        for row in range(n):
            if isSafe(board, row, col):
                board[row] = board[row][:col] + 'Q' + board[row][col + 1:]
                solve(result, board, n, col + 1)
                board[row] = board[row][:col] + '.' + board[row][col + 1:]

    result, board = [], ['.' * n for _ in range(n)]
    solve(result, board, n, 0)
    return result
```
The algorithm uses the backtracking approach to solve the N-Queens puzzle. The idea is to place queens one by one in different columns, starting from the leftmost column. When placing a queen, check if that position is safe from all previously placed queens in terms of the horizontal, diagonal, and anti-diagonal directions. If the selected position is safe, move on to the next column and try to place another queen there. If no safe positions are found in the current column, then go back to the previous column and move the queen to another safe position. Repeat this process until all queens are placed in a valid configuration or all possible arrangements have been tried. During the process, whenever we successfully place `n` queens on the board, add that configuration to our result list. Finally, return the list of all unique solutions found.

## A solution in Javascript

```javascript
function solveNQueens(n) {
  function isSafe(board, row, col) {
    for (let i = 0; i < col; i++)
      if (board[row][i] == 'Q') return false;
    for (let i = row, j = col; i >= 0 && j >= 0; i--, j--)
      if (board[i][j] == 'Q') return false;
    for (let i = row, j = col; i < n && j >= 0; i++, j--)
      if (board[i][j] == 'Q') return false;
    return true;
  }

  function solve(result, board, n, col) {
    if (col == n) {
      result.push(board.map(row => row.join('')));
      return;
    }
    for (let row = 0; row < n; row++) {
      if (isSafe(board, row, col)) {
        board[row][col] = 'Q';
        solve(result, board, n, col + 1);
        board[row][col] = '.';
      }
    }
  }

  const result = [];
  const board = Array.from({ length: n }, () => Array(n).fill('.'));
  solve(result, board, n, 0);
  return result;
}
```
The algorithm uses the backtracking approach to solve the N-Queens puzzle. The idea is to place queens one by one in different columns, starting from the leftmost column. When placing a queen, check if that position is safe from all previously placed queens in terms of the horizontal, diagonal, and anti-diagonal directions. If the selected position is safe, move on to the next column and try to place another queen there. If no safe positions are found in the current column, then go back to the previous column and move the queen to another safe position. Repeat this process until all queens are placed in a valid configuration or all possible arrangements have been tried. During the process, whenever we successfully place `n` queens on the board, add that configuration to our result list. Finally, return the list of all unique solutions found.


# N-Queens II

- slug: n-queens-ii
- difficulty: Hard

The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.

Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_.

**Example 1:**

**Input:** n = 4
**Output:** 2
**Explanation:** There are two distinct solutions to the 4-queens puzzle as shown.

**Example 2:**

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

**Constraints:**

*   `1 <= n <= 9`

## A solution in Java

```java
import java.util.ArrayList;

public int totalNQueens(int n) {
    ArrayList<Integer> cols = new ArrayList<>();
    return backtrack(n, cols);
}

public int backtrack(int n, ArrayList<Integer> cols) {
    if (cols.size() == n) {
        return 1;
    }

    int count = 0;
    for (int i = 0; i < n; i++) {
        if (isSafe(cols, i)) {
            cols.add(i);
            count += backtrack(n, cols);
            cols.remove(cols.size() - 1);
        }
    }
    return count;
}

public boolean isSafe(ArrayList<Integer> cols, int row) {
    int col = cols.size();
    for (int i = 0; i < cols.size(); i++) {
        if (cols.get(i) == row || Math.abs(i - col) == Math.abs(cols.get(i) - row)) {
            return false;
        }
    }
    return true;
}
```
The algorithm recursively places queens on columns and checks if the placement is safe, i.e., no queens are attacking each other.
1. Maintain an array `cols` storing the row indices of placed queens. The index in this array represents the column the queen is placed in. This ensures that no two queens are placed in the same column.
2. Recursively place queens (column-wise).
3. Check for a safe position for each queen in the current column:
   a. Check for same row (`cols[i] == row`).
   b. Check for diagonal attack (`abs(i - col) == abs(cols[i] - row)`).
4. If the current position is safe, place the queen in the current column at the current row position, and continue to place the next queen.
5. If all queens are placed, increment the solution count.
6. If the recursive call finishes, backtrack by removing the queen from the current column and move on to the next row in the same column.
7. The base case is when the `cols` size equals `n`, meaning all queens have been placed safely; increment the count.

This approach considers all possible configurations for placing the n queens while avoiding visiting invalid configurations. It uses backtracking to explore the state space efficiently. The algorithm finds the number of distinct solutions to the n-queens puzzle.

## A solution in C++

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

bool isSafe(vector<int> &cols, int row) {
    int col = cols.size();
    for (int i = 0; i < cols.size(); i++) {
        if (cols[i] == row || abs(i - col) == abs(cols[i] - row)) {
            return false;
        }
    }
    return true;
}

void backtrack(int n, vector<int> &cols, int &count) {
    if (cols.size() == n) {
        count++;
        return;
    }

    for (int i = 0; i < n; i++) {
        if (isSafe(cols, i)) {
            cols.push_back(i);
            backtrack(n, cols, count);
            cols.pop_back();
        }
    }
}

int totalNQueens(int n) {
    vector<int> cols;
    int count = 0;
    backtrack(n, cols, count);
    return count;
}
```
The algorithm recursively places queens on columns and checks if the placement is safe, i.e., no queens are attacking each other.
1. Maintain an array `cols` storing the row indices of placed queens. The index in this array represents the column the queen is placed in. This ensures that no two queens are placed in the same column.
2. Recursively place queens (column-wise).
3. Check for a safe position for each queen in the current column:
   a. Check for same row (`cols[i] == row`).
   b. Check for diagonal attack (`abs(i - col) == abs(cols[i] - row)`).
4. If the current position is safe, place the queen in the current column at the current row position, and continue to place the next queen.
5. If all queens are placed, increment the solution count.
6. If the recursive call finishes, backtrack by removing the queen from the current column and move on to the next row in the same column.
7. The base case is when the `cols` size equals `n`, meaning all queens have been placed safely; increment the count.

This approach considers all possible configurations for placing the n queens while avoiding visiting invalid configurations. It uses backtracking to explore the state space efficiently. The algorithm finds the number of distinct solutions to the n-queens puzzle.

## A solution in Python

```python
def is_safe(cols, row):
    col = len(cols)
    for i, r in enumerate(cols):
        if r == row or abs(i - col) == abs(r - row):
            return False
    return True

def backtrack(n, cols):
    if len(cols) == n:
        return 1

    count = 0
    for i in range(n):
        if is_safe(cols, i):
            cols.append(i)
            count += backtrack(n, cols)
            cols.pop()

    return count

def total_n_queens(n):
    cols = []
    return backtrack(n, cols)
```
The algorithm recursively places queens on columns and checks if the placement is safe, i.e., no queens are attacking each other.
1. Maintain an array `cols` storing the row indices of placed queens. The index in this array represents the column the queen is placed in. This ensures that no two queens are placed in the same column.
2. Recursively place queens (column-wise).
3. Check for a safe position for each queen in the current column:
   a. Check for same row (`cols[i] == row`).
   b. Check for diagonal attack (`abs(i - col) == abs(cols[i] - row)`).
4. If the current position is safe, place the queen in the current column at the current row position, and continue to place the next queen.
5. If all queens are placed, increment the solution count.
6. If the recursive call finishes, backtrack by removing the queen from the current column and move on to the next row in the same column.
7. The base case is when the `cols` size equals `n`, meaning all queens have been placed safely; increment the count.

This approach considers all possible configurations for placing the n queens while avoiding visiting invalid configurations. It uses backtracking to explore the state space efficiently. The algorithm finds the number of distinct solutions to the n-queens puzzle.

## A solution in Javascript

```javascript
function isSafe(cols, row) {
    let col = cols.length;
    for (let i = 0; i < cols.length; i++) {
        if (cols[i] === row || Math.abs(i - col) === Math.abs(cols[i] - row)) {
            return false;
        }
    }
    return true;
}

function backtrack(n, cols) {
    if (cols.length === n) {
        return 1;
    }

    let count = 0;
    for (let i = 0; i < n; i++) {
        if (isSafe(cols, i)) {
            cols.push(i);
            count += backtrack(n, cols);
            cols.pop();
        }
    }
    return count;
}

function totalNQueens(n) {
    let cols = [];
    return backtrack(n, cols);
}
```
The algorithm recursively places queens on columns and checks if the placement is safe, i.e., no queens are attacking each other.
1. Maintain an array `cols` storing the row indices of placed queens. The index in this array represents the column the queen is placed in. This ensures that no two queens are placed in the same column.
2. Recursively place queens (column-wise).
3. Check for a safe position for each queen in the current column:
   a. Check for same row (`cols[i] == row`).
   b. Check for diagonal attack (`abs(i - col) == abs(cols[i] - row)`).
4. If the current position is safe, place the queen in the current column at the current row position, and continue to place the next queen.
5. If all queens are placed, increment the solution count.
6. If the recursive call finishes, backtrack by removing the queen from the current column and move on to the next row in the same column.
7. The base case is when the `cols` size equals `n`, meaning all queens have been placed safely; increment the count.

This approach considers all possible configurations for placing the n queens while avoiding visiting invalid configurations. It uses backtracking to explore the state space efficiently. The algorithm finds the number of distinct solutions to the n-queens puzzle.


# Maximum Subarray

- slug: maximum-subarray
- difficulty: Medium

Given an integer array `nums`, find the subarray with the largest sum, and return _its sum_.

**Example 1:**

**Input:** nums = \[-2,1,-3,4,-1,2,1,-5,4\]
**Output:** 6
**Explanation:** The subarray \[4,-1,2,1\] has the largest sum 6.

**Example 2:**

**Input:** nums = \[1\]
**Output:** 1
**Explanation:** The subarray \[1\] has the largest sum 1.

**Example 3:**

**Input:** nums = \[5,4,-1,7,8\]
**Output:** 23
**Explanation:** The subarray \[5,4,-1,7,8\] has the largest sum 23.

**Constraints:**

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

**Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle.

## A solution in Java

```java
public int maxSubArray(int[] nums) {
    int max_sum = nums[0];
    int current_sum = max_sum;

    for (int i = 1; i < nums.length; i++) {
        current_sum = Math.max(current_sum + nums[i], nums[i]);
        max_sum = Math.max(max_sum, current_sum);
    }

    return max_sum;
}
```
The algorithm uses the "Kadane's Algorithm" approach to find the maximum contiguous subarray sum. It iterates through the given array once and tracks the maximum sum found so far and the current sum.

For each element, we compare the sum of the current_sum with the element itself, and select the maximum of the two. This helps us to decide whether to continue the current contiguous subarray or start a new one from that element. Then, we compare the new current_sum with our global max_sum, and update max_sum if we find a larger value.

In the end, max_sum contains the largest sum of the contiguous subarray.

Time complexity: O(n)
Space complexity: O(1)

## A solution in C++

```cpp
int maxSubArray(vector<int>& nums) {
    int max_sum = nums[0];
    int current_sum = max_sum;

    for (int i = 1; i < nums.size(); i++) {
        current_sum = max(current_sum + nums[i], nums[i]);
        max_sum = max(max_sum, current_sum);
    }

    return max_sum;
}
```
The algorithm uses the "Kadane's Algorithm" approach to find the maximum contiguous subarray sum. It iterates through the given array once and tracks the maximum sum found so far and the current sum.

For each element, we compare the sum of the current_sum with the element itself, and select the maximum of the two. This helps us to decide whether to continue the current contiguous subarray or start a new one from that element. Then, we compare the new current_sum with our global max_sum, and update max_sum if we find a larger value.

In the end, max_sum contains the largest sum of the contiguous subarray.

Time complexity: O(n)
Space complexity: O(1)

## A solution in Python

```python
def maxSubArray(nums):
    max_sum = current_sum = nums[0]

    for num in nums[1:]:
        current_sum = max(current_sum + num, num)
        max_sum = max(max_sum, current_sum)

    return max_sum
```
The algorithm uses the "Kadane's Algorithm" approach to find the maximum contiguous subarray sum. It iterates through the given array once and tracks the maximum sum found so far and the current sum.

For each element, we compare the sum of the current_sum with the element itself, and select the maximum of the two. This helps us to decide whether to continue the current contiguous subarray or start a new one from that element. Then, we compare the new current_sum with our global max_sum, and update max_sum if we find a larger value.

In the end, max_sum contains the largest sum of the contiguous subarray.

Time complexity: O(n)
Space complexity: O(1)

## A solution in Javascript

```javascript
function maxSubArray(nums) {
    let max_sum = nums[0];
    let current_sum = max_sum;

    for (let i = 1; i < nums.length; i++) {
        current_sum = Math.max(current_sum + nums[i], nums[i]);
        max_sum = Math.max(max_sum, current_sum);
    }

    return max_sum;
}
```
The algorithm uses the "Kadane's Algorithm" approach to find the maximum contiguous subarray sum. It iterates through the given array once and tracks the maximum sum found so far and the current sum.

For each element, we compare the sum of the current_sum with the element itself, and select the maximum of the two. This helps us to decide whether to continue the current contiguous subarray or start a new one from that element. Then, we compare the new current_sum with our global max_sum, and update max_sum if we find a larger value.

In the end, max_sum contains the largest sum of the contiguous subarray.

Time complexity: O(n)
Space complexity: O(1)


# Spiral Matrix

- slug: spiral-matrix
- difficulty: Medium

Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.

**Example 1:**

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

**Example 2:**

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

**Constraints:**

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

## A solution in Java

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

public List<Integer> spiralOrder(int[][] matrix) {
    List<Integer> result = new ArrayList<>();
    if (matrix == null || matrix.length == 0) return result;
    int m = matrix.length, n = matrix[0].length;
    int rowStart = 0, colStart = 0, rowEnd = m - 1, colEnd = n - 1;

    while (rowStart <= rowEnd && colStart <= colEnd) {
        for (int i = colStart; i <= colEnd; i++) {
            result.add(matrix[rowStart][i]);
        }
        rowStart++;
        for (int i = rowStart; i <= rowEnd; i++) {
            result.add(matrix[i][colEnd]);
        }
        colEnd--;
        if (rowStart <= rowEnd) {
            for (int i = colEnd; i >= colStart; i--) {
                result.add(matrix[rowEnd][i]);
            }
        }
        rowEnd--;
        if (colStart <= colEnd) {
            for (int i = rowEnd; i >= rowStart; i--) {
                result.add(matrix[i][colStart]);
            }
        }
        colStart++;
    }
    return result;
}
```
The algorithm iterates over the matrix in a spiral order. Initialize the indices to keep track of the matrix boundaries. The algorithm goes from left to right, from top to bottom, from right to left, and then from bottom to top. With each iteration, update the matrix boundaries. The process continues until the row and column boundaries cross each other.

## A solution in C++

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

vector<int> spiralOrder(vector<vector<int>>& matrix) {
    vector<int> result;
    if (matrix.empty()) return result;
    int m = matrix.size(), n = matrix[0].size();
    int rowStart = 0, colStart = 0, rowEnd = m - 1, colEnd = n - 1;

    while (rowStart <= rowEnd && colStart <= colEnd) {
        for (int i = colStart; i <= colEnd; ++i) {
            result.push_back(matrix[rowStart][i]);
        }
        rowStart++;
        for (int i = rowStart; i <= rowEnd; ++i) {
            result.push_back(matrix[i][colEnd]);
        }
        colEnd--;
        if (rowStart <= rowEnd) {
            for (int i = colEnd; i >= colStart; --i) {
                result.push_back(matrix[rowEnd][i]);
            }
        }
        rowEnd--;
        if (colStart <= colEnd) {
            for (int i = rowEnd; i >= rowStart; --i) {
                result.push_back(matrix[i][colStart]);
            }
        }
        colStart++;
    }
    return result;
}
```
The algorithm iterates over the matrix in a spiral order. Initialize the indices to keep track of the matrix boundaries. The algorithm goes from left to right, from top to bottom, from right to left, and then from bottom to top. With each iteration, update the matrix boundaries. The process continues until the row and column boundaries cross each other.

## A solution in Python

```python
def spiralOrder(matrix):
    result = []
    if not matrix: return result
    m, n = len(matrix), len(matrix[0])
    rowStart, colStart, rowEnd, colEnd = 0, 0, m - 1, n - 1

    while rowStart <= rowEnd and colStart <= colEnd:
        for i in range(colStart, colEnd + 1):
            result.append(matrix[rowStart][i])
        rowStart += 1

        for i in range(rowStart, rowEnd + 1):
            result.append(matrix[i][colEnd])
        colEnd -= 1

        if rowStart <= rowEnd:
            for i in range(colEnd, colStart - 1, -1):
                result.append(matrix[rowEnd][i])
        rowEnd -= 1

        if colStart <= colEnd:
            for i in range(rowEnd, rowStart - 1, -1):
                result.append(matrix[i][colStart])
        colStart += 1

    return result
```
The algorithm iterates over the matrix in a spiral order. Initialize the indices to keep track of the matrix boundaries. The algorithm goes from left to right, from top to bottom, from right to left, and then from bottom to top. With each iteration, update the matrix boundaries. The process continues until the row and column boundaries cross each other.

## A solution in Javascript

```javascript
function spiralOrder(matrix) {
    const result = [];
    if (!matrix.length) return result;
    let m = matrix.length, n = matrix[0].length;
    let rowStart = 0, colStart = 0, rowEnd = m - 1, colEnd = n - 1;

    while (rowStart <= rowEnd && colStart <= colEnd) {
        for (let i = colStart; i <= colEnd; i++) {
            result.push(matrix[rowStart][i]);
        }
        rowStart++;
        for (let i = rowStart; i <= rowEnd; i++) {
            result.push(matrix[i][colEnd]);
        }
        colEnd--;
        if (rowStart <= rowEnd) {
            for (let i = colEnd; i >= colStart; i--) {
                result.push(matrix[rowEnd][i]);
            }
        }
        rowEnd--;
        if (colStart <= colEnd) {
            for (let i = rowEnd; i >= rowStart; i--) {
                result.push(matrix[i][colStart]);
            }
        }
        colStart++;
    }
    return result;
}
```
The algorithm iterates over the matrix in a spiral order. Initialize the indices to keep track of the matrix boundaries. The algorithm goes from left to right, from top to bottom, from right to left, and then from bottom to top. With each iteration, update the matrix boundaries. The process continues until the row and column boundaries cross each other.


# Jump Game

- slug: jump-game
- difficulty: Medium

You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position.

Return `true` _if you can reach the last index, or_ `false` _otherwise_.

**Example 1:**

**Input:** nums = \[2,3,1,1,4\]
**Output:** true
**Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index.

**Example 2:**

**Input:** nums = \[3,2,1,0,4\]
**Output:** false
**Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

**Constraints:**

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

## A solution in Java

```java
public boolean canJump(int[] nums) {
    int maxReach = 0;
    for (int i = 0; i < nums.length; ++i) {
        if (i > maxReach) return false;
        maxReach = Math.max(maxReach, i + nums[i]);
    }
    return true;
}
```
The algorithm iterates through the `nums` array, keeping track of the maximum reachable index in `maxReach`. In each iteration, it compares the current index `i` with `maxReach`. If `i` is greater than `maxReach`, it means that the last index cannot be reached. Otherwise, it updates the `maxReach` by taking the maximum value between the current `maxReach` and the sum of the current index `i` and the value of `nums[i]`. If the end of iteration is reached, it means that the last index can be reached, so the function returns true.

## A solution in C++

```cpp
bool canJump(vector<int>& nums) {
    int maxReach = 0;
    for (int i = 0; i < nums.size(); ++i) {
        if (i > maxReach) return false;
        maxReach = max(maxReach, i + nums[i]);
    }
    return true;
}
```
The algorithm iterates through the `nums` array, keeping track of the maximum reachable index in `maxReach`. In each iteration, it compares the current index `i` with `maxReach`. If `i` is greater than `maxReach`, it means that the last index cannot be reached. Otherwise, it updates the `maxReach` by taking the maximum value between the current `maxReach` and the sum of the current index `i` and the value of `nums[i]`. If the end of iteration is reached, it means that the last index can be reached, so the function returns true.

## A solution in Python

```python
def canJump(nums):
    max_reach = 0
    for i, num in enumerate(nums):
        if i > max_reach:
            return False
        max_reach = max(max_reach, i + num)
    return True
```
The algorithm iterates through the `nums` array, keeping track of the maximum reachable index in `maxReach`. In each iteration, it compares the current index `i` with `maxReach`. If `i` is greater than `maxReach`, it means that the last index cannot be reached. Otherwise, it updates the `maxReach` by taking the maximum value between the current `maxReach` and the sum of the current index `i` and the value of `nums[i]`. If the end of iteration is reached, it means that the last index can be reached, so the function returns true.

## A solution in Javascript

```javascript
function canJump(nums) {
    let maxReach = 0;
    for (let i = 0; i < nums.length; ++i) {
        if (i > maxReach) return false;
        maxReach = Math.max(maxReach, i + nums[i]);
    }
    return true;
}
```
The algorithm iterates through the `nums` array, keeping track of the maximum reachable index in `maxReach`. In each iteration, it compares the current index `i` with `maxReach`. If `i` is greater than `maxReach`, it means that the last index cannot be reached. Otherwise, it updates the `maxReach` by taking the maximum value between the current `maxReach` and the sum of the current index `i` and the value of `nums[i]`. If the end of iteration is reached, it means that the last index can be reached, so the function returns true.


# Merge Intervals

- slug: merge-intervals
- difficulty: Medium

Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.

**Example 1:**

**Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\]
**Output:** \[\[1,6\],\[8,10\],\[15,18\]\]
**Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\].

**Example 2:**

**Input:** intervals = \[\[1,4\],\[4,5\]\]
**Output:** \[\[1,5\]\]
**Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping.

**Constraints:**

*   `1 <= intervals.length <= 104`
*   `intervals[i].length == 2`
*   `0 <= starti <= endi <= 104`

## A solution in Java

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

public List<int[]> merge(int[][] intervals) {
    if (intervals.length == 0) return new ArrayList<>();

    Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
    List<int[]> result = new ArrayList<>();
    result.add(intervals[0]);

    for (int i = 1; i < intervals.length; i++) {
        if (result.get(result.size() - 1)[1] >= intervals[i][0]) {
            result.get(result.size() - 1)[1] = Math.max(result.get(result.size() - 1)[1], intervals[i][1]);
        } else {
            result.add(intervals[i]);
        }
    }

    return result;
}
```
The algorithm first sorts the intervals based on their start time. Then, it initializes an empty list `result` to store the merged intervals, and adds the first interval to `result`. Next, it iterates through the remaining intervals, comparing the end time of the last interval in `result` to the start time of the current interval. If they overlap (i.e., the end time of the last interval in `result` is greater than or equal to the start time of the current interval), then the end time of the last interval in `result` is updated to the maximum of its own end time and the end time of the current interval. Otherwise, the current interval is added to `result`. The process continues until all intervals have been processed, and `result` contains the merged, non-overlapping intervals covering the input intervals.

## A solution in C++

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

std::vector<std::vector<int>> merge(std::vector<std::vector<int>>& intervals) {
    if (intervals.empty()) return {};

    std::sort(intervals.begin(), intervals.end());
    std::vector<std::vector<int>> result;
    result.push_back(intervals[0]);

    for (int i = 1; i < intervals.size(); i++) {
        if (result.back()[1] >= intervals[i][0]) {
            result.back()[1] = std::max(result.back()[1], intervals[i][1]);
        } else {
            result.push_back(intervals[i]);
        }
    }

    return result;
}
```
The algorithm first sorts the intervals based on their start time. Then, it initializes an empty list `result` to store the merged intervals, and adds the first interval to `result`. Next, it iterates through the remaining intervals, comparing the end time of the last interval in `result` to the start time of the current interval. If they overlap (i.e., the end time of the last interval in `result` is greater than or equal to the start time of the current interval), then the end time of the last interval in `result` is updated to the maximum of its own end time and the end time of the current interval. Otherwise, the current interval is added to `result`. The process continues until all intervals have been processed, and `result` contains the merged, non-overlapping intervals covering the input intervals.

## A solution in Python

```python
def merge(intervals):
    if not intervals:
        return []

    intervals.sort()
    result = [intervals[0]]

    for i in range(1, len(intervals)):
        if result[-1][1] >= intervals[i][0]:
            result[-1][1] = max(result[-1][1], intervals[i][1])
        else:
            result.append(intervals[i])

    return result
```
The algorithm first sorts the intervals based on their start time. Then, it initializes an empty list `result` to store the merged intervals, and adds the first interval to `result`. Next, it iterates through the remaining intervals, comparing the end time of the last interval in `result` to the start time of the current interval. If they overlap (i.e., the end time of the last interval in `result` is greater than or equal to the start time of the current interval), then the end time of the last interval in `result` is updated to the maximum of its own end time and the end time of the current interval. Otherwise, the current interval is added to `result`. The process continues until all intervals have been processed, and `result` contains the merged, non-overlapping intervals covering the input intervals.

## A solution in Javascript

```javascript
function merge(intervals) {
    if (intervals.length === 0) return [];

    intervals.sort((a, b) => a[0] - b[0]);
    const result = [intervals[0]];

    for (let i = 1; i < intervals.length; i++) {
        if (result[result.length - 1][1] >= intervals[i][0]) {
            result[result.length - 1][1] = Math.max(result[result.length - 1][1], intervals[i][1]);
        } else {
            result.push(intervals[i]);
        }
    }

    return result;
}
```
The algorithm first sorts the intervals based on their start time. Then, it initializes an empty list `result` to store the merged intervals, and adds the first interval to `result`. Next, it iterates through the remaining intervals, comparing the end time of the last interval in `result` to the start time of the current interval. If they overlap (i.e., the end time of the last interval in `result` is greater than or equal to the start time of the current interval), then the end time of the last interval in `result` is updated to the maximum of its own end time and the end time of the current interval. Otherwise, the current interval is added to `result`. The process continues until all intervals have been processed, and `result` contains the merged, non-overlapping intervals covering the input intervals.


# Insert Interval

- slug: insert-interval
- difficulty: Medium

You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval.

Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary).

Return `intervals` _after the insertion_.

**Example 1:**

**Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\]
**Output:** \[\[1,5\],\[6,9\]\]

**Example 2:**

**Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\]
**Output:** \[\[1,2\],\[3,10\],\[12,16\]\]
**Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\].

**Constraints:**

*   `0 <= intervals.length <= 104`
*   `intervals[i].length == 2`
*   `0 <= starti <= endi <= 105`
*   `intervals` is sorted by `starti` in **ascending** order.
*   `newInterval.length == 2`
*   `0 <= start <= end <= 105`

## A solution in Java

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

public List<int[]> insert(int[][] intervals, int[] newInterval) {
    List<int[]> result = new ArrayList<>();
    int start_pos = 0;

    while (start_pos < intervals.length && intervals[start_pos][1] < newInterval[0]) {
        result.add(intervals[start_pos]);
        start_pos++;
    }

    while (start_pos < intervals.length && intervals[start_pos][0] <= newInterval[1]) {
        newInterval[0] = Math.min(newInterval[0], intervals[start_pos][0]);
        newInterval[1] = Math.max(newInterval[1], intervals[start_pos][1]);
        start_pos++;
    }

    result.add(newInterval);

    while (start_pos < intervals.length) {
        result.add(intervals[start_pos]);
        start_pos++;
    }

    return result;
}
```
The algorithm to merge the new interval starts by exploring the non-overlapping intervals before the new one as we are given a sorted list of intervals. We add the explored intervals that came before to the result. After that, we continue exploring intervals that overlap with the new interval and continuously merging them. We update the new interval's starting and ending points according to the merging process until no overlapping intervals remain. We add the merged interval to the result list, and finally, we add the rest of the original intervals present after the new interval. The result will be a merged list of intervals.

## A solution in C++

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

vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
    vector<vector<int>> result;
    int start_pos = 0;

    while (start_pos < intervals.size() && intervals[start_pos][1] < newInterval[0]) {
        result.push_back(intervals[start_pos]);
        start_pos++;
    }

    while (start_pos < intervals.size() && intervals[start_pos][0] <= newInterval[1]) {
        newInterval[0] = min(newInterval[0], intervals[start_pos][0]);
        newInterval[1] = max(newInterval[1], intervals[start_pos][1]);
        start_pos++;
    }

    result.push_back(newInterval);

    while (start_pos < intervals.size()) {
        result.push_back(intervals[start_pos]);
        start_pos++;
    }

    return result;
}
```
The algorithm to merge the new interval starts by exploring the non-overlapping intervals before the new one as we are given a sorted list of intervals. We add the explored intervals that came before to the result. After that, we continue exploring intervals that overlap with the new interval and continuously merging them. We update the new interval's starting and ending points according to the merging process until no overlapping intervals remain. We add the merged interval to the result list, and finally, we add the rest of the original intervals present after the new interval. The result will be a merged list of intervals.

## A solution in Python

```python
from typing import List

def insert(intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
    result = []
    start_pos = 0

    while start_pos < len(intervals) and intervals[start_pos][1] < newInterval[0]:
        result.append(intervals[start_pos])
        start_pos += 1

    while start_pos < len(intervals) and intervals[start_pos][0] <= newInterval[1]:
        newInterval[0] = min(newInterval[0], intervals[start_pos][0])
        newInterval[1] = max(newInterval[1], intervals[start_pos][1])
        start_pos += 1

    result.append(newInterval)

    while start_pos < len(intervals):
        result.append(intervals[start_pos])
        start_pos += 1

    return result
```
The algorithm to merge the new interval starts by exploring the non-overlapping intervals before the new one as we are given a sorted list of intervals. We add the explored intervals that came before to the result. After that, we continue exploring intervals that overlap with the new interval and continuously merging them. We update the new interval's starting and ending points according to the merging process until no overlapping intervals remain. We add the merged interval to the result list, and finally, we add the rest of the original intervals present after the new interval. The result will be a merged list of intervals.

## A solution in Javascript

```javascript
function insert(intervals, newInterval) {
    const result = [];
    let start_pos = 0;

    while (start_pos < intervals.length && intervals[start_pos][1] < newInterval[0]) {
        result.push(intervals[start_pos]);
        start_pos++;
    }

    while (start_pos < intervals.length && intervals[start_pos][0] <= newInterval[1]) {
        newInterval[0] = Math.min(newInterval[0], intervals[start_pos][0]);
        newInterval[1] = Math.max(newInterval[1], intervals[start_pos][1]);
        start_pos++;
    }

    result.push(newInterval);

    while (start_pos < intervals.length) {
        result.push(intervals[start_pos]);
        start_pos++;
    }

    return result;
}
```
The algorithm to merge the new interval starts by exploring the non-overlapping intervals before the new one as we are given a sorted list of intervals. We add the explored intervals that came before to the result. After that, we continue exploring intervals that overlap with the new interval and continuously merging them. We update the new interval's starting and ending points according to the merging process until no overlapping intervals remain. We add the merged interval to the result list, and finally, we add the rest of the original intervals present after the new interval. The result will be a merged list of intervals.


# Length of Last Word

- slug: length-of-last-word
- difficulty: Easy

Given a string `s` consisting of words and spaces, return _the length of the **last** word in the string._

A **word** is a maximal substring consisting of non-space characters only.

**Example 1:**

**Input:** s =  "Hello World "
**Output:** 5
**Explanation:** The last word is  "World " with length 5.

**Example 2:**

**Input:** s =  "   fly me   to   the moon   "
**Output:** 4
**Explanation:** The last word is  "moon " with length 4.

**Example 3:**

**Input:** s =  "luffy is still joyboy "
**Output:** 6
**Explanation:** The last word is  "joyboy " with length 6.

**Constraints:**

*   `1 <= s.length <= 104`
*   `s` consists of only English letters and spaces `' '`.
*   There will be at least one word in `s`.

## A solution in Java

```java
public int lengthOfLastWord(String s) {
    int length = 0;
    int tail = s.length() - 1;
    while (tail >= 0 && s.charAt(tail) == ' ') tail--;
    while (tail >= 0 && s.charAt(tail) != ' ') {
        length++;
        tail--;
    }
    return length;
}
```
The algorithm for finding the length of the last word in a string containing multiple words separated by spaces is as follows:

1. Initialize variables for the length of the last word and the tail (i.e., the end) of the input string.
2. Traverse the string in reverse order to find the start of the last word by checking if a character is a space. Skip all spaces found.
3. Continue traversing the string in reverse order and record the length of the last word until a space is encountered or the start of the string is reached.
4. Return the length of the last word.

This algorithm is implemented in each of the given programming languages (C++, Java, Python, and JavaScript) with the appropriate syntax and variable initialization. The functions are named `lengthOfLastWord` for C++, Java, and JavaScript, and `length_of_last_word` for Python.

## A solution in C++

```cpp
int lengthOfLastWord(string s) {
    int length = 0;
    int tail = s.length() - 1;
    while (tail >= 0 && s[tail] == ' ') tail--;
    while (tail >= 0 && s[tail] != ' ') {
        length++;
        tail--;
    }
    return length;
}
```
The algorithm for finding the length of the last word in a string containing multiple words separated by spaces is as follows:

1. Initialize variables for the length of the last word and the tail (i.e., the end) of the input string.
2. Traverse the string in reverse order to find the start of the last word by checking if a character is a space. Skip all spaces found.
3. Continue traversing the string in reverse order and record the length of the last word until a space is encountered or the start of the string is reached.
4. Return the length of the last word.

This algorithm is implemented in each of the given programming languages (C++, Java, Python, and JavaScript) with the appropriate syntax and variable initialization. The functions are named `lengthOfLastWord` for C++, Java, and JavaScript, and `length_of_last_word` for Python.

## A solution in Python

```python
def length_of_last_word(s: str) -> int:
    length = 0
    tail = len(s) - 1
    while tail >= 0 and s[tail] == ' ':
        tail -= 1
    while tail >= 0 and s[tail] != ' ':
        length += 1
        tail -= 1
    return length
```
The algorithm for finding the length of the last word in a string containing multiple words separated by spaces is as follows:

1. Initialize variables for the length of the last word and the tail (i.e., the end) of the input string.
2. Traverse the string in reverse order to find the start of the last word by checking if a character is a space. Skip all spaces found.
3. Continue traversing the string in reverse order and record the length of the last word until a space is encountered or the start of the string is reached.
4. Return the length of the last word.

This algorithm is implemented in each of the given programming languages (C++, Java, Python, and JavaScript) with the appropriate syntax and variable initialization. The functions are named `lengthOfLastWord` for C++, Java, and JavaScript, and `length_of_last_word` for Python.

## A solution in Javascript

```javascript
function lengthOfLastWord(s) {
    let length = 0;
    let tail = s.length - 1;
    while (tail >= 0 && s[tail] === ' ') tail--;
    while (tail >= 0 && s[tail] !== ' ') {
        length++;
        tail--;
    }
    return length;
}
```
The algorithm for finding the length of the last word in a string containing multiple words separated by spaces is as follows:

1. Initialize variables for the length of the last word and the tail (i.e., the end) of the input string.
2. Traverse the string in reverse order to find the start of the last word by checking if a character is a space. Skip all spaces found.
3. Continue traversing the string in reverse order and record the length of the last word until a space is encountered or the start of the string is reached.
4. Return the length of the last word.

This algorithm is implemented in each of the given programming languages (C++, Java, Python, and JavaScript) with the appropriate syntax and variable initialization. The functions are named `lengthOfLastWord` for C++, Java, and JavaScript, and `length_of_last_word` for Python.


# Spiral Matrix II

- slug: spiral-matrix-ii
- difficulty: Medium

Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order.

**Example 1:**

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

**Example 2:**

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

**Constraints:**

*   `1 <= n <= 20`

## A solution in Java

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

public int[][] generateMatrix(int n) {
    int[][] matrix = new int[n][n];
    int value = 1, top = 0, bottom = n - 1, left = 0, right = n - 1;

    while (value <= n * n) {
        for (int i = left; i <= right; i++) {
            matrix[top][i] = value++;
        }

        for (int i = top + 1; i <= bottom; i++) {
            matrix[i][right] = value++;
        }

        if (top < bottom && left < right) {
            for (int i = right - 1; i >= left; i--) {
                matrix[bottom][i] = value++;
            }

            for (int i = bottom - 1; i > top; i--) {
                matrix[i][left] = value++;
            }
        }

        top++; bottom--; left++; right--;
    }

    return matrix;
}
```
The algorithm initializes an n x n matrix and defines variables to maintain the current top (row), bottom (row), left (column), and right (column) positions. The algorithm then loops through the four sides of the outer square/boundary of the matrix in clockwise order (top row left to right, right column top to bottom, bottom row right to left, left column bottom to top) and fills the elements with the numbers in sequence from 1 to n². After completing a boundary, update the top, bottom, left, and right variables to point to the next inner square/boundary, and repeat the process until every position in the matrix has been filled.

## A solution in C++

```cpp
#include <vector>

std::vector<std::vector<int>> generateMatrix(int n) {
    std::vector<std::vector<int>> matrix(n, std::vector<int>(n));
    int value = 1, top = 0, bottom = n - 1, left = 0, right = n - 1;

    while (value <= n * n) {
        for (int i = left; i <= right; i++) {
            matrix[top][i] = value++;
        }

        for (int i = top + 1; i <= bottom; i++) {
            matrix[i][right] = value++;
        }

        if (top < bottom && left < right) {
            for (int i = right - 1; i >= left; i--) {
                matrix[bottom][i] = value++;
            }

            for (int i = bottom - 1; i > top; i--) {
                matrix[i][left] = value++;
            }
        }

        top++, bottom--, left++, right--;
    }

    return matrix;
}
```
The algorithm initializes an n x n matrix and defines variables to maintain the current top (row), bottom (row), left (column), and right (column) positions. The algorithm then loops through the four sides of the outer square/boundary of the matrix in clockwise order (top row left to right, right column top to bottom, bottom row right to left, left column bottom to top) and fills the elements with the numbers in sequence from 1 to n². After completing a boundary, update the top, bottom, left, and right variables to point to the next inner square/boundary, and repeat the process until every position in the matrix has been filled.

## A solution in Python

```python
def generateMatrix(n: int) -> List[List[int]]:
    matrix = [[0] * n for _ in range(n)]
    value, top, bottom, left, right = 1, 0, n - 1, 0, n - 1

    while value <= n * n:
        for i in range(left, right + 1):
            matrix[top][i] = value
            value += 1

        for i in range(top + 1, bottom + 1):
            matrix[i][right] = value
            value += 1

        if top < bottom and left < right:
            for i in range(right - 1, left - 1, -1):
                matrix[bottom][i] = value
                value += 1

            for i in range(bottom - 1, top, -1):
                matrix[i][left] = value
                value += 1

        top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1

    return matrix
```
The algorithm initializes an n x n matrix and defines variables to maintain the current top (row), bottom (row), left (column), and right (column) positions. The algorithm then loops through the four sides of the outer square/boundary of the matrix in clockwise order (top row left to right, right column top to bottom, bottom row right to left, left column bottom to top) and fills the elements with the numbers in sequence from 1 to n². After completing a boundary, update the top, bottom, left, and right variables to point to the next inner square/boundary, and repeat the process until every position in the matrix has been filled.

## A solution in Javascript

```javascript
function generateMatrix(n) {
    const matrix = Array.from({ length: n }, () => new Array(n).fill(0));
    let value = 1, top = 0, bottom = n - 1, left = 0, right = n - 1;

    while (value <= n * n) {
        for (let i = left; i <= right; i++) {
            matrix[top][i] = value++;
        }

        for (let i = top + 1; i <= bottom; i++) {
            matrix[i][right] = value++;
        }

        if (top < bottom && left < right) {
            for (let i = right - 1; i >= left; i--) {
                matrix[bottom][i] = value++;
            }

            for (let i = bottom - 1; i > top; i--) {
                matrix[i][left] = value++;
            }
        }

        top++, bottom--, left++, right--;
    }

    return matrix;
}
```
The algorithm initializes an n x n matrix and defines variables to maintain the current top (row), bottom (row), left (column), and right (column) positions. The algorithm then loops through the four sides of the outer square/boundary of the matrix in clockwise order (top row left to right, right column top to bottom, bottom row right to left, left column bottom to top) and fills the elements with the numbers in sequence from 1 to n². After completing a boundary, update the top, bottom, left, and right variables to point to the next inner square/boundary, and repeat the process until every position in the matrix has been filled.


# Permutation Sequence

- slug: permutation-sequence
- difficulty: Hard

The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations.

By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`:

1.  `"123 "`
2.  `"132 "`
3.  `"213 "`
4.  `"231 "`
5.  `"312 "`
6.  `"321 "`

Given `n` and `k`, return the `kth` permutation sequence.

**Example 1:**

**Input:** n = 3, k = 3
**Output:** "213"

**Example 2:**

**Input:** n = 4, k = 9
**Output:** "2314"

**Example 3:**

**Input:** n = 3, k = 1
**Output:** "123"

**Constraints:**

*   `1 <= n <= 9`
*   `1 <= k <= n!`

## A solution in Java

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

public String getPermutation(int n, int k) {
    List<Integer> nums = new ArrayList<>();
    int[] factorials = new int[n];
    StringBuilder sb = new StringBuilder();
    int index;

    factorials[0] = 1;
    for (int i = 1; i <= n; ++i) {
        nums.add(i);
        factorials[i - 1] = i * factorials[i - 1];
    }

    k--;

    for (int i = n; i >= 1; --i) {
        index = k / factorials[i - 1];
        k %= factorials[i - 1];
        sb.append(nums.get(index));
        nums.remove(index);
    }

    return sb.toString();
}
```
The algorithm uses factorials and a list of available numbers to construct the kth permutation.

First, we precompute the factorials up to n using a loop.

Next, we initialize an array or list of available numbers, from 1 to n.

Then, we iterate from n down to 1, calculating the index of the current number in the available list to be included in the resulting permutation. We can calculate it as follows: `index = (k - 1) // factorials[i - 1]`.

After, we update the value of k to: `k %= factorials[i - 1]`.

At each step, we append or concatenate the chosen number to the result and remove it from the list of available numbers.

Finally, we return the result as a string.

## A solution in C++

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

std::string getPermutation(int n, int k) {
    std::vector<int> factorials(n, 1);
    std::vector<char> nums(n, '1');
    std::string result;
    int index;

    for (int i = 1; i <= n; ++i) {
        nums[i - 1] += i - 1;
        factorials[i - 1] *= i;
    }

    k--;

    for (int i = n; i >= 1; --i) {
        index = k / factorials[i - 1];
        k %= factorials[i - 1];
        result.push_back(nums[index]);
        nums.erase(nums.begin() + index);
    }

    return result;
}
```
The algorithm uses factorials and a list of available numbers to construct the kth permutation.

First, we precompute the factorials up to n using a loop.

Next, we initialize an array or list of available numbers, from 1 to n.

Then, we iterate from n down to 1, calculating the index of the current number in the available list to be included in the resulting permutation. We can calculate it as follows: `index = (k - 1) // factorials[i - 1]`.

After, we update the value of k to: `k %= factorials[i - 1]`.

At each step, we append or concatenate the chosen number to the result and remove it from the list of available numbers.

Finally, we return the result as a string.

## A solution in Python

```python
def getPermutation(n, k):
    factorials = [1]
    nums = list(range(1, n + 1))
    result = []

    for i in range(1, n):
        factorials.append(factorials[-1] * i)

    k -= 1

    for i in range(n, 0, -1):
        index = k // factorials[i - 1]
        k %= factorials[i - 1]
        result.append(str(nums.pop(index)))

    return ''.join(result)
```
The algorithm uses factorials and a list of available numbers to construct the kth permutation.

First, we precompute the factorials up to n using a loop.

Next, we initialize an array or list of available numbers, from 1 to n.

Then, we iterate from n down to 1, calculating the index of the current number in the available list to be included in the resulting permutation. We can calculate it as follows: `index = (k - 1) // factorials[i - 1]`.

After, we update the value of k to: `k %= factorials[i - 1]`.

At each step, we append or concatenate the chosen number to the result and remove it from the list of available numbers.

Finally, we return the result as a string.

## A solution in Javascript

```javascript
function getPermutation(n, k) {
    const factorials = [1];
    const nums = [...Array(n)].map((_, i) => i + 1);
    let result = '';

    for (let i = 1; i < n; i++) {
        factorials[i] = factorials[i - 1] * i;
    }

    k--;

    for (let i = n; i >= 1; i--) {
        const index = Math.floor(k / factorials[i - 1]);
        k %= factorials[i - 1];
        result += nums[index];
        nums.splice(index, 1);
    }

    return result;
}
```
The algorithm uses factorials and a list of available numbers to construct the kth permutation.

First, we precompute the factorials up to n using a loop.

Next, we initialize an array or list of available numbers, from 1 to n.

Then, we iterate from n down to 1, calculating the index of the current number in the available list to be included in the resulting permutation. We can calculate it as follows: `index = (k - 1) // factorials[i - 1]`.

After, we update the value of k to: `k %= factorials[i - 1]`.

At each step, we append or concatenate the chosen number to the result and remove it from the list of available numbers.

Finally, we return the result as a string.


# Rotate List

- slug: rotate-list
- difficulty: Medium

Given the `head` of a linked list, rotate the list to the right by `k` places.

**Example 1:**

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

**Example 2:**

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

**Constraints:**

*   The number of nodes in the list is in the range `[0, 500]`.
*   `-100 <= Node.val <= 100`
*   `0 <= k <= 2 * 109`

## A solution in Java

```java
public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) {
        this.val = val;
    }
    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public ListNode rotateRight(ListNode head, int k) {
    if (head == null || head.next == null || k == 0) return head;

    ListNode current = head;
    int len = 1;
    while (current.next != null) {
        len++;
        current = current.next;
    }
    current.next = head;
    k = len - k % len;

    while (k-- > 0) {
        current = current.next;
    }
    head = current.next;
    current.next = null;

    return head;
}
```
The algorithm first finds the length of the linked list by iterating through it. It then calculates the actual number of rotations needed, considering that if `k` is equal to or larger than the length of the linked list, the same rotation will be repeated. To minimize the rotations, we find the remainder of `k` divided by the length of the list.

Next, we connect the tail of the linked list to the head, forming a circular linked list. Following this, we iterate again through the list and perform the rotations by updating the pointers of the new head and tail. Finally, we break the cycle in the list and return the new head.

## A solution in C++

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

};

ListNode* rotateRight(ListNode* head, int k) {
    if (!head || !head->next || k == 0) return head;

    ListNode *current = head;
    int len = 1;
    while (current->next) {
        len++;
        current = current->next;
    }
    current->next = head;
    k = len - k % len;

    while (k--) {
        current = current->next;
    }
    head = current->next;
    current->next = nullptr;

    return head;
}
```
The algorithm first finds the length of the linked list by iterating through it. It then calculates the actual number of rotations needed, considering that if `k` is equal to or larger than the length of the linked list, the same rotation will be repeated. To minimize the rotations, we find the remainder of `k` divided by the length of the list.

Next, we connect the tail of the linked list to the head, forming a circular linked list. Following this, we iterate again through the list and perform the rotations by updating the pointers of the new head and tail. Finally, we break the cycle in the list and return the new head.

## A solution in Python

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

def rotateRight(head, k):
    if not head or not head.next or k == 0:
        return head

    current = head
    length = 1
    while current.next:
        length += 1
        current = current.next
    current.next = head
    k = length - k % length

    while k:
        k -= 1
        current = current.next
    head = current.next
    current.next = None

    return head
```
The algorithm first finds the length of the linked list by iterating through it. It then calculates the actual number of rotations needed, considering that if `k` is equal to or larger than the length of the linked list, the same rotation will be repeated. To minimize the rotations, we find the remainder of `k` divided by the length of the list.

Next, we connect the tail of the linked list to the head, forming a circular linked list. Following this, we iterate again through the list and perform the rotations by updating the pointers of the new head and tail. Finally, we break the cycle in the list and return the new head.

## A solution in Javascript

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

function rotateRight(head, k) {
    if (!head || !head.next || k === 0) return head;

    let current = head;
    let len = 1;
    while (current.next) {
        len++;
        current = current.next;
    }
    current.next = head;
    k = len - k % len;

    while (k--) {
        current = current.next;
    }
    head = current.next;
    current.next = null;

    return head;
}
```
The algorithm first finds the length of the linked list by iterating through it. It then calculates the actual number of rotations needed, considering that if `k` is equal to or larger than the length of the linked list, the same rotation will be repeated. To minimize the rotations, we find the remainder of `k` divided by the length of the list.

Next, we connect the tail of the linked list to the head, forming a circular linked list. Following this, we iterate again through the list and perform the rotations by updating the pointers of the new head and tail. Finally, we break the cycle in the list and return the new head.


# Unique Paths

- slug: unique-paths
- difficulty: Medium

There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.

Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.

The test cases are generated so that the answer will be less than or equal to `2 * 109`.

**Example 1:**

**Input:** m = 3, n = 7
**Output:** 28

**Example 2:**

**Input:** m = 3, n = 2
**Output:** 3
**Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down

**Constraints:**

*   `1 <= m, n <= 100`

## A solution in Java

```java
public int uniquePaths(int m, int n) {
    int[][] dp = new int[m][n];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (i == 0 || j == 0) {
                dp[i][j] = 1;
            } else {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
            }
        }
    }
    return dp[m - 1][n - 1];
}
```
The idea is to use dynamic programming to solve this problem. We create a 2D array `dp` with dimensions `m` x `n` to store the number of unique paths to reach each cell in the grid.

Initially, we fill out the first row and first column of the `dp` array with 1 since there is only one way to reach any cell in the first row or first column: by moving either right along the first row or down along the first column.

Then, for every other cell in the `dp` array, we can calculate the number of unique paths to that cell by summing the number of unique paths to the cell above it and to the cell to its left. We can do this because the robot can only move down or right, so the paths to the current cell must have come from those two directions.

Finally, we return the value at the bottom-right corner of the `dp` array, which represents the number of unique paths the robot can take to reach the destination.

## A solution in C++

```cpp
int uniquePaths(int m, int n) {
    vector<vector<int>> dp(m, vector<int>(n, 1));
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
        }
    }
    return dp[m - 1][n - 1];
}
```
The idea is to use dynamic programming to solve this problem. We create a 2D array `dp` with dimensions `m` x `n` to store the number of unique paths to reach each cell in the grid.

Initially, we fill out the first row and first column of the `dp` array with 1 since there is only one way to reach any cell in the first row or first column: by moving either right along the first row or down along the first column.

Then, for every other cell in the `dp` array, we can calculate the number of unique paths to that cell by summing the number of unique paths to the cell above it and to the cell to its left. We can do this because the robot can only move down or right, so the paths to the current cell must have come from those two directions.

Finally, we return the value at the bottom-right corner of the `dp` array, which represents the number of unique paths the robot can take to reach the destination.

## A solution in Python

```python
def uniquePaths(m, n):
    dp = [[1] * n for _ in range(m)]
    for i in range(1, m):
        for j in range(1, n):
            dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
    return dp[m - 1][n - 1]
```
The idea is to use dynamic programming to solve this problem. We create a 2D array `dp` with dimensions `m` x `n` to store the number of unique paths to reach each cell in the grid.

Initially, we fill out the first row and first column of the `dp` array with 1 since there is only one way to reach any cell in the first row or first column: by moving either right along the first row or down along the first column.

Then, for every other cell in the `dp` array, we can calculate the number of unique paths to that cell by summing the number of unique paths to the cell above it and to the cell to its left. We can do this because the robot can only move down or right, so the paths to the current cell must have come from those two directions.

Finally, we return the value at the bottom-right corner of the `dp` array, which represents the number of unique paths the robot can take to reach the destination.

## A solution in Javascript

```javascript
function uniquePaths(m, n) {
    const dp = Array.from({ length: m }, () => Array(n).fill(1));
    for (let i = 1; i < m; i++) {
        for (let j = 1; j < n; j++) {
            dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
        }
    }
    return dp[m - 1][n - 1];
}
```
The idea is to use dynamic programming to solve this problem. We create a 2D array `dp` with dimensions `m` x `n` to store the number of unique paths to reach each cell in the grid.

Initially, we fill out the first row and first column of the `dp` array with 1 since there is only one way to reach any cell in the first row or first column: by moving either right along the first row or down along the first column.

Then, for every other cell in the `dp` array, we can calculate the number of unique paths to that cell by summing the number of unique paths to the cell above it and to the cell to its left. We can do this because the robot can only move down or right, so the paths to the current cell must have come from those two directions.

Finally, we return the value at the bottom-right corner of the `dp` array, which represents the number of unique paths the robot can take to reach the destination.


# Unique Paths II

- slug: unique-paths-ii
- difficulty: Medium

You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.

An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle.

Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.

The testcases are generated so that the answer will be less than or equal to `2 * 109`.

**Example 1:**

**Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** 2
**Explanation:** There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

**Example 2:**

**Input:** obstacleGrid = \[\[0,1\],\[0,0\]\]
**Output:** 1

**Constraints:**

*   `m == obstacleGrid.length`
*   `n == obstacleGrid[i].length`
*   `1 <= m, n <= 100`
*   `obstacleGrid[i][j]` is `0` or `1`.

## A solution in Java

```java
public int uniquePathsWithObstacles(int[][] grid) {
    int m = grid.length;
    int n = grid[0].length;
    if (grid[0][0] == 1) return 0;

    grid[0][0] = 1;
    for (int i = 1; i < m; ++i)
        grid[i][0] = (grid[i][0] == 0 && grid[i - 1][0] == 1) ? 1 : 0;
    for (int i = 1; i < n; ++i)
        grid[0][i] = (grid[0][i] == 0 && grid[0][i - 1] == 1) ? 1 : 0;

    for (int i = 1; i < m; ++i)
        for (int j = 1; j < n; ++j)
            if (grid[i][j] == 0)
                grid[i][j] = grid[i - 1][j] + grid[i][j - 1];
            else
                grid[i][j] = 0;

    return grid[m - 1][n - 1];
}
```
1. If the starting point has an obstacle, return 0 as there is no valid path.
2. Initialize the first cell of the grid as 1 and process the first row and column,
   setting their values to 1 if the cell is not an obstacle and if the previous cell is not an obstacle.
3. Iterate through the grid starting from the second row and column, and for each cell, if it's not an obstacle, set its value to the sum of the values of the cells above it and to its left.
4. Return the value of the bottom-right corner of the grid, which is the number of unique paths.

## A solution in C++

```cpp
int uniquePathsWithObstacles(vector<vector<int>>& grid) {
    int m = grid.size();
    int n = grid[0].size();
    if (grid[0][0] == 1) return 0;

    grid[0][0] = 1;
    for (int i = 1; i < m; ++i)
        grid[i][0] = (grid[i][0] == 0 && grid[i - 1][0] == 1) ? 1 : 0;
    for (int i = 1; i < n; ++i)
        grid[0][i] = (grid[0][i] == 0 && grid[0][i - 1] == 1) ? 1 : 0;

    for (int i = 1; i < m; ++i)
        for (int j = 1; j < n; ++j)
            if (grid[i][j] == 0)
                grid[i][j] = grid[i - 1][j] + grid[i][j - 1];
            else
                grid[i][j] = 0;

    return grid[m - 1][n - 1];
}
```
1. If the starting point has an obstacle, return 0 as there is no valid path.
2. Initialize the first cell of the grid as 1 and process the first row and column,
   setting their values to 1 if the cell is not an obstacle and if the previous cell is not an obstacle.
3. Iterate through the grid starting from the second row and column, and for each cell, if it's not an obstacle, set its value to the sum of the values of the cells above it and to its left.
4. Return the value of the bottom-right corner of the grid, which is the number of unique paths.

## A solution in Python

```python
def uniquePathsWithObstacles(grid):
    m, n = len(grid), len(grid[0])
    if grid[0][0] == 1:
        return 0

    grid[0][0] = 1
    for i in range(1, m):
        grid[i][0] = 1 if grid[i][0] == 0 and grid[i - 1][0] == 1 else 0
    for i in range(1, n):
        grid[0][i] = 1 if grid[0][i] == 0 and grid[0][i - 1] == 1 else 0

    for i in range(1, m):
        for j in range(1, n):
            if grid[i][j] == 0:
                grid[i][j] = grid[i - 1][j] + grid[i][j - 1]
            else:
                grid[i][j] = 0

    return grid[m - 1][n - 1]
```
1. If the starting point has an obstacle, return 0 as there is no valid path.
2. Initialize the first cell of the grid as 1 and process the first row and column,
   setting their values to 1 if the cell is not an obstacle and if the previous cell is not an obstacle.
3. Iterate through the grid starting from the second row and column, and for each cell, if it's not an obstacle, set its value to the sum of the values of the cells above it and to its left.
4. Return the value of the bottom-right corner of the grid, which is the number of unique paths.

## A solution in Javascript

```javascript
function uniquePathsWithObstacles(grid) {
    const m = grid.length;
    const n = grid[0].length;
    if (grid[0][0] === 1) return 0;

    grid[0][0] = 1;
    for (let i = 1; i < m; ++i) {
        grid[i][0] = (grid[i][0] === 0 && grid[i - 1][0] === 1) ? 1 : 0;
    }
    for (let i = 1; i < n; ++i) {
        grid[0][i] = (grid[0][i] === 0 && grid[0][i - 1] === 1) ? 1 : 0;
    }

    for (let i = 1; i < m; ++i) {
        for (let j = 1; j < n; ++j) {
            if (grid[i][j] === 0) {
                grid[i][j] = grid[i - 1][j] + grid[i][j - 1];
            } else {
                grid[i][j] = 0;
            }
        }
    }

    return grid[m - 1][n - 1];
}
```
1. If the starting point has an obstacle, return 0 as there is no valid path.
2. Initialize the first cell of the grid as 1 and process the first row and column,
   setting their values to 1 if the cell is not an obstacle and if the previous cell is not an obstacle.
3. Iterate through the grid starting from the second row and column, and for each cell, if it's not an obstacle, set its value to the sum of the values of the cells above it and to its left.
4. Return the value of the bottom-right corner of the grid, which is the number of unique paths.


# Minimum Path Sum

- slug: minimum-path-sum
- difficulty: Medium

Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.

**Note:** You can only move either down or right at any point in time.

**Example 1:**

**Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\]
**Output:** 7
**Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum.

**Example 2:**

**Input:** grid = \[\[1,2,3\],\[4,5,6\]\]
**Output:** 12

**Constraints:**

*   `m == grid.length`
*   `n == grid[i].length`
*   `1 <= m, n <= 200`
*   `0 <= grid[i][j] <= 100`

## A solution in Java

```java
public int minPathSum(int[][] grid) {
    int m = grid.length, n = grid[0].length;

    for(int i = 1; i < m; i++)
        grid[i][0] += grid[i - 1][0];

    for(int i = 1; i < n; i++)
        grid[0][i] += grid[0][i - 1];

    for(int i = 1; i < m; i++){
        for(int j = 1; j < n; j++){
            grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);
        }
    }
    return grid[m - 1][n - 1];
}
```
The algorithm solves the problem through dynamic programming. It creates a table and fills it by the following rules:
1. The first element of each row will be the sum of its previous row element and its current value.
2. The first element of each column will be the sum of its previous column element and its current value.
3. For all other elements, find the minimum path/components from its top (i-1,j) and left (i,j-1) neighbors, and then add its current value.

At the end of the loop, the bottom right cell contains the minimum path sum from the top left corner to the bottom right corner.

## A solution in C++

```cpp
int minPathSum(vector<vector<int>>& grid) {
    int m = grid.size(), n = grid[0].size();

    for(int i = 1; i < m; i++)
        grid[i][0] += grid[i - 1][0];

    for(int i = 1; i < n; i++)
        grid[0][i] += grid[0][i - 1];

    for(int i = 1; i < m; i++){
        for(int j = 1; j < n; j++){
            grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]);
        }
    }
    return grid[m - 1][n - 1];
}
```
The algorithm solves the problem through dynamic programming. It creates a table and fills it by the following rules:
1. The first element of each row will be the sum of its previous row element and its current value.
2. The first element of each column will be the sum of its previous column element and its current value.
3. For all other elements, find the minimum path/components from its top (i-1,j) and left (i,j-1) neighbors, and then add its current value.

At the end of the loop, the bottom right cell contains the minimum path sum from the top left corner to the bottom right corner.

## A solution in Python

```python
def minPathSum(grid):
    m, n = len(grid), len(grid[0])

    for i in range(1, m):
        grid[i][0] += grid[i - 1][0]

    for i in range(1, n):
        grid[0][i] += grid[0][i - 1]

    for i in range(1, m):
        for j in range(1, n):
            grid[i][j] += min(grid[i - 1][j], grid[i][j - 1])

    return grid[m - 1][n - 1]
```
The algorithm solves the problem through dynamic programming. It creates a table and fills it by the following rules:
1. The first element of each row will be the sum of its previous row element and its current value.
2. The first element of each column will be the sum of its previous column element and its current value.
3. For all other elements, find the minimum path/components from its top (i-1,j) and left (i,j-1) neighbors, and then add its current value.

At the end of the loop, the bottom right cell contains the minimum path sum from the top left corner to the bottom right corner.

## A solution in Javascript

```javascript
function minPathSum(grid) {
    let m = grid.length, n = grid[0].length;

    for(let i = 1; i < m; i++)
        grid[i][0] += grid[i - 1][0];

    for(let i = 1; i < n; i++)
        grid[0][i] += grid[0][i - 1];

    for(let i = 1; i < m; i++){
        for(let j = 1; j < n; j++){
            grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);
        }
    }
    return grid[m - 1][n - 1];
}
```
The algorithm solves the problem through dynamic programming. It creates a table and fills it by the following rules:
1. The first element of each row will be the sum of its previous row element and its current value.
2. The first element of each column will be the sum of its previous column element and its current value.
3. For all other elements, find the minimum path/components from its top (i-1,j) and left (i,j-1) neighbors, and then add its current value.

At the end of the loop, the bottom right cell contains the minimum path sum from the top left corner to the bottom right corner.


# Valid Number

- slug: valid-number
- difficulty: Hard

A **valid number** can be split up into these components (in order):

1.  A **decimal number** or an **integer**.
2.  (Optional) An `'e'` or `'E'`, followed by an **integer**.

A **decimal number** can be split up into these components (in order):

1.  (Optional) A sign character (either `'+'` or `'-'`).
2.  One of the following formats:
    1.  One or more digits, followed by a dot `'.'`.
    2.  One or more digits, followed by a dot `'.'`, followed by one or more digits.
    3.  A dot `'.'`, followed by one or more digits.

An **integer** can be split up into these components (in order):

1.  (Optional) A sign character (either `'+'` or `'-'`).
2.  One or more digits.

For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`.

Given a string `s`, return `true` _if_ `s` _is a **valid number**_.

**Example 1:**

**Input:** s =  "0 "
**Output:** true

**Example 2:**

**Input:** s =  "e "
**Output:** false

**Example 3:**

**Input:** s =  ". "
**Output:** false

**Constraints:**

*   `1 <= s.length <= 20`
*   `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.

## A solution in Java

```java
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Solution {
    public boolean isNumber(String s) {
        String pattern = "^[-+]?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(e[-+]?[0-9]+)?$";
        return Pattern.matches(pattern, s);
    }
}
```
The algorithm utilizes regular expressions to match the input string against a pattern that defines a valid number. The regular expression in this case has the following meaning:

1. `^`: Start of the string
2. `[-+]?`: An optional sign, either `+` or `-`
3. `(`: Start of a group that can be an integer or a decimal
4. `(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))`: Here, a valid number can either have digits before and after the decimal point or only after the decimal point (or only before the decimal point with an optional decimal delimiter).
5. `)`: End of the group
6. `(e[-+]?[0-9]+)?`: An optional scientific notation part, which consists of the letter 'e', followed by an optional sign and at least one digit
7. `$`: End of the string

The regex pattern is constructed to cover all cases according to the problem's description. The function then uses each language's regex library to match the input string against this pattern, returning `true` if the input string matches and `false` otherwise.

## A solution in C++

```cpp
#include <regex>
#include <string>

bool isNumber(const std::string& s) {
    std::regex pattern("^[-+]?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(e[-+]?[0-9]+)?$");
    return std::regex_match(s, pattern);
}
```
The algorithm utilizes regular expressions to match the input string against a pattern that defines a valid number. The regular expression in this case has the following meaning:

1. `^`: Start of the string
2. `[-+]?`: An optional sign, either `+` or `-`
3. `(`: Start of a group that can be an integer or a decimal
4. `(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))`: Here, a valid number can either have digits before and after the decimal point or only after the decimal point (or only before the decimal point with an optional decimal delimiter).
5. `)`: End of the group
6. `(e[-+]?[0-9]+)?`: An optional scientific notation part, which consists of the letter 'e', followed by an optional sign and at least one digit
7. `$`: End of the string

The regex pattern is constructed to cover all cases according to the problem's description. The function then uses each language's regex library to match the input string against this pattern, returning `true` if the input string matches and `false` otherwise.

## A solution in Python

```python
import re

def is_number(s: str) -> bool:
    pattern = re.compile(r'^[-+]?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(e[-+]?[0-9]+)?$')
    return bool(pattern.match(s))
```
The algorithm utilizes regular expressions to match the input string against a pattern that defines a valid number. The regular expression in this case has the following meaning:

1. `^`: Start of the string
2. `[-+]?`: An optional sign, either `+` or `-`
3. `(`: Start of a group that can be an integer or a decimal
4. `(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))`: Here, a valid number can either have digits before and after the decimal point or only after the decimal point (or only before the decimal point with an optional decimal delimiter).
5. `)`: End of the group
6. `(e[-+]?[0-9]+)?`: An optional scientific notation part, which consists of the letter 'e', followed by an optional sign and at least one digit
7. `$`: End of the string

The regex pattern is constructed to cover all cases according to the problem's description. The function then uses each language's regex library to match the input string against this pattern, returning `true` if the input string matches and `false` otherwise.

## A solution in Javascript

```javascript
function isNumber(s) {
    const pattern = /^[-+]?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(e[-+]?[0-9]+)?$/;
    return pattern.test(s);
}
```
The algorithm utilizes regular expressions to match the input string against a pattern that defines a valid number. The regular expression in this case has the following meaning:

1. `^`: Start of the string
2. `[-+]?`: An optional sign, either `+` or `-`
3. `(`: Start of a group that can be an integer or a decimal
4. `(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))`: Here, a valid number can either have digits before and after the decimal point or only after the decimal point (or only before the decimal point with an optional decimal delimiter).
5. `)`: End of the group
6. `(e[-+]?[0-9]+)?`: An optional scientific notation part, which consists of the letter 'e', followed by an optional sign and at least one digit
7. `$`: End of the string

The regex pattern is constructed to cover all cases according to the problem's description. The function then uses each language's regex library to match the input string against this pattern, returning `true` if the input string matches and `false` otherwise.


# Plus One

- slug: plus-one
- difficulty: Easy

You are given a **large integer** represented as an integer array `digits`, where each `digits[i]` is the `ith` digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading `0`'s.

Increment the large integer by one and return _the resulting array of digits_.

**Example 1:**

**Input:** digits = \[1,2,3\]
**Output:** \[1,2,4\]
**Explanation:** The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be \[1,2,4\].

**Example 2:**

**Input:** digits = \[4,3,2,1\]
**Output:** \[4,3,2,2\]
**Explanation:** The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be \[4,3,2,2\].

**Example 3:**

**Input:** digits = \[9\]
**Output:** \[1,0\]
**Explanation:** The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be \[1,0\].

**Constraints:**

*   `1 <= digits.length <= 100`
*   `0 <= digits[i] <= 9`
*   `digits` does not contain any leading `0`'s.

## A solution in Java

```java
public int[] plusOne(int[] digits) {
    int n = digits.length;

    for(int i = n - 1; i >= 0; i--) {
        if(digits[i] < 9) {
            digits[i]++;
            return digits;
        }
        digits[i] = 0;
    }

    int[] newDigits = new int[n + 1];
    newDigits[0] = 1;
    return newDigits;
}
```
We start by iterating through the array from the least significant digit (rightmost) to the most significant digit (leftmost). In each iteration, we check whether the digit is less than 9. If the digit is less than 9, increment it and return the incremented array. If the digit is 9, we set it to 0 and continue the loop to the next most significant digit.

After the loop, if we haven't found any digit less than 9, that means we have a number like 9999...9 which needs to be incremented to 10000...0. So we add a 1 at the beginning of the array (the most significant digit). Finally, we return the incremented array.

## A solution in C++

```cpp
#include <vector>

std::vector<int> plusOne(std::vector<int>& digits) {
    int n = digits.size();

    for(int i = n - 1; i >= 0; i--) {
        if(digits[i] < 9) {
            digits[i]++;
            return digits;
        }
        digits[i] = 0;
    }

    digits.insert(digits.begin(), 1);
    return digits;
}
```
We start by iterating through the array from the least significant digit (rightmost) to the most significant digit (leftmost). In each iteration, we check whether the digit is less than 9. If the digit is less than 9, increment it and return the incremented array. If the digit is 9, we set it to 0 and continue the loop to the next most significant digit.

After the loop, if we haven't found any digit less than 9, that means we have a number like 9999...9 which needs to be incremented to 10000...0. So we add a 1 at the beginning of the array (the most significant digit). Finally, we return the incremented array.

## A solution in Python

```python
def plusOne(digits: List[int]) -> List[int]:
    n = len(digits)

    for i in range(n - 1, -1, -1):
        if digits[i] < 9:
            digits[i] += 1
            return digits
        digits[i] = 0

    digits.insert(0, 1)
    return digits
```
We start by iterating through the array from the least significant digit (rightmost) to the most significant digit (leftmost). In each iteration, we check whether the digit is less than 9. If the digit is less than 9, increment it and return the incremented array. If the digit is 9, we set it to 0 and continue the loop to the next most significant digit.

After the loop, if we haven't found any digit less than 9, that means we have a number like 9999...9 which needs to be incremented to 10000...0. So we add a 1 at the beginning of the array (the most significant digit). Finally, we return the incremented array.

## A solution in Javascript

```javascript
function plusOne(digits) {
    let n = digits.length;

    for(let i = n - 1; i >= 0; i--) {
        if(digits[i] < 9) {
            digits[i]++;
            return digits;
        }
        digits[i] = 0;
    }

    digits.unshift(1);
    return digits;
}
```
We start by iterating through the array from the least significant digit (rightmost) to the most significant digit (leftmost). In each iteration, we check whether the digit is less than 9. If the digit is less than 9, increment it and return the incremented array. If the digit is 9, we set it to 0 and continue the loop to the next most significant digit.

After the loop, if we haven't found any digit less than 9, that means we have a number like 9999...9 which needs to be incremented to 10000...0. So we add a 1 at the beginning of the array (the most significant digit). Finally, we return the incremented array.