# Longest Duplicate Substring

- slug: longest-duplicate-substring
- difficulty: Hard

Given a string `s`, consider all _duplicated substrings_: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.

Return **any** duplicated substring that has the longest possible length. If `s` does not have a duplicated substring, the answer is `" "`.

**Example 1:**

**Input:** s = "banana"
**Output:** "ana"

**Example 2:**

**Input:** s = "abcd"
**Output:** ""

**Constraints:**

*   `2 <= s.length <= 3 * 104`
*   `s` consists of lowercase English letters.

## A solution in Java

```java
import java.util.*;

public List<Character> commonChars(String[] words) {
    Map<Character, Integer> merged = new HashMap<>();

    for (String word : words) {
        Map<Character, Integer> wordMap = new HashMap<>();
        for (char c : word.toCharArray()) {
            wordMap.put(c, wordMap.getOrDefault(c, 0) + 1);
        }
        if (merged.isEmpty()) {
            merged = wordMap;
        } else {
            for (char c : merged.keySet()) {
                merged.put(c, Math.min(merged.get(c), wordMap.getOrDefault(c, 0)));
            }
        }
    }

    List<Character> result = new ArrayList<>();
    for (Map.Entry<Character, Integer> entry : merged.entrySet()) {
        for (int i = 0; i < entry.getValue(); i++) {
            result.add(entry.getKey());
        }
    }
    return result;
}
```
The algorithm follows these steps:

1. Initialize an empty hash_map (C++)/HashMap (Java)/Counter (Python)/Object (JavaScript) `merged` to store the count of characters that appear in all words.
2. Iterate through each word in the input array `words`.
3. For each word, create a map `wordMap` to store the count of each character in the word.
4. If `merged` is empty, set `merged` equal to `wordMap`. Otherwise, update the count of each character in `merged` with the minimum count of the same character in `wordMap`. This ensures that we only keep the count of characters that appear in all words.
5. After iterating through all words, create a result array/list.
6. For each character in `merged`, add the character to the result array/list with its count as the number of duplicates.
7. Return the result array/list.

## A solution in C++

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

std::vector<char> commonChars(std::vector<std::string>& words) {
    std::unordered_map<char, int> merged;
    for (const auto& word : words) {
        std::unordered_map<char, int> word_map;
        for (char c : word) {
            ++word_map[c];
        }
        if (merged.empty()) {
            merged = word_map;
        }
        else {
            for (auto& entry : merged) {
                entry.second = std::min(entry.second, word_map[entry.first]);
            }
        }
    }

    std::vector<char> result;
    for (const auto& entry : merged) {
        for (int i = 0; i < entry.second; ++i) {
            result.push_back(entry.first);
        }
    }
    return result;
}
```
The algorithm follows these steps:

1. Initialize an empty hash_map (C++)/HashMap (Java)/Counter (Python)/Object (JavaScript) `merged` to store the count of characters that appear in all words.
2. Iterate through each word in the input array `words`.
3. For each word, create a map `wordMap` to store the count of each character in the word.
4. If `merged` is empty, set `merged` equal to `wordMap`. Otherwise, update the count of each character in `merged` with the minimum count of the same character in `wordMap`. This ensures that we only keep the count of characters that appear in all words.
5. After iterating through all words, create a result array/list.
6. For each character in `merged`, add the character to the result array/list with its count as the number of duplicates.
7. Return the result array/list.

## A solution in Python

```python
from collections import Counter

def commonChars(words):
    merged = Counter()
    for word in words:
        word_count = Counter(word)
        if not merged:
            merged = word_count
        else:
            for char in merged:
                merged[char] = min(merged[char], word_count[char])

    result = []
    for char, count in merged.items():
        result.extend([char] * count)
    return result
```
The algorithm follows these steps:

1. Initialize an empty hash_map (C++)/HashMap (Java)/Counter (Python)/Object (JavaScript) `merged` to store the count of characters that appear in all words.
2. Iterate through each word in the input array `words`.
3. For each word, create a map `wordMap` to store the count of each character in the word.
4. If `merged` is empty, set `merged` equal to `wordMap`. Otherwise, update the count of each character in `merged` with the minimum count of the same character in `wordMap`. This ensures that we only keep the count of characters that appear in all words.
5. After iterating through all words, create a result array/list.
6. For each character in `merged`, add the character to the result array/list with its count as the number of duplicates.
7. Return the result array/list.

## A solution in Javascript

```javascript
function commonChars(words) {
    let merged = {};

    for (const word of words) {
        let wordMap = {};
        for (const char of word) {
            wordMap[char] = (wordMap[char] || 0) + 1;
        }
        if (Object.keys(merged).length === 0) {
            merged = wordMap;
        } else {
            for (const char in merged) {
                merged[char] = Math.min(merged[char], wordMap[char] || 0);
            }
        }
    }

    let result = [];
    for (const char in merged) {
        for (let i = 0; i < merged[char]; i++) {
            result.push(char);
        }
    }
    return result;
}
```
The algorithm follows these steps:

1. Initialize an empty hash_map (C++)/HashMap (Java)/Counter (Python)/Object (JavaScript) `merged` to store the count of characters that appear in all words.
2. Iterate through each word in the input array `words`.
3. For each word, create a map `wordMap` to store the count of each character in the word.
4. If `merged` is empty, set `merged` equal to `wordMap`. Otherwise, update the count of each character in `merged` with the minimum count of the same character in `wordMap`. This ensures that we only keep the count of characters that appear in all words.
5. After iterating through all words, create a result array/list.
6. For each character in `merged`, add the character to the result array/list with its count as the number of duplicates.
7. Return the result array/list.


# Last Stone Weight

- slug: last-stone-weight
- difficulty: Easy

You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.

We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:

*   If `x == y`, both stones are destroyed, and
*   If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.

At the end of the game, there is **at most one** stone left.

Return _the weight of the last remaining stone_. If there are no stones left, return `0`.

**Example 1:**

**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.

**Example 2:**

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

**Constraints:**

*   `1 <= stones.length <= 30`
*   `1 <= stones[i] <= 1000`

## A solution in Java

```java
public int longestOnes(int[] nums, int k) {
    int left = 0, right = 0, maxOnes = 0, zeroCount = 0;
    while (right < nums.length) {
        if (nums[right] == 0) zeroCount++;
        while (zeroCount > k) {
            if (nums[left] == 0) zeroCount--;
            left++;
        }
        maxOnes = Math.max(maxOnes, right - left + 1);
        right++;
    }
    return maxOnes;
}
```
The algorithm for this problem is a sliding window solution. We iterate through the array, and for each iteration, we check if the current element is a 0. If it is, we increment the zeroCount. If the zeroCount exceeds k, we move the left pointer of the sliding window forwards, checking if the element we are leaving is a 0, and decrementing the zeroCount accordingly. We then calculate and store the maximum consecutive 1's within the sliding window for each iteration, incrementing the right pointer of the sliding window at every step. Finally, we return the maximum consecutive 1's after iterating through the whole array. The algorithm focuses on processing the array in a single pass and adjusting window boundaries accordingly. Each language implementation follows this algorithm and uses similar variable names for convenience.

## A solution in C++

```cpp
int longestOnes(vector<int>& nums, int k) {
    int left = 0, right = 0, maxOnes = 0, zeroCount = 0;
    while (right < nums.size()) {
        if (nums[right] == 0) zeroCount++;
        while (zeroCount > k) {
            if (nums[left] == 0) zeroCount--;
            left++;
        }
        maxOnes = max(maxOnes, right - left + 1);
        right++;
    }
    return maxOnes;
}
```
The algorithm for this problem is a sliding window solution. We iterate through the array, and for each iteration, we check if the current element is a 0. If it is, we increment the zeroCount. If the zeroCount exceeds k, we move the left pointer of the sliding window forwards, checking if the element we are leaving is a 0, and decrementing the zeroCount accordingly. We then calculate and store the maximum consecutive 1's within the sliding window for each iteration, incrementing the right pointer of the sliding window at every step. Finally, we return the maximum consecutive 1's after iterating through the whole array. The algorithm focuses on processing the array in a single pass and adjusting window boundaries accordingly. Each language implementation follows this algorithm and uses similar variable names for convenience.

## A solution in Python

```python
def longestOnes(nums, k):
    left, right, max_ones, zero_count = 0, 0, 0, 0
    while right < len(nums):
        if nums[right] == 0:
            zero_count += 1
        while zero_count > k:
            if nums[left] == 0:
                zero_count -= 1
            left += 1
        max_ones = max(max_ones, right - left + 1)
        right += 1
    return max_ones
```
The algorithm for this problem is a sliding window solution. We iterate through the array, and for each iteration, we check if the current element is a 0. If it is, we increment the zeroCount. If the zeroCount exceeds k, we move the left pointer of the sliding window forwards, checking if the element we are leaving is a 0, and decrementing the zeroCount accordingly. We then calculate and store the maximum consecutive 1's within the sliding window for each iteration, incrementing the right pointer of the sliding window at every step. Finally, we return the maximum consecutive 1's after iterating through the whole array. The algorithm focuses on processing the array in a single pass and adjusting window boundaries accordingly. Each language implementation follows this algorithm and uses similar variable names for convenience.

## A solution in Javascript

```javascript
function longestOnes(nums, k) {
    let left = 0, right = 0, maxOnes = 0, zeroCount = 0;
    while (right < nums.length) {
        if (nums[right] === 0) zeroCount++;
        while (zeroCount > k) {
            if (nums[left] === 0) zeroCount--;
            left++;
        }
        maxOnes = Math.max(maxOnes, right - left + 1);
        right++;
    }
    return maxOnes;
}
```
The algorithm for this problem is a sliding window solution. We iterate through the array, and for each iteration, we check if the current element is a 0. If it is, we increment the zeroCount. If the zeroCount exceeds k, we move the left pointer of the sliding window forwards, checking if the element we are leaving is a 0, and decrementing the zeroCount accordingly. We then calculate and store the maximum consecutive 1's within the sliding window for each iteration, incrementing the right pointer of the sliding window at every step. Finally, we return the maximum consecutive 1's after iterating through the whole array. The algorithm focuses on processing the array in a single pass and adjusting window boundaries accordingly. Each language implementation follows this algorithm and uses similar variable names for convenience.


# Remove All Adjacent Duplicates In String

- slug: remove-all-adjacent-duplicates-in-string
- difficulty: Easy

You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them.

We repeatedly make **duplicate removals** on `s` until we no longer can.

Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**.

**Example 1:**

**Input:** s =  "abbaca "
**Output:**  "ca "
**Explanation:**
For example, in  "abbaca " we could remove  "bb " since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is  "aaca ", of which only  "aa " is possible, so the final string is  "ca ".

**Example 2:**

**Input:** s =  "azxxzy "
**Output:**  "ay "

**Constraints:**

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

## A solution in Java

```java
public int maxSumAfterKOperations(int[] nums, int k) {
    PriorityQueue<Integer> pq = new PriorityQueue<>();
    for(int num : nums) pq.add(num);
    while(k-- > 0){
        int current = pq.poll();
        pq.add(-current);
    }
    int sum = 0;
    for(int num : pq) sum += num;
    return sum;
}
```
1. Create a min-heap from the given integer array nums.
2. Iterate k times and for each iteration, do the following:
   - Pop the smallest element from the min-heap.
   - Negate the popped element and push it back to the min-heap.
3. Calculate the sum of the elements in the min-heap and return it.

Note: In JavaScript, we have also created a PriorityQueue class to achieve the functionality of a priority queue like in other languages.

## A solution in C++

```cpp
int maxSumAfterKOperations(vector<int>& nums, int k) {
    priority_queue<int, vector<int>, greater<int>> pq(nums.begin(), nums.end());
    while(k--){
        int current = pq.top();
        pq.pop();
        pq.push(-current);
    }
    return accumulate(nums.begin(), nums.end(), 0);
}
```
1. Create a min-heap from the given integer array nums.
2. Iterate k times and for each iteration, do the following:
   - Pop the smallest element from the min-heap.
   - Negate the popped element and push it back to the min-heap.
3. Calculate the sum of the elements in the min-heap and return it.

Note: In JavaScript, we have also created a PriorityQueue class to achieve the functionality of a priority queue like in other languages.

## A solution in Python

```python
import heapq

def maxSumAfterKOperations(nums, k):
    heapq.heapify(nums)
    for _ in range(k):
        current = heapq.heappop(nums)
        heapq.heappush(nums, -current)
    return sum(nums)
```
1. Create a min-heap from the given integer array nums.
2. Iterate k times and for each iteration, do the following:
   - Pop the smallest element from the min-heap.
   - Negate the popped element and push it back to the min-heap.
3. Calculate the sum of the elements in the min-heap and return it.

Note: In JavaScript, we have also created a PriorityQueue class to achieve the functionality of a priority queue like in other languages.

## A solution in Javascript

```javascript
function maxSumAfterKOperations(nums, k) {
    const pq = new PriorityQueue(nums, (a, b) => a - b);
    while(k--){
        const current = pq.poll();
        pq.offer(-current);
    }
    let sum = 0;
    while(!pq.isEmpty()){
        sum += pq.poll();
    }
    return sum;
}

class PriorityQueue {
    constructor(data=[], compareFunction=(a, b) => a > b){
        this.data = data;
        this.compareFunction = compareFunction;
        this.heapify();
    }
    heapify(){
        if(this.data.length > 0){
            for(let i=Math.floor(this.size()/2); i>=0; i--){
                this.siftDown(i);
            }
        }
    }
    parent(i){ return Math.floor((i-1)/2);}
    left(i){ return 2*i + 1;}
    right(i){ return 2*i + 2;}
    size(){ return this.data.length;}
    isEmpty(){ return this.size()==0;}
    peek(){ return this.data[0];}
    poll(){
        const extracted = this.data.shift();
        if(!this.isEmpty()){
            this.data.unshift(this.data.pop());
            this.siftDown(0);
        }
        return extracted;
    }
    siftDown(i){
        let minIndex = i;
        const l = this.left(i);
        if(l<this.size() && this.compareFunction(this.data[l], this.data[minIndex])) minIndex = l;
        const r = this.right(i);
        if(r<this.size() && this.compareFunction(this.data[r], this.data[minIndex])) minIndex = r;
        if(i!=minIndex){
            [this.data[i], this.data[minIndex]] = [this.data[minIndex], this.data[i]];
            this.siftDown(minIndex);
        }
    }
    offer(value){
        this.data.push(value);
        this.siftUp(this.size()-1);
    }
    siftUp(i){
        while(i>0 && this.compareFunction(this.data[i], this.data[this.parent(i)])){
            [this.data[i], this.data[this.parent(i)]] = [this.data[this.parent(i)], this.data[i]];
            i = this.parent(i);
        }
    }
}
```
1. Create a min-heap from the given integer array nums.
2. Iterate k times and for each iteration, do the following:
   - Pop the smallest element from the min-heap.
   - Negate the popped element and push it back to the min-heap.
3. Calculate the sum of the elements in the min-heap and return it.

Note: In JavaScript, we have also created a PriorityQueue class to achieve the functionality of a priority queue like in other languages.


# Longest String Chain

- slug: longest-string-chain
- difficulty: Medium

You are given an array of `words` where each word consists of lowercase English letters.

`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.

*   For example, `"abc "` is a **predecessor** of `"abac "`, while `"cba "` is not a **predecessor** of `"bcad "`.

A **word chain** is a sequence of words `[word1, word2, ..., wordk]` with `k >= 1`, where `word1` is a **predecessor** of `word2`, `word2` is a **predecessor** of `word3`, and so on. A single word is trivially a **word chain** with `k == 1`.

Return _the **length** of the **longest possible word chain** with words chosen from the given list of_ `words`.

**Example 1:**

**Input:** words = \[ "a ", "b ", "ba ", "bca ", "bda ", "bdca "\]
**Output:** 4
**Explanation**: One of the longest word chains is \[ "a ", "ba ", "bda ", "bdca "\].

**Example 2:**

**Input:** words = \[ "xbc ", "pcxbcf ", "xb ", "cxbc ", "pcxbc "\]
**Output:** 5
**Explanation:** All the words can be put in a word chain \[ "xb ",  "xbc ",  "cxbc ",  "pcxbc ",  "pcxbcf "\].

**Example 3:**

**Input:** words = \[ "abcd ", "dbqca "\]
**Output:** 1
**Explanation:** The trivial word chain \[ "abcd "\] is one of the longest word chains.
\[ "abcd ", "dbqca "\] is not a valid word chain because the ordering of the letters is changed.

**Constraints:**

*   `1 <= words.length <= 1000`
*   `1 <= words[i].length <= 16`
*   `words[i]` only consists of lowercase English letters.

## A solution in Java

```java
public int clumsy(int n) {
    if (n <= 2) {
        return n;
    }
    if (n == 3) {
        return 6;
    }
    int result = n * (n - 1) / (n - 2) + (n - 3);
    n -= 4;
    while (n >= 4) {
        result = result - (n * (n - 1) / (n - 2)) + (n - 3);
        n -= 4;
    }
    return result - clumsy(n);
}
```
The algorithm starts by checking the base cases for when n is less than or equal to 2 or when n equals 3. Each case returns the appropriate value. Then we initialize the result variable to the first four operations for n. To do this, we perform multiplication and division first, then addition, and any remaining subtraction.

We then decrement n by 4, and enter a loop to continue the clumsy factorial, evaluating the next four operations until n is less than 4. Inside the loop, we do the same operation as before, but subtracting instead of adding the result for each group. We end the loop when n is less than 4.

Finally, we subtract the clumsy factorial of the remaining n (less than 4) from the result and return it. This ensures that the last steps follow the rotation of operations correctly.

## A solution in C++

```cpp
int clumsy(int n) {
    if (n <= 2) {
        return n;
    }
    if (n == 3) {
        return 6;
    }
    int result = n * (n - 1) / (n - 2) + (n - 3);
    n -= 4;
    while (n >= 4) {
        result = result - (n * (n - 1) / (n - 2)) + (n - 3);
        n -= 4;
    }
    return result - clumsy(n);
}
```
The algorithm starts by checking the base cases for when n is less than or equal to 2 or when n equals 3. Each case returns the appropriate value. Then we initialize the result variable to the first four operations for n. To do this, we perform multiplication and division first, then addition, and any remaining subtraction.

We then decrement n by 4, and enter a loop to continue the clumsy factorial, evaluating the next four operations until n is less than 4. Inside the loop, we do the same operation as before, but subtracting instead of adding the result for each group. We end the loop when n is less than 4.

Finally, we subtract the clumsy factorial of the remaining n (less than 4) from the result and return it. This ensures that the last steps follow the rotation of operations correctly.

## A solution in Python

```python
def clumsy(n: int) -> int:
    if n <= 2:
        return n
    if n == 3:
        return 6
    result = n * (n - 1) // (n - 2) + (n - 3)
    n -= 4
    while n >= 4:
        result = result - (n * (n - 1) // (n - 2)) + (n - 3)
        n -= 4
    return result - clumsy(n)
```
The algorithm starts by checking the base cases for when n is less than or equal to 2 or when n equals 3. Each case returns the appropriate value. Then we initialize the result variable to the first four operations for n. To do this, we perform multiplication and division first, then addition, and any remaining subtraction.

We then decrement n by 4, and enter a loop to continue the clumsy factorial, evaluating the next four operations until n is less than 4. Inside the loop, we do the same operation as before, but subtracting instead of adding the result for each group. We end the loop when n is less than 4.

Finally, we subtract the clumsy factorial of the remaining n (less than 4) from the result and return it. This ensures that the last steps follow the rotation of operations correctly.

## A solution in Javascript

```javascript
function clumsy(n) {
    if (n <= 2) {
        return n;
    }
    if (n === 3) {
        return 6;
    }
    let result = Math.floor(n * (n - 1) / (n - 2)) + (n - 3);
    n -= 4;
    while (n >= 4) {
        result = result - Math.floor(n * (n - 1) / (n - 2)) + (n - 3);
        n -= 4;
    }
    return result - clumsy(n);
}
```
The algorithm starts by checking the base cases for when n is less than or equal to 2 or when n equals 3. Each case returns the appropriate value. Then we initialize the result variable to the first four operations for n. To do this, we perform multiplication and division first, then addition, and any remaining subtraction.

We then decrement n by 4, and enter a loop to continue the clumsy factorial, evaluating the next four operations until n is less than 4. Inside the loop, we do the same operation as before, but subtracting instead of adding the result for each group. We end the loop when n is less than 4.

Finally, we subtract the clumsy factorial of the remaining n (less than 4) from the result and return it. This ensures that the last steps follow the rotation of operations correctly.


# Last Stone Weight II

- slug: last-stone-weight-ii
- difficulty: Medium

You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.

We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights `x` and `y` with `x <= y`. The result of this smash is:

*   If `x == y`, both stones are destroyed, and
*   If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.

At the end of the game, there is **at most one** stone left.

Return _the smallest possible weight of the left stone_. If there are no stones left, return `0`.

**Example 1:**

**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We can combine 2 and 4 to get 2, so the array converts to \[2,7,1,8,1\] then,
we can combine 7 and 8 to get 1, so the array converts to \[2,1,1,1\] then,
we can combine 2 and 1 to get 1, so the array converts to \[1,1,1\] then,
we can combine 1 and 1 to get 0, so the array converts to \[1\], then that's the optimal value.

**Example 2:**

**Input:** stones = \[31,26,33,21,40\]
**Output:** 5

**Constraints:**

*   `1 <= stones.length <= 30`
*   `1 <= stones[i] <= 100`

## A solution in Java

```java
public int min_rotations(int[] tops, int[] bottoms) {
    int res = Integer.MAX_VALUE;

    for (int target : new int[] {tops[0], bottoms[0]}) {
        int top_rot = 0, bot_rot = 0;
        for (int i = 0; i < tops.length; ++i) {
            if (tops[i] != target && bottoms[i] != target) {
                top_rot = bot_rot = Integer.MAX_VALUE;
                break;
            }
            top_rot += tops[i] != target ? 1 : 0;
            bot_rot += bottoms[i] != target ? 1 : 0;
        }
        res = Math.min(res, Math.min(top_rot, bot_rot));
    }

    return res == Integer.MAX_VALUE ? -1 : res;
}
```
The algorithm iterates through the given tops and bottoms lists (arrays in C++ and Java). The goal is to check if we can make all values in tops or bottoms the same by swapping tops[i] and bottoms[i] values. We take the first domino's top and bottom values as our initial targets.

For each target value, we initialize `top_rot` and `bot_rot` to store the number of rotations required to make all elements of the tops and bottoms the same. We iterate the tops and bottoms and check if either the top or bottom values are the same as the target. If neither is the target, we set both `top_rot` and `bot_rot` to the maximum possible value, and break from the loop. Otherwise, we increment `top_rot` and/or `bot_rot` accordingly.

After iterating for both targets, we take the minimum of `top_rot`, `bot_rot`, and `res`. If we couldn't find a solution, `res` will remain as the maximum possible value, and we return -1. Otherwise, we return the minimum number of rotations needed.

## A solution in C++

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

int min_rotations(std::vector<int>& tops, std::vector<int>& bottoms) {
    int res = INT_MAX;

    for (int target : {tops[0], bottoms[0]}) {
        int top_rot = 0, bot_rot = 0;
        for (int i = 0; i < tops.size(); ++i) {
            if (tops[i] != target && bottoms[i] != target) {
                top_rot = bot_rot = INT_MAX;
                break;
            }
            top_rot += tops[i] != target;
            bot_rot += bottoms[i] != target;
        }
        res = std::min({res, top_rot, bot_rot});
    }

    return res == INT_MAX ? -1 : res;
}
```
The algorithm iterates through the given tops and bottoms lists (arrays in C++ and Java). The goal is to check if we can make all values in tops or bottoms the same by swapping tops[i] and bottoms[i] values. We take the first domino's top and bottom values as our initial targets.

For each target value, we initialize `top_rot` and `bot_rot` to store the number of rotations required to make all elements of the tops and bottoms the same. We iterate the tops and bottoms and check if either the top or bottom values are the same as the target. If neither is the target, we set both `top_rot` and `bot_rot` to the maximum possible value, and break from the loop. Otherwise, we increment `top_rot` and/or `bot_rot` accordingly.

After iterating for both targets, we take the minimum of `top_rot`, `bot_rot`, and `res`. If we couldn't find a solution, `res` will remain as the maximum possible value, and we return -1. Otherwise, we return the minimum number of rotations needed.

## A solution in Python

```python
def min_rotations(tops, bottoms):
    res = float('inf')

    for target in (tops[0], bottoms[0]):
        top_rot, bot_rot = 0, 0
        for ti, bi in zip(tops, bottoms):
            if ti != target and bi != target:
                top_rot = bot_rot = float('inf')
                break
            top_rot += ti != target
            bot_rot += bi != target

        res = min(res, top_rot, bot_rot)

    return -1 if res == float('inf') else res
```
The algorithm iterates through the given tops and bottoms lists (arrays in C++ and Java). The goal is to check if we can make all values in tops or bottoms the same by swapping tops[i] and bottoms[i] values. We take the first domino's top and bottom values as our initial targets.

For each target value, we initialize `top_rot` and `bot_rot` to store the number of rotations required to make all elements of the tops and bottoms the same. We iterate the tops and bottoms and check if either the top or bottom values are the same as the target. If neither is the target, we set both `top_rot` and `bot_rot` to the maximum possible value, and break from the loop. Otherwise, we increment `top_rot` and/or `bot_rot` accordingly.

After iterating for both targets, we take the minimum of `top_rot`, `bot_rot`, and `res`. If we couldn't find a solution, `res` will remain as the maximum possible value, and we return -1. Otherwise, we return the minimum number of rotations needed.

## A solution in Javascript

```javascript
function min_rotations(tops, bottoms) {
    let res = Infinity;

    let targets = [tops[0], bottoms[0]];

    for (let target of targets) {
        let top_rot = 0;
        let bot_rot = 0;

        for (let i = 0; i < tops.length; ++i) {
            if (tops[i] !== target && bottoms[i] !== target) {
                top_rot = bot_rot = Infinity;
                break;
            }

            if (tops[i] !== target) {
                top_rot++;
            }

            if (bottoms[i] !== target) {
                bot_rot++;
            }
        }
        res = Math.min(res, top_rot, bot_rot);
    }

    return res === Infinity ? -1 : res;
}
```
The algorithm iterates through the given tops and bottoms lists (arrays in C++ and Java). The goal is to check if we can make all values in tops or bottoms the same by swapping tops[i] and bottoms[i] values. We take the first domino's top and bottom values as our initial targets.

For each target value, we initialize `top_rot` and `bot_rot` to store the number of rotations required to make all elements of the tops and bottoms the same. We iterate the tops and bottoms and check if either the top or bottom values are the same as the target. If neither is the target, we set both `top_rot` and `bot_rot` to the maximum possible value, and break from the loop. Otherwise, we increment `top_rot` and/or `bot_rot` accordingly.

After iterating for both targets, we take the minimum of `top_rot`, `bot_rot`, and `res`. If we couldn't find a solution, `res` will remain as the maximum possible value, and we return -1. Otherwise, we return the minimum number of rotations needed.


# Height Checker

- slug: height-checker
- difficulty: Easy

A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in **non-decreasing order** by height. Let this ordering be represented by the integer array `expected` where `expected[i]` is the expected height of the `ith` student in line.

You are given an integer array `heights` representing the **current order** that the students are standing in. Each `heights[i]` is the height of the `ith` student in line (**0-indexed**).

Return _the **number of indices** where_ `heights[i] != expected[i]`.

**Example 1:**

**Input:** heights = \[1,1,4,2,1,3\]
**Output:** 3
**Explanation:**
heights:  \[1,1,4,2,1,3\]
expected: \[1,1,1,2,3,4\]
Indices 2, 4, and 5 do not match.

**Example 2:**

**Input:** heights = \[5,1,2,3,4\]
**Output:** 5
**Explanation:**
heights:  \[5,1,2,3,4\]
expected: \[1,2,3,4,5\]
All indices do not match.

**Example 3:**

**Input:** heights = \[1,2,3,4,5\]
**Output:** 0
**Explanation:**
heights:  \[1,2,3,4,5\]
expected: \[1,2,3,4,5\]
All indices match.

**Constraints:**

*   `1 <= heights.length <= 100`
*   `1 <= heights[i] <= 100`

## A solution in Java

```java
import java.util.Arrays;

public int heightChecker(int[] heights) {
    int[] expected = heights.clone();
    Arrays.sort(expected);

    int count = 0;
    for (int i = 0; i < heights.length; ++i) {
        if (heights[i] != expected[i]) {
            ++count;
        }
    }

    return count;
}
```
1. Create a copy of the input array called expected.
2. Sort the expected array in non-decreasing order.
3. Initialize a counter variable called count to 0.
4. Iterate through the input array with index i.
  4.1. If the element at index i in the input array is not equal to the element at index i in the expected array, increment the count.
5. Return the count.

## A solution in C++

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

int heightChecker(std::vector<int>& heights) {
    std::vector<int> expected = heights;
    std::sort(expected.begin(), expected.end());

    int count = 0;
    for (int i = 0; i < heights.size(); ++i) {
        if (heights[i] != expected[i]) {
            ++count;
        }
    }

    return count;
}
```
1. Create a copy of the input array called expected.
2. Sort the expected array in non-decreasing order.
3. Initialize a counter variable called count to 0.
4. Iterate through the input array with index i.
  4.1. If the element at index i in the input array is not equal to the element at index i in the expected array, increment the count.
5. Return the count.

## A solution in Python

```python
def height_checker(heights):
    expected = sorted(heights)

    count = 0
    for i in range(len(heights)):
        if heights[i] != expected[i]:
            count += 1

    return count
```
1. Create a copy of the input array called expected.
2. Sort the expected array in non-decreasing order.
3. Initialize a counter variable called count to 0.
4. Iterate through the input array with index i.
  4.1. If the element at index i in the input array is not equal to the element at index i in the expected array, increment the count.
5. Return the count.

## A solution in Javascript

```javascript
function heightChecker(heights) {
    const expected = [...heights].sort((a, b) => a - b);

    let count = 0;
    for (let i = 0; i < heights.length; ++i) {
        if (heights[i] !== expected[i]) {
            ++count;
        }
    }

    return count;
}
```
1. Create a copy of the input array called expected.
2. Sort the expected array in non-decreasing order.
3. Initialize a counter variable called count to 0.
4. Iterate through the input array with index i.
  4.1. If the element at index i in the input array is not equal to the element at index i in the expected array, increment the count.
5. Return the count.


# Grumpy Bookstore Owner

- slug: grumpy-bookstore-owner
- difficulty: Medium

There is a bookstore owner that has a store open for `n` minutes. Every minute, some number of customers enter the store. You are given an integer array `customers` of length `n` where `customers[i]` is the number of the customer that enters the store at the start of the `ith` minute and all those customers leave after the end of that minute.

On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where `grumpy[i]` is `1` if the bookstore owner is grumpy during the `ith` minute, and is `0` otherwise.

When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied.

The bookstore owner knows a secret technique to keep themselves not grumpy for `minutes` consecutive minutes, but can only use it once.

Return _the maximum number of customers that can be satisfied throughout the day_.

**Example 1:**

**Input:** customers = \[1,0,1,2,1,1,7,5\], grumpy = \[0,1,0,1,0,1,0,1\], minutes = 3
**Output:** 16
**Explanation:** The bookstore owner keeps themselves not grumpy for the last 3 minutes.
The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.

**Example 2:**

**Input:** customers = \[1\], grumpy = \[0\], minutes = 1
**Output:** 1

**Constraints:**

*   `n == customers.length == grumpy.length`
*   `1 <= minutes <= n <= 2 * 104`
*   `0 <= customers[i] <= 1000`
*   `grumpy[i]` is either `0` or `1`.

## A solution in Java

```java
public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {
    int total_customers = 0, max_extra_customers = 0, extra_customers = 0;
    for (int i = 0; i < customers.length; ++i) {
        if (grumpy[i] == 0) {
            total_customers += customers[i];
        }
        if (i < minutes) {
            extra_customers += customers[i] * grumpy[i];
        } else {
            extra_customers += (customers[i] * grumpy[i]) - (customers[i - minutes] * grumpy[i - minutes]);
        }
        max_extra_customers = Math.max(max_extra_customers, extra_customers);
    }
    return total_customers + max_extra_customers;
}
```
First, we need to calculate the initial sum of satisfied customers which we do by looping through the `customers` array and checking if the bookstore owner is grumpy at that minute, i.e., `grumpy[i] == 0`. If the bookstore owner is not grumpy, we add the customers at that minute to `total_customers`.

Then, we need to find the maximum possible number of extra customers that can be satisfied by using the secret technique for `minutes` minutes. Initialise two variables, `max_extra_customers` and `extra_customers`, to 0. Iterate through the `customers` array again. If the current minute, `i`, is less than `minutes`, increment `extra_customers` by the product of `customers[i]` and `grumpy[i]`. Otherwise, increment `extra_customers` by adding the product of `customers[i]` and `grumpy[i]` and subtracting the product of `customers[i - minutes]` and `grumpy[i - minutes]`.

Update `max_extra_customers` with the maximum of its current value and `extra_customers`. After the iteration, return the sum of `total_customers` and `max_extra_customers` as the maximum number of satisfied customers throughout the day.

## A solution in C++

```cpp
int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int minutes) {
    int total_customers = 0, max_extra_customers = 0, extra_customers = 0;
    for (int i = 0; i < customers.size(); ++i) {
        if (grumpy[i] == 0) {
            total_customers += customers[i];
        }
        if (i < minutes) {
            extra_customers += customers[i] * grumpy[i];
        } else {
            extra_customers += (customers[i] * grumpy[i]) - (customers[i - minutes] * grumpy[i - minutes]);
        }
        max_extra_customers = max(max_extra_customers, extra_customers);
    }
    return total_customers + max_extra_customers;
}
```
First, we need to calculate the initial sum of satisfied customers which we do by looping through the `customers` array and checking if the bookstore owner is grumpy at that minute, i.e., `grumpy[i] == 0`. If the bookstore owner is not grumpy, we add the customers at that minute to `total_customers`.

Then, we need to find the maximum possible number of extra customers that can be satisfied by using the secret technique for `minutes` minutes. Initialise two variables, `max_extra_customers` and `extra_customers`, to 0. Iterate through the `customers` array again. If the current minute, `i`, is less than `minutes`, increment `extra_customers` by the product of `customers[i]` and `grumpy[i]`. Otherwise, increment `extra_customers` by adding the product of `customers[i]` and `grumpy[i]` and subtracting the product of `customers[i - minutes]` and `grumpy[i - minutes]`.

Update `max_extra_customers` with the maximum of its current value and `extra_customers`. After the iteration, return the sum of `total_customers` and `max_extra_customers` as the maximum number of satisfied customers throughout the day.

## A solution in Python

```python
def maxSatisfied(customers, grumpy, minutes):
    total_customers = 0
    max_extra_customers = 0
    extra_customers = 0
    for i in range(len(customers)):
        if grumpy[i] == 0:
            total_customers += customers[i]
        if i < minutes:
            extra_customers += customers[i] * grumpy[i]
        else:
            extra_customers += (customers[i] * grumpy[i]) - (customers[i - minutes] * grumpy[i - minutes])
        max_extra_customers = max(max_extra_customers, extra_customers)
    return total_customers + max_extra_customers
```
First, we need to calculate the initial sum of satisfied customers which we do by looping through the `customers` array and checking if the bookstore owner is grumpy at that minute, i.e., `grumpy[i] == 0`. If the bookstore owner is not grumpy, we add the customers at that minute to `total_customers`.

Then, we need to find the maximum possible number of extra customers that can be satisfied by using the secret technique for `minutes` minutes. Initialise two variables, `max_extra_customers` and `extra_customers`, to 0. Iterate through the `customers` array again. If the current minute, `i`, is less than `minutes`, increment `extra_customers` by the product of `customers[i]` and `grumpy[i]`. Otherwise, increment `extra_customers` by adding the product of `customers[i]` and `grumpy[i]` and subtracting the product of `customers[i - minutes]` and `grumpy[i - minutes]`.

Update `max_extra_customers` with the maximum of its current value and `extra_customers`. After the iteration, return the sum of `total_customers` and `max_extra_customers` as the maximum number of satisfied customers throughout the day.

## A solution in Javascript

```javascript
function maxSatisfied(customers, grumpy, minutes) {
    let total_customers = 0, max_extra_customers = 0, extra_customers = 0;
    for (let i = 0; i < customers.length; ++i) {
        if (grumpy[i] === 0) {
            total_customers += customers[i];
        }
        if (i < minutes) {
            extra_customers += customers[i] * grumpy[i];
        } else {
            extra_customers += (customers[i] * grumpy[i]) - (customers[i - minutes] * grumpy[i - minutes]);
        }
        max_extra_customers = Math.max(max_extra_customers, extra_customers);
    }
    return total_customers + max_extra_customers;
}
```
First, we need to calculate the initial sum of satisfied customers which we do by looping through the `customers` array and checking if the bookstore owner is grumpy at that minute, i.e., `grumpy[i] == 0`. If the bookstore owner is not grumpy, we add the customers at that minute to `total_customers`.

Then, we need to find the maximum possible number of extra customers that can be satisfied by using the secret technique for `minutes` minutes. Initialise two variables, `max_extra_customers` and `extra_customers`, to 0. Iterate through the `customers` array again. If the current minute, `i`, is less than `minutes`, increment `extra_customers` by the product of `customers[i]` and `grumpy[i]`. Otherwise, increment `extra_customers` by adding the product of `customers[i]` and `grumpy[i]` and subtracting the product of `customers[i - minutes]` and `grumpy[i - minutes]`.

Update `max_extra_customers` with the maximum of its current value and `extra_customers`. After the iteration, return the sum of `total_customers` and `max_extra_customers` as the maximum number of satisfied customers throughout the day.


# Previous Permutation With One Swap

- slug: previous-permutation-with-one-swap
- difficulty: Medium

Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array.

**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` and `arr[j]`

**Example 1:**

**Input:** arr = \[3,2,1\]
**Output:** \[3,1,2\]
**Explanation:** Swapping 2 and 1.

**Example 2:**

**Input:** arr = \[1,1,5\]
**Output:** \[1,1,5\]
**Explanation:** This is already the smallest permutation.

**Example 3:**

**Input:** arr = \[1,9,4,6,7\]
**Output:** \[1,7,4,6,9\]
**Explanation:** Swapping 9 and 7.

**Constraints:**

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

## A solution in Java

```java
public int[] prevPermOpt1(int[] arr) {
    int n = arr.length;
    for (int i = n - 2; i >= 0; i--) {
        if (arr[i] > arr[i + 1]) {
            int j = i + 1;
            while (j < n && arr[j] < arr[i]) j++;
            int temp = arr[i];
            arr[i] = arr[j - 1];
            arr[j - 1] = temp;
            break;
        }
    }
    return arr;
}
```
The algorithm consists of iterating through the array from right to left to find the first number `arr[i]` that's greater than its immediate right adjacent number, `arr[i + 1]`. Then, it iterates rightwards starting from the `arr[i]` until it finds the number just smaller than `arr[i]`, and it swaps them. This gives the lexicographically largest permutation smaller than `arr` in exactly one swap. If no such number `arr[i]` is found, it means the given array `arr` is already the smallest permutation possible, and the same array is returned.

## A solution in C++

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

vector<int> prevPermOpt1(vector<int>& arr) {
    int n = arr.size();
    for (int i = n - 2; i >= 0; i--) {
        if (arr[i] > arr[i + 1]) {
            int j = i + 1;
            while (j < n && arr[j] < arr[i]) j++;
            swap(arr[i], arr[j - 1]);
            break;
        }
    }
    return arr;
}
```
The algorithm consists of iterating through the array from right to left to find the first number `arr[i]` that's greater than its immediate right adjacent number, `arr[i + 1]`. Then, it iterates rightwards starting from the `arr[i]` until it finds the number just smaller than `arr[i]`, and it swaps them. This gives the lexicographically largest permutation smaller than `arr` in exactly one swap. If no such number `arr[i]` is found, it means the given array `arr` is already the smallest permutation possible, and the same array is returned.

## A solution in Python

```python
def prevPermOpt1(arr):
    n = len(arr)
    for i in range(n - 2, -1, -1):
        if arr[i] > arr[i + 1]:
            j = i + 1
            while j < n and arr[j] < arr[i]:
                j += 1
            arr[i], arr[j - 1] = arr[j - 1], arr[i]
            break
    return arr
```
The algorithm consists of iterating through the array from right to left to find the first number `arr[i]` that's greater than its immediate right adjacent number, `arr[i + 1]`. Then, it iterates rightwards starting from the `arr[i]` until it finds the number just smaller than `arr[i]`, and it swaps them. This gives the lexicographically largest permutation smaller than `arr` in exactly one swap. If no such number `arr[i]` is found, it means the given array `arr` is already the smallest permutation possible, and the same array is returned.

## A solution in Javascript

```javascript
function prevPermOpt1(arr) {
    const n = arr.length;
    for (let i = n - 2; i >= 0; i--) {
        if (arr[i] > arr[i + 1]) {
            let j = i + 1;
            while (j < n && arr[j] < arr[i]) j++;
            [arr[i], arr[j - 1]] = [arr[j - 1], arr[i]];
            break;
        }
    }
    return arr;
}
```
The algorithm consists of iterating through the array from right to left to find the first number `arr[i]` that's greater than its immediate right adjacent number, `arr[i + 1]`. Then, it iterates rightwards starting from the `arr[i]` until it finds the number just smaller than `arr[i]`, and it swaps them. This gives the lexicographically largest permutation smaller than `arr` in exactly one swap. If no such number `arr[i]` is found, it means the given array `arr` is already the smallest permutation possible, and the same array is returned.


# Distant Barcodes

- slug: distant-barcodes
- difficulty: Medium

In a warehouse, there is a row of barcodes, where the `ith` barcode is `barcodes[i]`.

Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.

**Example 1:**

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

**Example 2:**

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

**Constraints:**

*   `1 <= barcodes.length <= 10000`
*   `1 <= barcodes[i] <= 10000`

## A solution in Java

```java
public int bitwiseComplement(int n) {
    int x = 1;
    while (n > x) {
        x = x * 2 + 1;
    }
    return x - n;
}
```
The algorithm starts by setting an integer `x` to 1. Then, we use a while loop to keep multiplying `x` by 2 and adding 1 until it becomes greater than the given number `n`. This results in a number `x` which has all 1s in its binary representation and has the same number of binary digits (or greater) as the given number `n`. Finally, we return the difference between `x` and `n`, which flip-flops 0s and 1s and gives the complement of `n`.

## A solution in C++

```cpp
int bitwiseComplement(int n) {
    int x = 1;
    while (n > x) {
        x = x * 2 + 1;
    }
    return x - n;
}
```
The algorithm starts by setting an integer `x` to 1. Then, we use a while loop to keep multiplying `x` by 2 and adding 1 until it becomes greater than the given number `n`. This results in a number `x` which has all 1s in its binary representation and has the same number of binary digits (or greater) as the given number `n`. Finally, we return the difference between `x` and `n`, which flip-flops 0s and 1s and gives the complement of `n`.

## A solution in Python

```python
def bitwise_complement(n):
    x = 1
    while n > x:
        x = x * 2 + 1
    return x - n
```
The algorithm starts by setting an integer `x` to 1. Then, we use a while loop to keep multiplying `x` by 2 and adding 1 until it becomes greater than the given number `n`. This results in a number `x` which has all 1s in its binary representation and has the same number of binary digits (or greater) as the given number `n`. Finally, we return the difference between `x` and `n`, which flip-flops 0s and 1s and gives the complement of `n`.

## A solution in Javascript

```javascript
function bitwiseComplement(n) {
    let x = 1;
    while (n > x) {
        x = x * 2 + 1;
    }
    return x - n;
}
```
The algorithm starts by setting an integer `x` to 1. Then, we use a while loop to keep multiplying `x` by 2 and adding 1 until it becomes greater than the given number `n`. This results in a number `x` which has all 1s in its binary representation and has the same number of binary digits (or greater) as the given number `n`. Finally, we return the difference between `x` and `n`, which flip-flops 0s and 1s and gives the complement of `n`.


# Shortest Way to Form String

- slug: shortest-way-to-form-string
- difficulty: Medium

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

Given two strings `source` and `target`, return _the minimum number of **subsequences** of_ `source` _such that their concatenation equals_ `target`. If the task is impossible, return `-1`.

**Example 1:**

**Input:** source =  "abc ", target =  "abcbc "
**Output:** 2
**Explanation:** The target  "abcbc " can be formed by  "abc " and  "bc ", which are subsequences of source  "abc ".

**Example 2:**

**Input:** source =  "abc ", target =  "acdbc "
**Output:** -1
**Explanation:** The target string cannot be constructed from the subsequences of source string due to the character  "d " in target string.

**Example 3:**

**Input:** source =  "xyz ", target =  "xzyxz "
**Output:** 3
**Explanation:** The target string can be constructed as follows  "xz " +  "y " +  "xz ".

**Constraints:**

*   `1 <= source.length, target.length <= 1000`
*   `source` and `target` consist of lowercase English letters.

## A solution in Java

```java
public int numPairsDivisibleBy60(int[] time) {
    int[] count = new int[60];
    int pairs = 0;

    for (int t : time) {
        int mod = t % 60;
        pairs += count[(60 - mod) % 60];
        count[mod]++;
    }

    return pairs;
}
```
The algorithm calculates the modulus (`t % 60`) for each song duration and stores the frequency in the `count` array. When iterating through the song durations, if the durations have moduluses that sum to 60, they meet the pair condition. Therefore, for each song duration, it adds the frequency of the required modulus (`(60 - mod) % 60`) to the count of pairs. This way, the algorithm counts all valid pairs for each song duration.

The algorithm only requires one pass through the input list; thus, its time complexity is O(n), where n is the number of songs in the input list. The extra space needed is the `count` array, which has a constant size of 60; hence, the space complexity is O(1).

## A solution in C++

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

int numPairsDivisibleBy60(vector<int>& time) {
    int count[60] = {0};
    int pairs = 0;

    for (int t : time) {
        int mod = t % 60;
        pairs += count[(60 - mod) % 60];
        count[mod]++;
    }

    return pairs;
}
```
The algorithm calculates the modulus (`t % 60`) for each song duration and stores the frequency in the `count` array. When iterating through the song durations, if the durations have moduluses that sum to 60, they meet the pair condition. Therefore, for each song duration, it adds the frequency of the required modulus (`(60 - mod) % 60`) to the count of pairs. This way, the algorithm counts all valid pairs for each song duration.

The algorithm only requires one pass through the input list; thus, its time complexity is O(n), where n is the number of songs in the input list. The extra space needed is the `count` array, which has a constant size of 60; hence, the space complexity is O(1).

## A solution in Python

```python
def num_pairs_divisible_by60(time):
    count = [0] * 60
    pairs = 0

    for t in time:
        mod = t % 60
        pairs += count[(60 - mod) % 60]
        count[mod] += 1

    return pairs
```
The algorithm calculates the modulus (`t % 60`) for each song duration and stores the frequency in the `count` array. When iterating through the song durations, if the durations have moduluses that sum to 60, they meet the pair condition. Therefore, for each song duration, it adds the frequency of the required modulus (`(60 - mod) % 60`) to the count of pairs. This way, the algorithm counts all valid pairs for each song duration.

The algorithm only requires one pass through the input list; thus, its time complexity is O(n), where n is the number of songs in the input list. The extra space needed is the `count` array, which has a constant size of 60; hence, the space complexity is O(1).

## A solution in Javascript

```javascript
function numPairsDivisibleBy60(time) {
    let count = new Array(60).fill(0);
    let pairs = 0;

    for (let t of time) {
        let mod = t % 60;
        pairs += count[(60 - mod) % 60];
        count[mod]++;
    }

    return pairs;
}
```
The algorithm calculates the modulus (`t % 60`) for each song duration and stores the frequency in the `count` array. When iterating through the song durations, if the durations have moduluses that sum to 60, they meet the pair condition. Therefore, for each song duration, it adds the frequency of the required modulus (`(60 - mod) % 60`) to the count of pairs. This way, the algorithm counts all valid pairs for each song duration.

The algorithm only requires one pass through the input list; thus, its time complexity is O(n), where n is the number of songs in the input list. The extra space needed is the `count` array, which has a constant size of 60; hence, the space complexity is O(1).


# Confusing Number

- slug: confusing-number
- difficulty: Easy

A **confusing number** is a number that when rotated `180` degrees becomes a different number with **each digit valid**.

We can rotate digits of a number by `180` degrees to form new digits.

*   When `0`, `1`, `6`, `8`, and `9` are rotated `180` degrees, they become `0`, `1`, `9`, `8`, and `6` respectively.
*   When `2`, `3`, `4`, `5`, and `7` are rotated `180` degrees, they become **invalid**.

Note that after rotating a number, we can ignore leading zeros.

*   For example, after rotating `8000`, we have `0008` which is considered as just `8`.

Given an integer `n`, return `true` _if it is a **confusing number**, or_ `false` _otherwise_.

**Example 1:**

**Input:** n = 6
**Output:** true
**Explanation:** We get 9 after rotating 6, 9 is a valid number, and 9 != 6.

**Example 2:**

**Input:** n = 89
**Output:** true
**Explanation:** We get 68 after rotating 89, 68 is a valid number and 68 != 89.

**Example 3:**

**Input:** n = 11
**Output:** false
**Explanation:** We get 11 after rotating 11, 11 is a valid number but the value remains the same, thus 11 is not a confusing number

**Constraints:**

*   `0 <= n <= 109`

## A solution in Java

```java
import java.util.Arrays;

public int shipWithinDays(int[] weights, int days) {
    int left = Arrays.stream(weights).max().getAsInt();
    int right = Arrays.stream(weights).sum();
    while (left < right) {
        int mid = left + (right - left) / 2;
        int day_count = 1, curr_capacity = 0;
        for (int w : weights) {
            curr_capacity += w;
            if (curr_capacity > mid) {
                day_count++;
                curr_capacity = w;
            }
        }
        if (day_count > days) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left;
}
```
The algorithm employs binary search to find the least weight capacity. It starts by setting the initial search range to the maximum weight among packages (left) and the total weight of all packages (right). Then, the algorithm does the following steps until left is not less than right:
1. Compute the middle value (mid) of the search range.
2. Go through the packages' weights and count the days needed to ship them with the current mid value as the capacity. If the accumulated weight of packages exceeds the current capacity (mid), increment the day count and reset the accumulated weight.
3. If the calculated days needed is greater than the given days, we need a bigger capacity, so we update left to mid + 1. Otherwise, update right to mid.

After the loop, left is the least weight capacity that will ship all packages within days days.

## A solution in C++

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

int shipWithinDays(std::vector<int>& weights, int days) {
    int left = *max_element(weights.begin(), weights.end());
    int right = accumulate(weights.begin(), weights.end(), 0);
    while (left < right) {
        int mid = left + (right - left) / 2;
        int day_count = 1, curr_capacity = 0;
        for (int w : weights) {
            curr_capacity += w;
            if (curr_capacity > mid) {
                day_count++;
                curr_capacity = w;
            }
        }
        if (day_count > days) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left;
}
```
The algorithm employs binary search to find the least weight capacity. It starts by setting the initial search range to the maximum weight among packages (left) and the total weight of all packages (right). Then, the algorithm does the following steps until left is not less than right:
1. Compute the middle value (mid) of the search range.
2. Go through the packages' weights and count the days needed to ship them with the current mid value as the capacity. If the accumulated weight of packages exceeds the current capacity (mid), increment the day count and reset the accumulated weight.
3. If the calculated days needed is greater than the given days, we need a bigger capacity, so we update left to mid + 1. Otherwise, update right to mid.

After the loop, left is the least weight capacity that will ship all packages within days days.

## A solution in Python

```javascript
function shipWithinDays(weights, days) {
    let left = Math.max(...weights), right = weights.reduce((a, b) => a + b, 0);
    while (left < right) {
        let mid = left + ((right - left) / 2) | 0;
        let day_count = 1, curr_capacity = 0;
        for (const w of weights) {
            curr_capacity += w;
            if (curr_capacity > mid) {
                day_count++;
                curr_capacity = w;
            }
        }
        if (day_count > days) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left;
}
```
The algorithm employs binary search to find the least weight capacity. It starts by setting the initial search range to the maximum weight among packages (left) and the total weight of all packages (right). Then, the algorithm does the following steps until left is not less than right:
1. Compute the middle value (mid) of the search range.
2. Go through the packages' weights and count the days needed to ship them with the current mid value as the capacity. If the accumulated weight of packages exceeds the current capacity (mid), increment the day count and reset the accumulated weight.
3. If the calculated days needed is greater than the given days, we need a bigger capacity, so we update left to mid + 1. Otherwise, update right to mid.

After the loop, left is the least weight capacity that will ship all packages within days days.

## A solution in Javascript

```python
def ship_within_days(weights, days):
    left, right = max(weights), sum(weights)
    while left < right:
        mid = left + (right - left) // 2
        day_count, curr_capacity = 1, 0
        for w in weights:
            curr_capacity += w
            if curr_capacity > mid:
                day_count += 1
                curr_capacity = w
        if day_count > days:
            left = mid + 1
        else:
            right = mid
    return left
```
The algorithm employs binary search to find the least weight capacity. It starts by setting the initial search range to the maximum weight among packages (left) and the total weight of all packages (right). Then, the algorithm does the following steps until left is not less than right:
1. Compute the middle value (mid) of the search range.
2. Go through the packages' weights and count the days needed to ship them with the current mid value as the capacity. If the accumulated weight of packages exceeds the current capacity (mid), increment the day count and reset the accumulated weight.
3. If the calculated days needed is greater than the given days, we need a bigger capacity, so we update left to mid + 1. Otherwise, update right to mid.

After the loop, left is the least weight capacity that will ship all packages within days days.


# Campus Bikes

- slug: campus-bikes
- difficulty: Medium

On a campus represented on the X-Y plane, there are `n` workers and `m` bikes, with `n <= m`.

You are given an array `workers` of length `n` where `workers[i] = [xi, yi]` is the position of the `ith` worker. You are also given an array `bikes` of length `m` where `bikes[j] = [xj, yj]` is the position of the `jth` bike. All the given positions are **unique**.

Assign a bike to each worker. Among the available bikes and workers, we choose the `(workeri, bikej)` pair with the shortest **Manhattan distance** between each other and assign the bike to that worker.

If there are multiple `(workeri, bikej)` pairs with the same shortest **Manhattan distance**, we choose the pair with **the smallest worker index**. If there are multiple ways to do that, we choose the pair with **the smallest bike index**. Repeat this process until there are no available workers.

Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the index (**0-indexed**) of the bike that the_ `ith` _worker is assigned to_.

The **Manhattan distance** between two points `p1` and `p2` is `Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|`.

**Example 1:**

**Input:** workers = \[\[0,0\],\[2,1\]\], bikes = \[\[1,2\],\[3,3\]\]
**Output:** \[1,0\]
**Explanation:** Worker 1 grabs Bike 0 as they are closest (without ties), and Worker 0 is assigned Bike 1. So the output is \[1, 0\].

**Example 2:**

**Input:** workers = \[\[0,0\],\[1,1\],\[2,0\]\], bikes = \[\[1,0\],\[2,2\],\[2,1\]\]
**Output:** \[0,2,1\]
**Explanation:** Worker 0 grabs Bike 0 at first. Worker 1 and Worker 2 share the same distance to Bike 2, thus Worker 1 is assigned to Bike 2, and Worker 2 will take Bike 1. So the output is \[0,2,1\].

**Constraints:**

*   `n == workers.length`
*   `m == bikes.length`
*   `1 <= n <= m <= 1000`
*   `workers[i].length == bikes[j].length == 2`
*   `0 <= xi, yi < 1000`
*   `0 <= xj, yj < 1000`
*   All worker and bike locations are **unique**.

## A solution in Java

```java
import java.util.HashSet;

public int numDupDigitsAtMostN(int n) {
    int count = 0;
    for (int i = 1; i <= n; i++) {
        HashSet<Integer> digits = new HashSet<>();
        int num = i;
        while (num != 0) {
            int digit = num % 10;
            if (digits.contains(digit)) {
                count++;
                break;
            } else {
                digits.add(digit);
            }
            num /= 10;
        }
    }
    return count;
}
```
The algorithm iterates over the range of numbers from 1 to n inclusive. For each number, it extracts the digits by taking the remainder when dividing by 10 (`num % 10`) and adds it to a set (or hash set in Java) of digits. If a digit is already present in the set, it means that the digit is repeated, so we increment the count and break this iteration. At the end, we return the count of numbers with at least one repeated digit.

## A solution in C++

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

int numDupDigitsAtMostN(int n) {
    int count = 0;
    for (int i = 1; i <= n; i++) {
        set<int> digits;
        int num = i;
        while (num != 0) {
            int digit = num % 10;
            if (digits.count(digit)) {
                count++;
                break;
            } else {
                digits.insert(digit);
            }
            num /= 10;
        }
    }
    return count;
}
```
The algorithm iterates over the range of numbers from 1 to n inclusive. For each number, it extracts the digits by taking the remainder when dividing by 10 (`num % 10`) and adds it to a set (or hash set in Java) of digits. If a digit is already present in the set, it means that the digit is repeated, so we increment the count and break this iteration. At the end, we return the count of numbers with at least one repeated digit.

## A solution in Python

```python
def num_dup_digits_at_most_n(n):
    count = 0
    for i in range(1, n + 1):
        digits = set()
        num = i
        while num != 0:
            digit = num % 10
            if digit in digits:
                count += 1
                break
            else:
                digits.add(digit)
            num //= 10
    return count
```
The algorithm iterates over the range of numbers from 1 to n inclusive. For each number, it extracts the digits by taking the remainder when dividing by 10 (`num % 10`) and adds it to a set (or hash set in Java) of digits. If a digit is already present in the set, it means that the digit is repeated, so we increment the count and break this iteration. At the end, we return the count of numbers with at least one repeated digit.

## A solution in Javascript

```javascript
function numDupDigitsAtMostN(n) {
    let count = 0;
    for (let i = 1; i <= n; i++) {
        let digits = new Set();
        let num = i;
        while (num !== 0) {
            let digit = num % 10;
            if (digits.has(digit)) {
                count++;
                break;
            } else {
                digits.add(digit);
            }
            num = Math.floor(num / 10);
        }
    }
    return count;
}
```
The algorithm iterates over the range of numbers from 1 to n inclusive. For each number, it extracts the digits by taking the remainder when dividing by 10 (`num % 10`) and adds it to a set (or hash set in Java) of digits. If a digit is already present in the set, it means that the digit is repeated, so we increment the count and break this iteration. At the end, we return the count of numbers with at least one repeated digit.


# Minimize Rounding Error to Meet Target

- slug: minimize-rounding-error-to-meet-target
- difficulty: Medium

Given an array of `prices` `[p1,p2...,pn]` and a `target`, round each price `pi` to `Roundi(pi)` so that the rounded array `[Round1(p1),Round2(p2)...,Roundn(pn)]` sums to the given `target`. Each operation `Roundi(pi)` could be either `Floor(pi)` or `Ceil(pi)`.

Return the string `"-1 "` if the rounded array is impossible to sum to `target`. Otherwise, return the smallest rounding error, which is defined as `Σ |Roundi(pi) - (pi)|` for `i` from `1` to `n`, as a string with three places after the decimal.

**Example 1:**

**Input:** prices = \[ "0.700 ", "2.800 ", "4.900 "\], target = 8
**Output:**  "1.000 "
**Explanation:**
Use Floor, Ceil and Ceil operations to get (0.7 - 0) + (3 - 2.8) + (5 - 4.9) = 0.7 + 0.2 + 0.1 = 1.0 .

**Example 2:**

**Input:** prices = \[ "1.500 ", "2.500 ", "3.500 "\], target = 10
**Output:**  "-1 "
**Explanation:** It is impossible to meet the target.

**Example 3:**

**Input:** prices = \[ "1.500 ", "2.500 ", "3.500 "\], target = 9
**Output:**  "1.500 "

**Constraints:**

*   `1 <= prices.length <= 500`
*   Each string `prices[i]` represents a real number in the range `[0.0, 1000.0]` and has exactly 3 decimal places.
*   `0 <= target <= 106`

## A solution in Java

```java
import java.text.DecimalFormat;
import java.math.BigDecimal;

public String findRoundingError(String[] prices, int target) {
    int n = prices.length;
    BigDecimal[] decimals = new BigDecimal[n];
    int roundedSum = 0;
    BigDecimal errorSum = BigDecimal.ZERO;

    for (int i = 0; i < n; i++) {
        BigDecimal price = new BigDecimal(prices[i]);
        decimals[i] = price.subtract(price.setScale(0, BigDecimal.ROUND_DOWN));
        roundedSum += price.setScale(0, BigDecimal.ROUND_DOWN).intValue();
        errorSum = errorSum.add(decimals[i]);
    }

    if (target < roundedSum || target > roundedSum + n) {
        return "-1 ";
    }

    int ceilCount = target - roundedSum;
    BigDecimal roundingError = BigDecimal.ZERO;

    for (int i = 0; i < n; i++) {
        if (ceilCount > 0) {
            roundingError = roundingError.add(BigDecimal.ONE.subtract(decimals[i]));
            ceilCount--;
        } else {
            roundingError = roundingError.add(decimals[i]);
        }
    }

    DecimalFormat df = new DecimalFormat("#.000");
    return df.format(roundingError) + " ";
}
```
1. Convert the input `prices` to decimal numbers, and calculate the decimal parts (decimal array) using flooring or subtraction from the integer value.
2. Compute the sum of the floors (rounded sum) of the `prices`.
3. Check if the target is reachable (i.e., in the range of the rounded sum and the rounded sum + number of prices). If not, return "-1 ".
4. Calculate the number of ceiling operations needed (ceil_count).
5. Compute the smallest rounding error by iterating over the decimal array, subtracting the decimal value (using ceil operation) or adding it to the rounding error. The condition should depend on whether ceil_count is positive or not.
6. Return the result as a string with three decimal places.

## A solution in C++

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

string findRoundingError(vector<string>& prices, int target) {
    int n = prices.size();
    vector<double> decimals(n);
    int rounded_sum = 0;
    double error_sum = 0.0;

    for (int i = 0; i < n; ++i) {
        double price = stod(prices[i]);
        decimals[i] = price - floor(price);
        rounded_sum += floor(price);
        error_sum += decimals[i];
    }

    if (target < rounded_sum || target > rounded_sum + n) {
        return "-1 ";
    }

    int ceil_count = target - rounded_sum;
    double rounding_error = 0.0;

    for (int i = 0; i < n; ++i) {
        if (ceil_count > 0) {
            rounding_error += 1 - decimals[i];
            --ceil_count;
        } else {
            rounding_error += decimals[i];
        }
    }

    return to_string(rounding_error).substr(0, 5) + " ";
}
```
1. Convert the input `prices` to decimal numbers, and calculate the decimal parts (decimal array) using flooring or subtraction from the integer value.
2. Compute the sum of the floors (rounded sum) of the `prices`.
3. Check if the target is reachable (i.e., in the range of the rounded sum and the rounded sum + number of prices). If not, return "-1 ".
4. Calculate the number of ceiling operations needed (ceil_count).
5. Compute the smallest rounding error by iterating over the decimal array, subtracting the decimal value (using ceil operation) or adding it to the rounding error. The condition should depend on whether ceil_count is positive or not.
6. Return the result as a string with three decimal places.

## A solution in Python

```python
from math import floor, ceil

def find_rounding_error(prices, target):
    n = len(prices)
    decimals = [float(price) - floor(float(price)) for price in prices]
    rounded_sum = sum(floor(float(price)) for price in prices)

    if target < rounded_sum or target > rounded_sum + n:
        return "-1 "

    ceil_count = target - rounded_sum
    rounding_error = 0.0

    for d in decimals:
        if ceil_count > 0:
            rounding_error += 1 - d
            ceil_count -= 1
        else:
            rounding_error += d

    return f"{rounding_error:.3f} "
```
1. Convert the input `prices` to decimal numbers, and calculate the decimal parts (decimal array) using flooring or subtraction from the integer value.
2. Compute the sum of the floors (rounded sum) of the `prices`.
3. Check if the target is reachable (i.e., in the range of the rounded sum and the rounded sum + number of prices). If not, return "-1 ".
4. Calculate the number of ceiling operations needed (ceil_count).
5. Compute the smallest rounding error by iterating over the decimal array, subtracting the decimal value (using ceil operation) or adding it to the rounding error. The condition should depend on whether ceil_count is positive or not.
6. Return the result as a string with three decimal places.

## A solution in Javascript

```javascript
function findRoundingError(prices, target) {
    const n = prices.length;
    const decimals = prices.map(price => {
        let num = parseFloat(price);
        return num - Math.floor(num);
    });

    const roundedSum = prices.reduce((sum, price) => {
        return sum + Math.floor(parseFloat(price));
    }, 0);

    if (target < roundedSum || target > roundedSum + n) {
        return '-1 ';
    }

    let ceilCount = target - roundedSum;
    let roundingError = 0;

    for (let d of decimals) {
        if (ceilCount > 0) {
            roundingError += 1 - d;
            ceilCount--;
        } else {
            roundingError += d;
        }
    }
    roundingError = roundingError.toFixed(3);
    return roundingError.toString() + " ";
}
```
1. Convert the input `prices` to decimal numbers, and calculate the decimal parts (decimal array) using flooring or subtraction from the integer value.
2. Compute the sum of the floors (rounded sum) of the `prices`.
3. Check if the target is reachable (i.e., in the range of the rounded sum and the rounded sum + number of prices). If not, return "-1 ".
4. Calculate the number of ceiling operations needed (ceil_count).
5. Compute the smallest rounding error by iterating over the decimal array, subtracting the decimal value (using ceil operation) or adding it to the rounding error. The condition should depend on whether ceil_count is positive or not.
6. Return the result as a string with three decimal places.


# All Paths from Source Lead to Destination

- slug: all-paths-from-source-lead-to-destination
- difficulty: Medium

Given the `edges` of a directed graph where `edges[i] = [ai, bi]` indicates there is an edge between nodes `ai` and `bi`, and two nodes `source` and `destination` of this graph, determine whether or not all paths starting from `source` eventually, end at `destination`, that is:

*   At least one path exists from the `source` node to the `destination` node
*   If a path exists from the `source` node to a node with no outgoing edges, then that node is equal to `destination`.
*   The number of possible paths from `source` to `destination` is a finite number.

Return `true` if and only if all roads from `source` lead to `destination`.

**Example 1:**

**Input:** n = 3, edges = \[\[0,1\],\[0,2\]\], source = 0, destination = 2
**Output:** false
**Explanation:** It is possible to reach and get stuck on both node 1 and node 2.

**Example 2:**

**Input:** n = 4, edges = \[\[0,1\],\[0,3\],\[1,2\],\[2,1\]\], source = 0, destination = 3
**Output:** false
**Explanation:** We have two possibilities: to end at node 3, or to loop over node 1 and node 2 indefinitely.

**Example 3:**

**Input:** n = 4, edges = \[\[0,1\],\[0,2\],\[1,3\],\[2,3\]\], source = 0, destination = 3
**Output:** true

**Constraints:**

*   `1 <= n <= 104`
*   `0 <= edges.length <= 104`
*   `edges.length == 2`
*   `0 <= ai, bi <= n - 1`
*   `0 <= source <= n - 1`
*   `0 <= destination <= n - 1`
*   The given graph may have self-loops and parallel edges.

## A solution in Java

```java
import java.util.*;

public boolean leadsToDestination(int n, int[][] edges, int source, int destination) {
    Map<Integer, List<Integer>> graph = new HashMap<>();
    for (int[] edge : edges) {
        graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]);
    }

    int[] visited = new int[n];
    return dfs(source, graph, visited, destination);
}

private boolean dfs(int node, Map<Integer, List<Integer>> graph, int[] visited, int destination) {
    if (!graph.containsKey(node)) return node == destination;
    if (visited[node] != 0) return visited[node] == 2;

    visited[node] = 1;
    for (int neighbor : graph.get(node)) {
        if (!dfs(neighbor, graph, visited, destination)) return false;
    }

    visited[node] = 2;
    return true;
}
```
The approach is to use Depth-First Search (DFS) to traverse the graph starting from the source node. While doing DFS, if a node is found that has no outgoing edges, we check if it is the destination node. Also, if we visit a node that we have visited before and it has finished processing, it means the destination node can be reached from the current node, so we return true.

1. Start by creating a graph from the edge list, and initializing a visited list of length n with all values set to 0.

2. Use a helper function, `dfs`, which receives the current node, the graph, the visited list, and the destination node as parameters.

3. In the dfs function, check the following:
  a. If the node has no outgoing edges (i.e., it's not in the graph), return whether the node is the destination node.
  b. If the visited[node] is not 0, return whether it is equal to 2.
  c. If neither of the above conditions are met, set visited[node] to 1 and iterate through the neighbors of the node in the graph. For each neighbor, recursively call the dfs function with the neighbor as the new node. If any of the recursive calls return false, return false.
  d. After the loop is done, set visited[node] to 2 and return true.

4. In the main function, call `dfs` with the source node and return the result.

## A solution in C++

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

bool dfs(int node, const std::unordered_map<int, std::vector<int>>& graph, std::vector<int>& visited, int destination) {
    if (graph.find(node) == graph.end()) return node == destination;
    if (visited[node] != 0) return visited[node] == 2;

    visited[node] = 1;
    for (int neighbor : graph.at(node)) {
        if (!dfs(neighbor, graph, visited, destination)) return false;
    }

    visited[node] = 2;
    return true;
}

bool leadsToDestination(int n, const std::vector<std::vector<int>>& edges, int source, int destination) {
    std::unordered_map<int, std::vector<int>> graph;
    for (const auto& edge : edges) {
        graph[edge[0]].push_back(edge[1]);
    }

    std::vector<int> visited(n, 0);
    return dfs(source, graph, visited, destination);
}
```
The approach is to use Depth-First Search (DFS) to traverse the graph starting from the source node. While doing DFS, if a node is found that has no outgoing edges, we check if it is the destination node. Also, if we visit a node that we have visited before and it has finished processing, it means the destination node can be reached from the current node, so we return true.

1. Start by creating a graph from the edge list, and initializing a visited list of length n with all values set to 0.

2. Use a helper function, `dfs`, which receives the current node, the graph, the visited list, and the destination node as parameters.

3. In the dfs function, check the following:
  a. If the node has no outgoing edges (i.e., it's not in the graph), return whether the node is the destination node.
  b. If the visited[node] is not 0, return whether it is equal to 2.
  c. If neither of the above conditions are met, set visited[node] to 1 and iterate through the neighbors of the node in the graph. For each neighbor, recursively call the dfs function with the neighbor as the new node. If any of the recursive calls return false, return false.
  d. After the loop is done, set visited[node] to 2 and return true.

4. In the main function, call `dfs` with the source node and return the result.

## A solution in Python

```python
from collections import defaultdict

def leadsToDestination(n, edges, source, destination):
    graph = defaultdict(list)
    for u, v in edges:
        graph[u].append(v)

    visited = [0] * n
    return dfs(source, graph, visited, destination)

def dfs(node, graph, visited, destination):
    if node not in graph:
        return node == destination
    if visited[node] != 0:
        return visited[node] == 2

    visited[node] = 1
    for neighbor in graph[node]:
        if not dfs(neighbor, graph, visited, destination):
            return False

    visited[node] = 2
    return True
```
The approach is to use Depth-First Search (DFS) to traverse the graph starting from the source node. While doing DFS, if a node is found that has no outgoing edges, we check if it is the destination node. Also, if we visit a node that we have visited before and it has finished processing, it means the destination node can be reached from the current node, so we return true.

1. Start by creating a graph from the edge list, and initializing a visited list of length n with all values set to 0.

2. Use a helper function, `dfs`, which receives the current node, the graph, the visited list, and the destination node as parameters.

3. In the dfs function, check the following:
  a. If the node has no outgoing edges (i.e., it's not in the graph), return whether the node is the destination node.
  b. If the visited[node] is not 0, return whether it is equal to 2.
  c. If neither of the above conditions are met, set visited[node] to 1 and iterate through the neighbors of the node in the graph. For each neighbor, recursively call the dfs function with the neighbor as the new node. If any of the recursive calls return false, return false.
  d. After the loop is done, set visited[node] to 2 and return true.

4. In the main function, call `dfs` with the source node and return the result.

## A solution in Javascript

```javascript
function leadsToDestination(n, edges, source, destination) {
    const graph = new Map();
    for (const [u, v] of edges) {
        if (!graph.has(u)) graph.set(u, []);
        graph.get(u).push(v);
    }

    const visited = new Array(n).fill(0);
    return dfs(source, graph, visited, destination);
}

function dfs(node, graph, visited, destination) {
    if (!graph.has(node)) return node === destination;
    if (visited[node] !== 0) return visited[node] === 2;

    visited[node] = 1;
    for (const neighbor of graph.get(node)) {
        if (!dfs(neighbor, graph, visited, destination)) return false;
    }

    visited[node] = 2;
    return true;
}
```
The approach is to use Depth-First Search (DFS) to traverse the graph starting from the source node. While doing DFS, if a node is found that has no outgoing edges, we check if it is the destination node. Also, if we visit a node that we have visited before and it has finished processing, it means the destination node can be reached from the current node, so we return true.

1. Start by creating a graph from the edge list, and initializing a visited list of length n with all values set to 0.

2. Use a helper function, `dfs`, which receives the current node, the graph, the visited list, and the destination node as parameters.

3. In the dfs function, check the following:
  a. If the node has no outgoing edges (i.e., it's not in the graph), return whether the node is the destination node.
  b. If the visited[node] is not 0, return whether it is equal to 2.
  c. If neither of the above conditions are met, set visited[node] to 1 and iterate through the neighbors of the node in the graph. For each neighbor, recursively call the dfs function with the neighbor as the new node. If any of the recursive calls return false, return false.
  d. After the loop is done, set visited[node] to 2 and return true.

4. In the main function, call `dfs` with the source node and return the result.


# Missing Element in Sorted Array

- slug: missing-element-in-sorted-array
- difficulty: Medium

Given an integer array `nums` which is sorted in **ascending order** and all of its elements are **unique** and given also an integer `k`, return the `kth` missing number starting from the leftmost number of the array.

**Example 1:**

**Input:** nums = \[4,7,9,10\], k = 1
**Output:** 5
**Explanation:** The first missing number is 5.

**Example 2:**

**Input:** nums = \[4,7,9,10\], k = 3
**Output:** 8
**Explanation:** The missing numbers are \[5,6,8,...\], hence the third missing number is 8.

**Example 3:**

**Input:** nums = \[1,2,4\], k = 3
**Output:** 6
**Explanation:** The missing numbers are \[3,5,6,7,...\], hence the third missing number is 6.

**Constraints:**

*   `1 <= nums.length <= 5 * 104`
*   `1 <= nums[i] <= 107`
*   `nums` is sorted in **ascending order,** and all the elements are **unique**.
*   `1 <= k <= 108`

**Follow up:** Can you find a logarithmic time complexity (i.e., `O(log(n))`) solution?

## A solution in Java

```java
public int findKthPositive(int[] nums, int k) {
    int left = 0, right = nums.length;
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] - mid - 1 < k) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left + k;
}
```
The algorithm starts by defining two pointers, `left` and `right`, initially set to 0 and the length of the `nums` array, respectively. It then enters a while loop where it continues iterating until the `left` pointer is no longer less than `right`. Inside the loop, we calculate the midpoint index between the two pointers.

Based on the difference between the value stored at the midpoint index and the current midpoint index (subtracted by 1), we update our pointers. If the difference is less than `k`, then we set `left` to midpoint + 1, otherwise, we set `right` to midpoint. This is because we know the missing number should be either to the right or to the left of midpoint.

The loop terminates when we narrow down the search to one element. Finally, it returns the value of `left + k`, which gives us the kth missing number. This solution has a logarithmic time complexity, i.e., O(log n).

## A solution in C++

```cpp
int findKthPositive(vector<int>& nums, int k) {
    int left = 0, right = nums.size();
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] - mid - 1 < k) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left + k;
}
```
The algorithm starts by defining two pointers, `left` and `right`, initially set to 0 and the length of the `nums` array, respectively. It then enters a while loop where it continues iterating until the `left` pointer is no longer less than `right`. Inside the loop, we calculate the midpoint index between the two pointers.

Based on the difference between the value stored at the midpoint index and the current midpoint index (subtracted by 1), we update our pointers. If the difference is less than `k`, then we set `left` to midpoint + 1, otherwise, we set `right` to midpoint. This is because we know the missing number should be either to the right or to the left of midpoint.

The loop terminates when we narrow down the search to one element. Finally, it returns the value of `left + k`, which gives us the kth missing number. This solution has a logarithmic time complexity, i.e., O(log n).

## A solution in Python

```python
def findKthPositive(nums, k):
    left, right = 0, len(nums)
    while left < right:
        mid = left + (right - left) // 2
        if nums[mid] - mid - 1 < k:
            left = mid + 1
        else:
            right = mid
    return left + k
```
The algorithm starts by defining two pointers, `left` and `right`, initially set to 0 and the length of the `nums` array, respectively. It then enters a while loop where it continues iterating until the `left` pointer is no longer less than `right`. Inside the loop, we calculate the midpoint index between the two pointers.

Based on the difference between the value stored at the midpoint index and the current midpoint index (subtracted by 1), we update our pointers. If the difference is less than `k`, then we set `left` to midpoint + 1, otherwise, we set `right` to midpoint. This is because we know the missing number should be either to the right or to the left of midpoint.

The loop terminates when we narrow down the search to one element. Finally, it returns the value of `left + k`, which gives us the kth missing number. This solution has a logarithmic time complexity, i.e., O(log n).

## A solution in Javascript

```javascript
function findKthPositive(nums, k) {
    let left = 0, right = nums.length;
    while (left < right) {
        let mid = Math.floor(left + (right - left) / 2);
        if (nums[mid] - mid - 1 < k) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left + k;
}
```
The algorithm starts by defining two pointers, `left` and `right`, initially set to 0 and the length of the `nums` array, respectively. It then enters a while loop where it continues iterating until the `left` pointer is no longer less than `right`. Inside the loop, we calculate the midpoint index between the two pointers.

Based on the difference between the value stored at the midpoint index and the current midpoint index (subtracted by 1), we update our pointers. If the difference is less than `k`, then we set `left` to midpoint + 1, otherwise, we set `right` to midpoint. This is because we know the missing number should be either to the right or to the left of midpoint.

The loop terminates when we narrow down the search to one element. Finally, it returns the value of `left + k`, which gives us the kth missing number. This solution has a logarithmic time complexity, i.e., O(log n).