# Reward Top K Students

- slug: reward-top-k-students
- difficulty: Medium

You are given two string arrays `positive_feedback` and `negative_feedback`, containing the words denoting positive and negative feedback, respectively. Note that **no** word is both positive and negative.

Initially every student has `0` points. Each positive word in a feedback report **increases** the points of a student by `3`, whereas each negative word **decreases** the points by `1`.

You are given `n` feedback reports, represented by a **0-indexed** string array `report` and a **0-indexed** integer array `student_id`, where `student_id[i]` represents the ID of the student who has received the feedback report `report[i]`. The ID of each student is **unique**.

Given an integer `k`, return _the top_ `k` _students after ranking them in **non-increasing** order by their points_. In case more than one student has the same points, the one with the lower ID ranks higher.

**Example 1:**

**Input:** positive\_feedback = \[ "smart ", "brilliant ", "studious "\], negative\_feedback = \[ "not "\], report = \[ "this student is studious ", "the student is smart "\], student\_id = \[1,2\], k = 2
**Output:** \[1,2\]
**Explanation:**
Both the students have 1 positive feedback and 3 points but since student 1 has a lower ID he ranks higher.

**Example 2:**

**Input:** positive\_feedback = \[ "smart ", "brilliant ", "studious "\], negative\_feedback = \[ "not "\], report = \[ "this student is not studious ", "the student is smart "\], student\_id = \[1,2\], k = 2
**Output:** \[2,1\]
**Explanation:**
- The student with ID 1 has 1 positive feedback and 1 negative feedback, so he has 3-1=2 points.
- The student with ID 2 has 1 positive feedback, so he has 3 points.
Since student 2 has more points, \[2,1\] is returned.

**Constraints:**

*   `1 <= positive_feedback.length, negative_feedback.length <= 104`
*   `1 <= positive_feedback[i].length, negative_feedback[j].length <= 100`
*   Both `positive_feedback[i]` and `negative_feedback[j]` consists of lowercase English letters.
*   No word is present in both `positive_feedback` and `negative_feedback`.
*   `n == report.length == student_id.length`
*   `1 <= n <= 104`
*   `report[i]` consists of lowercase English letters and spaces `' '`.
*   There is a single space between consecutive words of `report[i]`.
*   `1 <= report[i].length <= 100`
*   `1 <= student_id[i] <= 109`
*   All the values of `student_id[i]` are **unique**.
*   `1 <= k <= n`

## A solution in Java

```java
import java.util.*;

public List<Integer> topKStudents(String[] positiveFeedback, String[] negativeFeedback, String[] report,
                                   int[] studentId, int k) {
    Map<Integer, Integer> points = new HashMap<>();

    for (int i = 0; i < report.length; i++) {
        int posCount = 0, negCount = 0;

        for (String pos : positiveFeedback) {
            int posIndex = report[i].indexOf(pos);
            while (posIndex != -1) {
                posCount++;
                posIndex = report[i].indexOf(pos, posIndex + pos.length());
            }
        }

        for (String neg : negativeFeedback) {
            int negIndex = report[i].indexOf(neg);
            while (negIndex != -1) {
                negCount++;
                negIndex = report[i].indexOf(neg, negIndex + neg.length());
            }
        }

        int studentPoints = points.getOrDefault(studentId[i], 0) + 3 * posCount - negCount;
        points.put(studentId[i], studentPoints);
    }

    List<Integer> students = new ArrayList<>();
    for (int id : studentId) {
      students.add(id);
    }

    Collections.sort(students, (a, b) -> points.get(a) != points.get(b) ? points.get(b) - points.get(a) : a - b);

    return students.subList(0, k);
}
```
1. Initialize an empty dictionary (unordered_map in C++, HashMap in Java) to store a student's points based on their ID.
2. Iterate through the given reports using index i.
3. For each report, initialize positive and negative count to 0.
4. Iterate through positive_feedback words and find occurrences of each positive word in the report. Increment positive count for each occurrence.
5. Iterate through negative_feedback words and find occurrences of each negative word in the report. Increment negative count for each occurrence.
6. Update the student's points in the dictionary based on their ID: add 3 times positive count minus negative count to their existing points.
7. Sort the student_id array/vector in descending order according to points and break ties by ascending student ID.
8. Return the top k elements of the sorted `student_id` array/vector.

## A solution in C++

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

std::vector<int> top_k_students(const std::vector<std::string>& positive_feedback,
                                 const std::vector<std::string>& negative_feedback,
                                 const std::vector<std::string>& report,
                                 const std::vector<int>& student_id,
                                 int k) {
    std::unordered_map<int, int> points;
    for (size_t i = 0; i < report.size(); ++i) {
        int pos_count = 0, neg_count = 0;
        for (const auto& pos : positive_feedback) {
            size_t pos_index = report[i].find(pos);
            while (pos_index != std::string::npos) {
                ++pos_count;
                pos_index = report[i].find(pos, pos_index + pos.length());
            }
        }
        for (const auto& neg : negative_feedback) {
            size_t neg_index = report[i].find(neg);
            while (neg_index != std::string::npos) {
                ++neg_count;
                neg_index = report[i].find(neg, neg_index + neg.length());
            }
        }
        points[student_id[i]] += 3 * pos_count - neg_count;
    }

    std::vector<int> students(student_id.begin(), student_id.end());
    std::sort(students.begin(), students.end(), [&points](int a, int b) {
        return points[a] != points[b] ? points[a] > points[b] : a < b;
    });

    return std::vector<int>(students.begin(), students.begin() + k);
}
```
1. Initialize an empty dictionary (unordered_map in C++, HashMap in Java) to store a student's points based on their ID.
2. Iterate through the given reports using index i.
3. For each report, initialize positive and negative count to 0.
4. Iterate through positive_feedback words and find occurrences of each positive word in the report. Increment positive count for each occurrence.
5. Iterate through negative_feedback words and find occurrences of each negative word in the report. Increment negative count for each occurrence.
6. Update the student's points in the dictionary based on their ID: add 3 times positive count minus negative count to their existing points.
7. Sort the student_id array/vector in descending order according to points and break ties by ascending student ID.
8. Return the top k elements of the sorted `student_id` array/vector.

## A solution in Python

```python
def top_k_students(positive_feedback, negative_feedback, report, student_id, k):
    points = {}
    for i in range(len(report)):
        pos_count, neg_count = 0, 0
        for pos in positive_feedback:
            pos_index = report[i].find(pos)
            while pos_index != -1:
                pos_count += 1
                pos_index = report[i].find(pos, pos_index + len(pos))
        for neg in negative_feedback:
            neg_index = report[i].find(neg)
            while neg_index != -1:
                neg_count += 1
                neg_index = report[i].find(neg, neg_index + len(neg))

        points[student_id[i]] = points.get(student_id[i], 0) + 3 * pos_count - neg_count

    students = sorted(student_id, key=lambda x: (-points[x], x))
    return students[:k]
```
1. Initialize an empty dictionary (unordered_map in C++, HashMap in Java) to store a student's points based on their ID.
2. Iterate through the given reports using index i.
3. For each report, initialize positive and negative count to 0.
4. Iterate through positive_feedback words and find occurrences of each positive word in the report. Increment positive count for each occurrence.
5. Iterate through negative_feedback words and find occurrences of each negative word in the report. Increment negative count for each occurrence.
6. Update the student's points in the dictionary based on their ID: add 3 times positive count minus negative count to their existing points.
7. Sort the student_id array/vector in descending order according to points and break ties by ascending student ID.
8. Return the top k elements of the sorted `student_id` array/vector.

## A solution in Javascript

```javascript
function topKStudents(positive_feedback, negative_feedback, report, student_id, k) {
    let points = {};

    for (let i = 0; i < report.length; i++) {
        let pos_count = 0, neg_count = 0;
        for (const pos of positive_feedback) {
            let pos_index = report[i].indexOf(pos);
            while (pos_index !== -1) {
                pos_count++;
                pos_index = report[i].indexOf(pos, pos_index + pos.length);
            }
        }
        for (const neg of negative_feedback) {
            let neg_index = report[i].indexOf(neg);
            while (neg_index !== -1) {
                neg_count++;
                neg_index = report[i].indexOf(neg, neg_index + neg.length);
            }
        }
        points[student_id[i]] = (points[student_id[i]] || 0) + 3 * pos_count - neg_count;
    }

    let students = [...student_id];
    students.sort((a, b) => points[a] !== points[b] ? points[b] - points[a] : a - b);
    return students.slice(0, k);
}
```
1. Initialize an empty dictionary (unordered_map in C++, HashMap in Java) to store a student's points based on their ID.
2. Iterate through the given reports using index i.
3. For each report, initialize positive and negative count to 0.
4. Iterate through positive_feedback words and find occurrences of each positive word in the report. Increment positive count for each occurrence.
5. Iterate through negative_feedback words and find occurrences of each negative word in the report. Increment negative count for each occurrence.
6. Update the student's points in the dictionary based on their ID: add 3 times positive count minus negative count to their existing points.
7. Sort the student_id array/vector in descending order according to points and break ties by ascending student ID.
8. Return the top k elements of the sorted `student_id` array/vector.


# Minimize the Maximum of Two Arrays

- slug: minimize-the-maximum-of-two-arrays
- difficulty: Medium

We have two arrays `arr1` and `arr2` which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:

*   `arr1` contains `uniqueCnt1` **distinct** positive integers, each of which is **not divisible** by `divisor1`.
*   `arr2` contains `uniqueCnt2` **distinct** positive integers, each of which is **not divisible** by `divisor2`.
*   **No** integer is present in both `arr1` and `arr2`.

Given `divisor1`, `divisor2`, `uniqueCnt1`, and `uniqueCnt2`, return _the **minimum possible maximum** integer that can be present in either array_.

**Example 1:**

**Input:** divisor1 = 2, divisor2 = 7, uniqueCnt1 = 1, uniqueCnt2 = 3
**Output:** 4
**Explanation:**
We can distribute the first 4 natural numbers into arr1 and arr2.
arr1 = \[1\] and arr2 = \[2,3,4\].
We can see that both arrays satisfy all the conditions.
Since the maximum value is 4, we return it.

**Example 2:**

**Input:** divisor1 = 3, divisor2 = 5, uniqueCnt1 = 2, uniqueCnt2 = 1
**Output:** 3
**Explanation:**
Here arr1 = \[1,2\], and arr2 = \[3\] satisfy all conditions.
Since the maximum value is 3, we return it.

**Example 3:**

**Input:** divisor1 = 2, divisor2 = 4, uniqueCnt1 = 8, uniqueCnt2 = 2
**Output:** 15
**Explanation:**
Here, the final possible arrays can be arr1 = \[1,3,5,7,9,11,13,15\], and arr2 = \[2,6\].
It can be shown that it is not possible to obtain a lower maximum satisfying all conditions.

**Constraints:**

*   `2 <= divisor1, divisor2 <= 105`
*   `1 <= uniqueCnt1, uniqueCnt2 < 109`
*   `2 <= uniqueCnt1 + uniqueCnt2 <= 109`

## A solution in Java

```java
public int minimumPossibleMax(int divisor1, int divisor2, int uniqueCnt1, int uniqueCnt2) {
    return (divisor1 - 1) * uniqueCnt1 + (divisor2 - 1) * uniqueCnt2 + 1;
}
```

    To find the minimum possible maximum integer, we distribute numbers to both arrays while avoiding overlap between the two arrays and numbers that are divisible by the respective divisors. The maximum element in arr1 can be found by selecting uniqueCnt1 numbers not divisible by divisor1, and similarly for arr2.

In general, the formula for the minimum possible maximum integer can be determined by the following expression:
```
(divisor1 - 1) * uniqueCnt1 + (divisor2 - 1) * uniqueCnt2 + 1
```
This formula results from choosing the first uniqueCnt1 numbers not divisible by divisor1 and the first uniqueCnt2 numbers not divisible by divisor2, with differing increments ensuring no overlap between the two arrays.

By applying this formula in the given function, we can simply return the minimum possible maximum integer satisfying all the given conditions.

## A solution in C++

```cpp
int minimumPossibleMax(int divisor1, int divisor2, int uniqueCnt1, int uniqueCnt2) {
    return (divisor1 - 1) * uniqueCnt1 + (divisor2 - 1) * uniqueCnt2 + 1;
}
```

    To find the minimum possible maximum integer, we distribute numbers to both arrays while avoiding overlap between the two arrays and numbers that are divisible by the respective divisors. The maximum element in arr1 can be found by selecting uniqueCnt1 numbers not divisible by divisor1, and similarly for arr2.

In general, the formula for the minimum possible maximum integer can be determined by the following expression:
```
(divisor1 - 1) * uniqueCnt1 + (divisor2 - 1) * uniqueCnt2 + 1
```
This formula results from choosing the first uniqueCnt1 numbers not divisible by divisor1 and the first uniqueCnt2 numbers not divisible by divisor2, with differing increments ensuring no overlap between the two arrays.

By applying this formula in the given function, we can simply return the minimum possible maximum integer satisfying all the given conditions.

## A solution in Python

```python
def minimum_possible_max(divisor1, divisor2, unique_cnt1, unique_cnt2):
    return (divisor1 - 1) * unique_cnt1 + (divisor2 - 1) * unique_cnt2 + 1
```

    To find the minimum possible maximum integer, we distribute numbers to both arrays while avoiding overlap between the two arrays and numbers that are divisible by the respective divisors. The maximum element in arr1 can be found by selecting uniqueCnt1 numbers not divisible by divisor1, and similarly for arr2.

In general, the formula for the minimum possible maximum integer can be determined by the following expression:
```
(divisor1 - 1) * uniqueCnt1 + (divisor2 - 1) * uniqueCnt2 + 1
```
This formula results from choosing the first uniqueCnt1 numbers not divisible by divisor1 and the first uniqueCnt2 numbers not divisible by divisor2, with differing increments ensuring no overlap between the two arrays.

By applying this formula in the given function, we can simply return the minimum possible maximum integer satisfying all the given conditions.

## A solution in Javascript

```javascript
function minimumPossibleMax(divisor1, divisor2, uniqueCnt1, uniqueCnt2) {
    return (divisor1 - 1) * uniqueCnt1 + (divisor2 - 1) * uniqueCnt2 + 1;
}
```

    To find the minimum possible maximum integer, we distribute numbers to both arrays while avoiding overlap between the two arrays and numbers that are divisible by the respective divisors. The maximum element in arr1 can be found by selecting uniqueCnt1 numbers not divisible by divisor1, and similarly for arr2.

In general, the formula for the minimum possible maximum integer can be determined by the following expression:
```
(divisor1 - 1) * uniqueCnt1 + (divisor2 - 1) * uniqueCnt2 + 1
```
This formula results from choosing the first uniqueCnt1 numbers not divisible by divisor1 and the first uniqueCnt2 numbers not divisible by divisor2, with differing increments ensuring no overlap between the two arrays.

By applying this formula in the given function, we can simply return the minimum possible maximum integer satisfying all the given conditions.


# Shortest Distance to Target String in a Circular Array

- slug: shortest-distance-to-target-string-in-a-circular-array
- difficulty: Easy

You are given a **0-indexed** **circular** string array `words` and a string `target`. A **circular array** means that the array's end connects to the array's beginning.

*   Formally, the next element of `words[i]` is `words[(i + 1) % n]` and the previous element of `words[i]` is `words[(i - 1 + n) % n]`, where `n` is the length of `words`.

Starting from `startIndex`, you can move to either the next word or the previous word with `1` step at a time.

Return _the **shortest** distance needed to reach the string_ `target`. If the string `target` does not exist in `words`, return `-1`.

**Example 1:**

**Input:** words = \[ "hello ", "i ", "am ", "leetcode ", "hello "\], target =  "hello ", startIndex = 1
**Output:** 1
**Explanation:** We start from index 1 and can reach  "hello " by
- moving 3 units to the right to reach index 4.
- moving 2 units to the left to reach index 4.
- moving 4 units to the right to reach index 0.
- moving 1 unit to the left to reach index 0.
The shortest distance to reach  "hello " is 1.

**Example 2:**

**Input:** words = \[ "a ", "b ", "leetcode "\], target =  "leetcode ", startIndex = 0
**Output:** 1
**Explanation:** We start from index 0 and can reach  "leetcode " by
- moving 2 units to the right to reach index 3.
- moving 1 unit to the left to reach index 3.
The shortest distance to reach  "leetcode " is 1.

**Example 3:**

**Input:** words = \[ "i ", "eat ", "leetcode "\], target =  "ate ", startIndex = 0
**Output:** -1
**Explanation:** Since  "ate " does not exist in `words`, we return -1.

**Constraints:**

*   `1 <= words.length <= 100`
*   `1 <= words[i].length <= 100`
*   `words[i]` and `target` consist of only lowercase English letters.
*   `0 <= startIndex < words.length`

## A solution in Java

```java
public int shortest_distance(String[] words, String target, int startIndex) {
    int n = words.length;
    int left = 0, right = 0, i = startIndex;
    while (true) {
        if (words[i].equals(target)) {
            return Math.min(left, right);
        }
        left++;
        right++;
        i = (i + 1) % n;
        if (left == n) {
            break;
        }
    }
    return -1;
}
```
The algorithm initializes the variables left, right, and i to count the minimum steps taken to reach the target string. It starts searching from the startIndex and iterates in a circular manner with the help of the modulo operator. When the word at the current index i matches the target, the minimum of left and right is returned as the shortest distance. If no matching word is found after the entire traversal, the algorithm returns -1. The reason for maintaining both left and right counters is that we are allowed to move in both directions (previous or next) from the startIndex. Both left and right counters are incremented in each iteration for every step taken during the search.

The code provided above is directly focused on solving the given problem, looping over until either the target is found or the traversal is complete, and in each language, the syntax is adapted to match the respective language conventions. The logic and algorithm stay the same across all languages.

## A solution in C++

```cpp
int shortest_distance(vector<string>& words, string target, int startIndex) {
    int n = words.size();
    int left = 0, right = 0, i = startIndex;
    while (true) {
        if (words[i] == target) {
            return min(left, right);
        }
        left++;
        right++;
        i = (i + 1) % n;
        if (left == n) {
            break;
        }
    }
    return -1;
}
```
The algorithm initializes the variables left, right, and i to count the minimum steps taken to reach the target string. It starts searching from the startIndex and iterates in a circular manner with the help of the modulo operator. When the word at the current index i matches the target, the minimum of left and right is returned as the shortest distance. If no matching word is found after the entire traversal, the algorithm returns -1. The reason for maintaining both left and right counters is that we are allowed to move in both directions (previous or next) from the startIndex. Both left and right counters are incremented in each iteration for every step taken during the search.

The code provided above is directly focused on solving the given problem, looping over until either the target is found or the traversal is complete, and in each language, the syntax is adapted to match the respective language conventions. The logic and algorithm stay the same across all languages.

## A solution in Python

```python
def shortest_distance(words, target, startIndex):
    n = len(words)
    left, right, i = 0, 0, startIndex
    while True:
        if words[i] == target:
            return min(left, right)
        left += 1
        right += 1
        i = (i + 1) % n
        if left == n:
            break
    return -1
```
The algorithm initializes the variables left, right, and i to count the minimum steps taken to reach the target string. It starts searching from the startIndex and iterates in a circular manner with the help of the modulo operator. When the word at the current index i matches the target, the minimum of left and right is returned as the shortest distance. If no matching word is found after the entire traversal, the algorithm returns -1. The reason for maintaining both left and right counters is that we are allowed to move in both directions (previous or next) from the startIndex. Both left and right counters are incremented in each iteration for every step taken during the search.

The code provided above is directly focused on solving the given problem, looping over until either the target is found or the traversal is complete, and in each language, the syntax is adapted to match the respective language conventions. The logic and algorithm stay the same across all languages.

## A solution in Javascript

```javascript
function shortest_distance(words, target, startIndex) {
    let n = words.length;
    let left = 0, right = 0, i = startIndex;
    while (true) {
        if (words[i] === target) {
            return Math.min(left, right);
        }
        left++;
        right++;
        i = (i + 1) % n;
        if (left === n) {
            break;
        }
    }
    return -1;
}
```
The algorithm initializes the variables left, right, and i to count the minimum steps taken to reach the target string. It starts searching from the startIndex and iterates in a circular manner with the help of the modulo operator. When the word at the current index i matches the target, the minimum of left and right is returned as the shortest distance. If no matching word is found after the entire traversal, the algorithm returns -1. The reason for maintaining both left and right counters is that we are allowed to move in both directions (previous or next) from the startIndex. Both left and right counters are incremented in each iteration for every step taken during the search.

The code provided above is directly focused on solving the given problem, looping over until either the target is found or the traversal is complete, and in each language, the syntax is adapted to match the respective language conventions. The logic and algorithm stay the same across all languages.


# Take K of Each Character From Left and Right

- slug: take-k-of-each-character-from-left-and-right
- difficulty: Medium

You are given a string `s` consisting of the characters `'a'`, `'b'`, and `'c'` and a non-negative integer `k`. Each minute, you may take either the **leftmost** character of `s`, or the **rightmost** character of `s`.

Return _the **minimum** number of minutes needed for you to take **at least**_ `k` _of each character, or return_ `-1` _if it is not possible to take_ `k` _of each character._

**Example 1:**

**Input:** s =  "aabaaaacaabc ", k = 2
**Output:** 8
**Explanation:**
Take three characters from the left of s. You now have two 'a' characters, and one 'b' character.
Take five characters from the right of s. You now have four 'a' characters, two 'b' characters, and two 'c' characters.
A total of 3 + 5 = 8 minutes is needed.
It can be proven that 8 is the minimum number of minutes needed.

**Example 2:**

**Input:** s =  "a ", k = 1
**Output:** -1
**Explanation:** It is not possible to take one 'b' or 'c' so return -1.

**Constraints:**

*   `1 <= s.length <= 105`
*   `s` consists of only the letters `'a'`, `'b'`, and `'c'`.
*   `0 <= k <= s.length`

## A solution in Java

```java
class Solution {
    public int minMinutes(String s, int k) {
        int n = s.length();
        int[] left_counts = new int[3], right_counts = new int[3];
        for (char c : s.toCharArray()) right_counts[c - 'a']++;

        int ans = n, total = 0;
        while (true) {
            int l = 0, r = n - 1;
            while (l < r && left_counts[s.charAt(l) - 'a'] < k &&
                          right_counts[s.charAt(r) - 'a'] < k) {
                int need_left = Math.max(0, k - left_counts[s.charAt(l) - 'a']);
                int need_right = Math.max(0, k - right_counts[s.charAt(r) - 'a']);
                if (need_left <= need_right) {
                    total += need_left;
                    l++;
                    left_counts[s.charAt(l) - 'a']++;
                    right_counts[s.charAt(l) - 'a']--;
                } else {
                    total += need_right;
                    r--;
                    right_counts[s.charAt(r) - 'a']--;
                    left_counts[s.charAt(r) - 'a']++;
                }
            }
            ans = Math.min(ans, total);
            if (l + 1 < s.length()) {
                total -= left_counts[s.charAt(l) - 'a'];
                left_counts[s.charAt(l) - 'a']--;
                right_counts[s.charAt(l + 1) - 'a']++;
                l++;
            } else break;
        }
        if(left_counts[0] >= k && left_counts[1] >= k && left_counts[2] >= k) return ans;
        return -1;
    }
}
```
For each character of the string `s`, we maintain two count arrays, `left_counts` and `right_counts`.

Initially, `left_counts` is filled with zeros, and `right_counts` contains the frequency count of each character in `s`. We will use two pointers `l` and `r` to track the leftmost and rightmost characters in `s`.

While the conditions for both pointers are met, we use the `need_left` and `need_right` values to determine how many characters must be taken from the left or right sides of the string. If `need_left` is less than or equal to `need_right`, we take characters from the left and update the necessary counts. Otherwise, we take characters from the right and update counts accordingly.

We then update the answer by taking the minimum of the current answer and the total accumulated number of minutes. If the `left_counts` have at least `k` of each character, we return the answer. Otherwise, we return -1, indicating it is not possible to satisfy the condition.

## A solution in C++

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

int min_minutes(std::string s, int k) {
    int n = s.length();
    std::vector<int> left_counts(3, 0), right_counts(3, 0);
    for (char c : s) right_counts[c - 'a']++;

    int ans = n, total = 0;
    while (true) {
        int l = 0, r = n - 1;
        while (l < r && left_counts[s[l] - 'a'] < k && right_counts[s[r] - 'a'] < k) {
            int need_left = std::max(0, k - left_counts[s[l] - 'a']);
            int need_right = std::max(0, k - right_counts[s[r] - 'a']);
            if (need_left <= need_right) {
                total += need_left;
                l++;
                left_counts[s[l] - 'a']++;
                right_counts[s[l] - 'a']--;
            } else {
                total += need_right;
                r--;
                right_counts[s[r] - 'a']--;
                left_counts[s[r] - 'a']++;
            }
        }
        ans = std::min(ans, total);
        if (l + 1 < s.length()) {
            total -= left_counts[s[l] - 'a'];
            left_counts[s[l] - 'a']--;
            right_counts[s[l + 1] - 'a']++;
            l++;
        } else break;
    }
    if(left_counts[0] >= k && left_counts[1] >= k && left_counts[2] >= k) return ans;
    return -1;
}
```
For each character of the string `s`, we maintain two count arrays, `left_counts` and `right_counts`.

Initially, `left_counts` is filled with zeros, and `right_counts` contains the frequency count of each character in `s`. We will use two pointers `l` and `r` to track the leftmost and rightmost characters in `s`.

While the conditions for both pointers are met, we use the `need_left` and `need_right` values to determine how many characters must be taken from the left or right sides of the string. If `need_left` is less than or equal to `need_right`, we take characters from the left and update the necessary counts. Otherwise, we take characters from the right and update counts accordingly.

We then update the answer by taking the minimum of the current answer and the total accumulated number of minutes. If the `left_counts` have at least `k` of each character, we return the answer. Otherwise, we return -1, indicating it is not possible to satisfy the condition.

## A solution in Python

```python
def min_minutes(s: str, k: int) -> int:
    n = len(s)
    left_counts = [0] * 3
    right_counts = [0] * 3
    for c in s:
        right_counts[ord(c) - ord('a')] += 1

    ans, total = n, 0
    l, r = 0, n - 1
    while l < r:
        while l < r and left_counts[ord(s[l]) - ord('a')] < k and right_counts[ord(s[r]) - ord('a')] < k:
            need_left = max(0, k - left_counts[ord(s[l]) - ord('a')])
            need_right = max(0, k - right_counts[ord(s[r]) - ord('a')])
            if need_left <= need_right:
                total += need_left
                l += 1
                left_counts[ord(s[l]) - ord('a')] += 1
                right_counts[ord(s[l]) - ord('a')] -= 1
            else:
                total += need_right
                r -= 1
                right_counts[ord(s[r]) - ord('a')] -= 1
                left_counts[ord(s[r]) - ord('a')] += 1
        ans = min(ans, total)
        if l + 1 < n:
            total -= left_counts[ord(s[l]) - ord('a')]
            left_counts[ord(s[l]) - ord('a')] -= 1
            right_counts[ord(s[l + 1]) - ord('a')] += 1
            l += 1
        else:
            break
    if all(cnt >= k for cnt in left_counts):
        return ans
    return -1
```
For each character of the string `s`, we maintain two count arrays, `left_counts` and `right_counts`.

Initially, `left_counts` is filled with zeros, and `right_counts` contains the frequency count of each character in `s`. We will use two pointers `l` and `r` to track the leftmost and rightmost characters in `s`.

While the conditions for both pointers are met, we use the `need_left` and `need_right` values to determine how many characters must be taken from the left or right sides of the string. If `need_left` is less than or equal to `need_right`, we take characters from the left and update the necessary counts. Otherwise, we take characters from the right and update counts accordingly.

We then update the answer by taking the minimum of the current answer and the total accumulated number of minutes. If the `left_counts` have at least `k` of each character, we return the answer. Otherwise, we return -1, indicating it is not possible to satisfy the condition.

## A solution in Javascript

```javascript
function minMinutes(s, k) {
    let n = s.length;
    let left_counts = new Array(3).fill(0);
    let right_counts = s.split('').map(c => (c.charCodeAt() - 'a'.charCodeAt())).reduce((acc, idx) => {
        acc[idx]++;
        return acc;
    }, new Array(3).fill(0));

    let ans = n, total = 0;
    let l = 0, r = n - 1;
    while (l < r) {
        while (l < r && left_counts[s.charCodeAt(l) - 'a'.charCodeAt()] < k &&
                       right_counts[s.charCodeAt(r) - 'a'.charCodeAt()] < k) {
            let need_left = Math.max(0, k - left_counts[s.charCodeAt(l) - 'a'.charCodeAt()]);
            let need_right = Math.max(0, k - right_counts[s.charCodeAt(r) - 'a'.charCodeAt()]);
            if (need_left <= need_right) {
                total += need_left;
                l++;
                left_counts[s.charCodeAt(l) - 'a'.charCodeAt()]++;
                right_counts[s.charCodeAt(l) - 'a'.charCodeAt()]--;
            } else {
                total += need_right;
                r--;
                right_counts[s.charCodeAt(r) - 'a'.charCodeAt()]--;
                left_counts[s.charCodeAt(r) - 'a'.charCodeAt()]++;
            }
        }
        ans = Math.min(ans, total);
        if (l + 1 < s.length()) {
            total -= left_counts[s.charCodeAt(l) - 'a'.charCodeAt()];
            left_counts[s.charCodeAt(l) - 'a'.charCodeAt()]--;
            right_counts[s.charCodeAt(l + 1) - 'a'.charCodeAt()]++;
            l++;
        } else break;
    }
    if (left_counts.every(cnt => cnt >= k)) {
        return ans;
    }
    return -1;
}
```
For each character of the string `s`, we maintain two count arrays, `left_counts` and `right_counts`.

Initially, `left_counts` is filled with zeros, and `right_counts` contains the frequency count of each character in `s`. We will use two pointers `l` and `r` to track the leftmost and rightmost characters in `s`.

While the conditions for both pointers are met, we use the `need_left` and `need_right` values to determine how many characters must be taken from the left or right sides of the string. If `need_left` is less than or equal to `need_right`, we take characters from the left and update the necessary counts. Otherwise, we take characters from the right and update counts accordingly.

We then update the answer by taking the minimum of the current answer and the total accumulated number of minutes. If the `left_counts` have at least `k` of each character, we return the answer. Otherwise, we return -1, indicating it is not possible to satisfy the condition.


# Maximum Tastiness of Candy Basket

- slug: maximum-tastiness-of-candy-basket
- difficulty: Medium

You are given an array of positive integers `price` where `price[i]` denotes the price of the `ith` candy and a positive integer `k`.

The store sells baskets of `k` **distinct** candies. The **tastiness** of a candy basket is the smallest absolute difference of the **prices** of any two candies in the basket.

Return _the **maximum** tastiness of a candy basket._

**Example 1:**

**Input:** price = \[13,5,1,8,21,2\], k = 3
**Output:** 8
**Explanation:** Choose the candies with the prices \[13,5,21\].
The tastiness of the candy basket is: min(|13 - 5|, |13 - 21|, |5 - 21|) = min(8, 8, 16) = 8.
It can be proven that 8 is the maximum tastiness that can be achieved.

**Example 2:**

**Input:** price = \[1,3,1\], k = 2
**Output:** 2
**Explanation:** Choose the candies with the prices \[1,3\].
The tastiness of the candy basket is: min(|1 - 3|) = min(2) = 2.
It can be proven that 2 is the maximum tastiness that can be achieved.

**Example 3:**

**Input:** price = \[7,7,7,7\], k = 2
**Output:** 0
**Explanation:** Choosing any two distinct candies from the candies we have will result in a tastiness of 0.

**Constraints:**

*   `2 <= k <= price.length <= 105`
*   `1 <= price[i] <= 109`

## A solution in Java

```java
public int maxTastiness(int[] price, int k) {
    Arrays.sort(price);
    int max_tastiness = 0;
    for (int i = 0; i < price.length - k + 1; i++) {
        int min_diff = Integer.MAX_VALUE;
        for (int j = i; j < i + k - 1; j++) {
            min_diff = Math.min(min_diff, price[j + 1] - price[j]);
        }
        max_tastiness = Math.max(max_tastiness, min_diff);
    }

    return max_tastiness;
}
```
To get the maximum number of possible baskets, we can sort the array in ascending order. Next, iterate through the sorted price array and create k-sized subarrays (or baskets) starting from each candy. This approach ensures that the subarray will contain k distinct elements. Calculate the tastiness of each basket by finding the smallest absolute difference between prices of nearest candies. Keep track of the maximum tastiness while iterating through these baskets. To get the maximum tastiness, compare each calculated tastiness and return the highest one.

## A solution in C++

```cpp
int maxTastiness(vector<int>& price, int k) {
    sort(price.begin(), price.end());
    int max_tastiness = 0;
    for (int i = 0; i < price.size() - k + 1; i++) {
        int min_diff = INT_MAX;
        for (int j = i; j < i + k - 1; j++) {
            min_diff = min(min_diff, price[j + 1] - price[j]);
        }
        max_tastiness = max(max_tastiness, min_diff);
    }

    return max_tastiness;
}
```
To get the maximum number of possible baskets, we can sort the array in ascending order. Next, iterate through the sorted price array and create k-sized subarrays (or baskets) starting from each candy. This approach ensures that the subarray will contain k distinct elements. Calculate the tastiness of each basket by finding the smallest absolute difference between prices of nearest candies. Keep track of the maximum tastiness while iterating through these baskets. To get the maximum tastiness, compare each calculated tastiness and return the highest one.

## A solution in Python

```python
def max_tastiness(price, k):
    price.sort()
    max_tastiness = 0
    for i in range(len(price) - k + 1):
        min_diff = float('inf')
        for j in range(i, i + k - 1):
            min_diff = min(min_diff, price[j + 1] - price[j])
        max_tastiness = max(max_tastiness, min_diff)

    return max_tastiness
```
To get the maximum number of possible baskets, we can sort the array in ascending order. Next, iterate through the sorted price array and create k-sized subarrays (or baskets) starting from each candy. This approach ensures that the subarray will contain k distinct elements. Calculate the tastiness of each basket by finding the smallest absolute difference between prices of nearest candies. Keep track of the maximum tastiness while iterating through these baskets. To get the maximum tastiness, compare each calculated tastiness and return the highest one.

## A solution in Javascript

```javascript
function maxTastiness(price, k) {
    price.sort((a, b) => a - b);
    let max_tastiness = 0;
    for (let i = 0; i < price.length - k + 1; i++) {
        let min_diff = Infinity;
        for (let j = i; j < i + k - 1; j++) {
            min_diff = Math.min(min_diff, price[j + 1] - price[j]);
        }
        max_tastiness = Math.max(max_tastiness, min_diff);
    }

    return max_tastiness;
}
```
To get the maximum number of possible baskets, we can sort the array in ascending order. Next, iterate through the sorted price array and create k-sized subarrays (or baskets) starting from each candy. This approach ensures that the subarray will contain k distinct elements. Calculate the tastiness of each basket by finding the smallest absolute difference between prices of nearest candies. Keep track of the maximum tastiness while iterating through these baskets. To get the maximum tastiness, compare each calculated tastiness and return the highest one.


# Number of Great Partitions

- slug: number-of-great-partitions
- difficulty: Hard

You are given an array `nums` consisting of **positive** integers and an integer `k`.

**Partition** the array into two ordered **groups** such that each element is in exactly **one** group. A partition is called great if the **sum** of elements of each group is greater than or equal to `k`.

Return _the number of **distinct** great partitions_. Since the answer may be too large, return it **modulo** `109 + 7`.

Two partitions are considered distinct if some element `nums[i]` is in different groups in the two partitions.

**Example 1:**

**Input:** nums = \[1,2,3,4\], k = 4
**Output:** 6
**Explanation:** The great partitions are: (\[1,2,3\], \[4\]), (\[1,3\], \[2,4\]), (\[1,4\], \[2,3\]), (\[2,3\], \[1,4\]), (\[2,4\], \[1,3\]) and (\[4\], \[1,2,3\]).

**Example 2:**

**Input:** nums = \[3,3,3\], k = 4
**Output:** 0
**Explanation:** There are no great partitions for this array.

**Example 3:**

**Input:** nums = \[6,6\], k = 2
**Output:** 2
**Explanation:** We can either put nums\[0\] in the first partition or in the second partition.
The great partitions will be (\[6\], \[6\]) and (\[6\], \[6\]).

**Constraints:**

*   `1 <= nums.length, k <= 1000`
*   `1 <= nums[i] <= 109`

## A solution in Java

```java
public int countPartitions(int[] nums, int k) {
    long total_sum = 0;
    int n = nums.length;
    int mod = 1000000007;

    for (int num : nums) {
        total_sum += num;
    }

    if (total_sum < (long) k * 2) {
        return 0;
    }

    long[] dp = new long[n + 1];
    dp[0] = 1;

    for (int i = 1; i <= k - 1; i++) {
        for (int j = n - 1; j >= 1; j--) {
            dp[j] = (dp[j] * j + dp[j - 1]) % mod;
        }
    }

    long result = 0;

    for (int i = 0; i < n - 1; i++) {
        total_sum -= nums[i];
        if (total_sum >= k) {
            result = (result + dp[i + 1]) % mod;
        }
    }

    return (int) result;
}
```
1. Calculate the total sum of the given `nums` array.
2. If the total sum is less than `k * 2`, return 0 as there are no great partitions.
3. Initialize a dynamic programming array `dp` with the same length as `nums` plus 1, and set `dp[0]` to 1.
4. Iterate through the `dp` array in reverse, from the second last element to the first, updating the `dp` array with the current sum of elements from the `nums` array. The updates are calculated modulo `10^9 + 7`.
5. Iterate through the `nums` array, decrementing the total sum by the value of the current element. If the updated total sum is greater than or equal to `k`, add the `dp` value at the index plus 1 to the result, again calculated modulo `10^9 + 7`.
6. Return the final result.

## A solution in C++

```cpp
#include <vector>

int countPartitions(std::vector<int>& nums, int k) {
    long long total_sum = 0;
    int n = nums.size();
    int mod = 1000000007;

    for (int num : nums) {
        total_sum += num;
    }

    if (total_sum < k * 2) {
        return 0;
    }

    std::vector<long long> dp(n + 1, 1);

    for (int i = 1; i <= k - 1; i++) {
        for (int j = n - 1; j >= 1; j--) {
            dp[j] = (dp[j] * j + dp[j - 1]) % mod;
        }
    }

    long long result = 0;

    for(int i = 0; i < n - 1; i++) {
        total_sum -= nums[i];
        if (total_sum >= k) {
            result = (result + dp[i + 1]) % mod;
        }
    }

    return (int) result;
}
```
1. Calculate the total sum of the given `nums` array.
2. If the total sum is less than `k * 2`, return 0 as there are no great partitions.
3. Initialize a dynamic programming array `dp` with the same length as `nums` plus 1, and set `dp[0]` to 1.
4. Iterate through the `dp` array in reverse, from the second last element to the first, updating the `dp` array with the current sum of elements from the `nums` array. The updates are calculated modulo `10^9 + 7`.
5. Iterate through the `nums` array, decrementing the total sum by the value of the current element. If the updated total sum is greater than or equal to `k`, add the `dp` value at the index plus 1 to the result, again calculated modulo `10^9 + 7`.
6. Return the final result.

## A solution in Python

```python
def countPartitions(nums, k):
    total_sum = sum(nums)
    n = len(nums)
    mod = 1000000007

    if total_sum < k * 2:
        return 0

    dp = [1] * (n + 1)

    for i in range(1, k):
        for j in range(n - 1, 0, -1):
            dp[j] = (dp[j] * j + dp[j - 1]) % mod

    result = 0

    for i in range(n - 1):
        total_sum -= nums[i]
        if total_sum >= k:
            result = (result + dp[i + 1]) % mod

    return result
```
1. Calculate the total sum of the given `nums` array.
2. If the total sum is less than `k * 2`, return 0 as there are no great partitions.
3. Initialize a dynamic programming array `dp` with the same length as `nums` plus 1, and set `dp[0]` to 1.
4. Iterate through the `dp` array in reverse, from the second last element to the first, updating the `dp` array with the current sum of elements from the `nums` array. The updates are calculated modulo `10^9 + 7`.
5. Iterate through the `nums` array, decrementing the total sum by the value of the current element. If the updated total sum is greater than or equal to `k`, add the `dp` value at the index plus 1 to the result, again calculated modulo `10^9 + 7`.
6. Return the final result.

## A solution in Javascript

```javascript
function countPartitions(nums, k) {
    let total_sum = nums.reduce((sum, num) => sum + num, 0);
    let n = nums.length;
    let mod = 1000000007;

    if (total_sum < k * 2) {
        return 0;
    }

    let dp = new Array(n + 1).fill(1);

    for (let i = 1; i <= k - 1; i++) {
        for (let j = n - 1; j >= 1; j--) {
            dp[j] = (dp[j] * j + dp[j - 1]) % mod;
        }
    }

    let result = 0;

    for (let i = 0; i < n - 1; i++) {
        total_sum -= nums[i];
        if (total_sum >= k) {
            result = (result + dp[i + 1]) % mod;
        }
    }

    return result;
}
```
1. Calculate the total sum of the given `nums` array.
2. If the total sum is less than `k * 2`, return 0 as there are no great partitions.
3. Initialize a dynamic programming array `dp` with the same length as `nums` plus 1, and set `dp[0]` to 1.
4. Iterate through the `dp` array in reverse, from the second last element to the first, updating the `dp` array with the current sum of elements from the `nums` array. The updates are calculated modulo `10^9 + 7`.
5. Iterate through the `nums` array, decrementing the total sum by the value of the current element. If the updated total sum is greater than or equal to `k`, add the `dp` value at the index plus 1 to the result, again calculated modulo `10^9 + 7`.
6. Return the final result.


# Count the Number of K-Big Indices

- slug: count-the-number-of-k-big-indices
- difficulty: Hard

You are given a **0-indexed** integer array `nums` and a positive integer `k`.

We call an index `i` **k-big** if the following conditions are satisfied:

*   There exist at least `k` different indices `idx1` such that `idx1 < i` and `nums[idx1] < nums[i]`.
*   There exist at least `k` different indices `idx2` such that `idx2 > i` and `nums[idx2] < nums[i]`.

Return _the number of k-big indices_.

**Example 1:**

**Input:** nums = \[2,3,6,5,2,3\], k = 2
**Output:** 2
**Explanation:** There are only two 2-big indices in nums:
- i = 2 --> There are two valid idx1: 0 and 1. There are three valid idx2: 2, 3, and 4.
- i = 3 --> There are two valid idx1: 0 and 1. There are two valid idx2: 3 and 4.

**Example 2:**

**Input:** nums = \[1,1,1\], k = 3
**Output:** 0
**Explanation:** There are no 3-big indices in nums.

**Constraints:**

*   `1 <= nums.length <= 105`
*   `1 <= nums[i], k <= nums.length`

## A solution in Java

```java
public int kBigIndices(int[] nums, int k) {
    int n = nums.length;
    int[] left = new int[n];
    int[] right = new int[n];

    for (int i = 1; i < n; i++) {
        if (nums[i] > nums[i - 1])
            left[i] = left[i - 1] + 1;

        int j = n - 1 - i;
        if (nums[j] < nums[j + 1])
            right[j] = right[j + 1] + 1;
    }

    int count = 0;
    for (int i = 0; i < n; i++)
        if (left[i] >= k && right[i] >= k)
            count++;

    return count;
}
```
The algorithm uses two extra arrays, `left` and `right`, to store the number of smaller elements from left and right sides, respectively. Iterate through the `nums` array and fill the `left` and `right` arrays according to the conditions.

Then, iterate the `left` and `right` arrays simultaneously, and for each index `i`, check if both `left[i]` and `right[i]` are greater than or equal to `k`. If both conditions are satisfied, increment the `count`. Finally, return the `count`.

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

## A solution in C++

```cpp
int kBigIndices(vector<int>& nums, int k) {
    int n = nums.size();
    vector<int> left(n, 0), right(n, 0);

    for (int i = 1; i < n; ++i) {
        if (nums[i] > nums[i - 1])
            left[i] = left[i - 1] + 1;

        int j = n - i - 1;
        if (nums[j] < nums[j + 1])
            right[j] = right[j + 1] + 1;
    }

    int count = 0;
    for (int i = 0; i < n; ++i)
        if (left[i] >= k && right[i] >= k)
            count++;

    return count;
}
```
The algorithm uses two extra arrays, `left` and `right`, to store the number of smaller elements from left and right sides, respectively. Iterate through the `nums` array and fill the `left` and `right` arrays according to the conditions.

Then, iterate the `left` and `right` arrays simultaneously, and for each index `i`, check if both `left[i]` and `right[i]` are greater than or equal to `k`. If both conditions are satisfied, increment the `count`. Finally, return the `count`.

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

## A solution in Python

```python
def kBigIndices(nums, k):
    n = len(nums)
    left, right = [0] * n, [0] * n

    for i in range(1, n):
        if nums[i] > nums[i - 1]:
            left[i] = left[i - 1] + 1

        j = n - i - 1
        if nums[j] < nums[j + 1]:
            right[j] = right[j + 1] + 1

    return sum(1 for i in range(n) if left[i] >= k and right[i] >= k)
```
The algorithm uses two extra arrays, `left` and `right`, to store the number of smaller elements from left and right sides, respectively. Iterate through the `nums` array and fill the `left` and `right` arrays according to the conditions.

Then, iterate the `left` and `right` arrays simultaneously, and for each index `i`, check if both `left[i]` and `right[i]` are greater than or equal to `k`. If both conditions are satisfied, increment the `count`. Finally, return the `count`.

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

## A solution in Javascript

```javascript
function kBigIndices(nums, k) {
    const n = nums.length;
    const left = Array(n).fill(0);
    const right = Array(n).fill(0);

    for (let i = 1; i < n; i++) {
        if (nums[i] > nums[i - 1])
            left[i] = left[i - 1] + 1;

        let j = n - 1 - i;
        if (nums[j] < nums[j + 1])
            right[j] = right[j + 1] + 1;
    }

    let count = 0;
    for (let i = 0; i < n; i++)
        if (left[i] >= k && right[i] >= k)
            count++;

    return count;
}
```
The algorithm uses two extra arrays, `left` and `right`, to store the number of smaller elements from left and right sides, respectively. Iterate through the `nums` array and fill the `left` and `right` arrays according to the conditions.

Then, iterate the `left` and `right` arrays simultaneously, and for each index `i`, check if both `left[i]` and `right[i]` are greater than or equal to `k`. If both conditions are satisfied, increment the `count`. Finally, return the `count`.

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


# Count the Digits That Divide a Number

- slug: count-the-digits-that-divide-a-number
- difficulty: Easy

Given an integer `num`, return _the number of digits in `num` that divide_ `num`.

An integer `val` divides `nums` if `nums % val == 0`.

**Example 1:**

**Input:** num = 7
**Output:** 1
**Explanation:** 7 divides itself, hence the answer is 1.

**Example 2:**

**Input:** num = 121
**Output:** 2
**Explanation:** 121 is divisible by 1, but not 2. Since 1 occurs twice as a digit, we return 2.

**Example 3:**

**Input:** num = 1248
**Output:** 4
**Explanation:** 1248 is divisible by all of its digits, hence the answer is 4.

**Constraints:**

*   `1 <= num <= 109`
*   `num` does not contain `0` as one of its digits.

## A solution in Java

```java
public int digitsDividingNum(int num) {
    int count = 0, temp = num;
    while (temp > 0) {
        int digit = temp % 10;
        if (num % digit == 0) {
            count++;
        }
        temp /= 10;
    }
    return count;
}
```
The algorithm for counting the number of digits in `num` that divide `num` is as follows:

1. Create a variable `count` to store the count of such digits, and set it to 0.
2. Create a temporary variable `temp` equal to the given `num`.
3. While `temp` is greater than 0, follow these steps:
    a. Find the last digit of `temp` by calculating the remainder of the division `temp % 10`.
    b. Check if `num % digit` is equal to 0; if so, increment the `count` by 1.
    c. Remove the last digit of `temp` by integer dividing it by 10 (i.e., `temp /= 10` in C++ and Java, `temp //= 10` in Python, or `temp = Math.floor(temp / 10)` in JavaScript).
4. Return the `count`.

Each language implements these steps in a fairly similar way, with only minor syntax differences between them.

## A solution in C++

```cpp
int digitsDividingNum(int num) {
    int count = 0, temp = num;
    while (temp > 0) {
        int digit = temp % 10;
        if (num % digit == 0) {
            count++;
        }
        temp /= 10;
    }
    return count;
}
```
The algorithm for counting the number of digits in `num` that divide `num` is as follows:

1. Create a variable `count` to store the count of such digits, and set it to 0.
2. Create a temporary variable `temp` equal to the given `num`.
3. While `temp` is greater than 0, follow these steps:
    a. Find the last digit of `temp` by calculating the remainder of the division `temp % 10`.
    b. Check if `num % digit` is equal to 0; if so, increment the `count` by 1.
    c. Remove the last digit of `temp` by integer dividing it by 10 (i.e., `temp /= 10` in C++ and Java, `temp //= 10` in Python, or `temp = Math.floor(temp / 10)` in JavaScript).
4. Return the `count`.

Each language implements these steps in a fairly similar way, with only minor syntax differences between them.

## A solution in Python

```python
def digits_dividing_num(num):
    count = 0
    temp = num
    while temp > 0:
        digit = temp % 10
        if num % digit == 0:
            count += 1
        temp //= 10
    return count
```
The algorithm for counting the number of digits in `num` that divide `num` is as follows:

1. Create a variable `count` to store the count of such digits, and set it to 0.
2. Create a temporary variable `temp` equal to the given `num`.
3. While `temp` is greater than 0, follow these steps:
    a. Find the last digit of `temp` by calculating the remainder of the division `temp % 10`.
    b. Check if `num % digit` is equal to 0; if so, increment the `count` by 1.
    c. Remove the last digit of `temp` by integer dividing it by 10 (i.e., `temp /= 10` in C++ and Java, `temp //= 10` in Python, or `temp = Math.floor(temp / 10)` in JavaScript).
4. Return the `count`.

Each language implements these steps in a fairly similar way, with only minor syntax differences between them.

## A solution in Javascript

```javascript
function digitsDividingNum(num) {
    let count = 0, temp = num;
    while (temp > 0) {
        let digit = temp % 10;
        if (num % digit === 0) {
            count++;
        }
        temp = Math.floor(temp / 10);
    }
    return count;
}
```
The algorithm for counting the number of digits in `num` that divide `num` is as follows:

1. Create a variable `count` to store the count of such digits, and set it to 0.
2. Create a temporary variable `temp` equal to the given `num`.
3. While `temp` is greater than 0, follow these steps:
    a. Find the last digit of `temp` by calculating the remainder of the division `temp % 10`.
    b. Check if `num % digit` is equal to 0; if so, increment the `count` by 1.
    c. Remove the last digit of `temp` by integer dividing it by 10 (i.e., `temp /= 10` in C++ and Java, `temp //= 10` in Python, or `temp = Math.floor(temp / 10)` in JavaScript).
4. Return the `count`.

Each language implements these steps in a fairly similar way, with only minor syntax differences between them.


# Distinct Prime Factors of Product of Array

- slug: distinct-prime-factors-of-product-of-array
- difficulty: Medium

Given an array of positive integers `nums`, return _the number of **distinct prime factors** in the product of the elements of_ `nums`.

**Note** that:

*   A number greater than `1` is called **prime** if it is divisible by only `1` and itself.
*   An integer `val1` is a factor of another integer `val2` if `val2 / val1` is an integer.

**Example 1:**

**Input:** nums = \[2,4,3,7,10,6\]
**Output:** 4
**Explanation:**
The product of all the elements in nums is: 2 \* 4 \* 3 \* 7 \* 10 \* 6 = 10080 = 25 \* 32 \* 5 \* 7.
There are 4 distinct prime factors so we return 4.

**Example 2:**

**Input:** nums = \[2,4,8,16\]
**Output:** 1
**Explanation:**
The product of all the elements in nums is: 2 \* 4 \* 8 \* 16 = 1024 = 210.
There is 1 distinct prime factor so we return 1.

**Constraints:**

*   `1 <= nums.length <= 104`
*   `2 <= nums[i] <= 1000`

## A solution in Java

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

public int countDistinctPrimeFactors(int[] nums) {
    Set<Integer> prime_factors = new HashSet<>();
    for (int n : nums) {
        for (int divisor = 2; divisor * divisor <= n; ++divisor) {
            if (n % divisor == 0) {
                prime_factors.add(divisor);
                prime_factors.add(n / divisor);
            }
        }
    }
    return prime_factors.size();
}
```
The algorithm iterates through each number in the input array `nums`. For each number, it computes divisors from 2 to the square root of the number. If a number is divisible by a divisor, both the divisor and its corresponding factor (n // divisor) are added to a set. Using a set ensures that only distinct factors are stored. Finally, the size of the set is returned as it contains the number of distinct prime factors in the product of the elements of `nums`.

## A solution in C++

```cpp
#include <set>

int countDistinctPrimeFactors(const std::vector<int>& nums) {
    std::set<int> prime_factors;
    for (const int n : nums) {
        for (int divisor = 2; divisor * divisor <= n; ++divisor) {
            if (n % divisor == 0) {
                prime_factors.insert(divisor);
                prime_factors.insert(n / divisor);
            }
        }
    }
    return prime_factors.size();
}
```
The algorithm iterates through each number in the input array `nums`. For each number, it computes divisors from 2 to the square root of the number. If a number is divisible by a divisor, both the divisor and its corresponding factor (n // divisor) are added to a set. Using a set ensures that only distinct factors are stored. Finally, the size of the set is returned as it contains the number of distinct prime factors in the product of the elements of `nums`.

## A solution in Python

```python
def count_distinct_prime_factors(nums):
    prime_factors = set()
    for n in nums:
        for divisor in range(2, int(n**0.5) + 1):
            if n % divisor == 0:
                prime_factors.add(divisor)
                prime_factors.add(n // divisor)
    return len(prime_factors)
```
The algorithm iterates through each number in the input array `nums`. For each number, it computes divisors from 2 to the square root of the number. If a number is divisible by a divisor, both the divisor and its corresponding factor (n // divisor) are added to a set. Using a set ensures that only distinct factors are stored. Finally, the size of the set is returned as it contains the number of distinct prime factors in the product of the elements of `nums`.

## A solution in Javascript

```javascript
function countDistinctPrimeFactors(nums) {
    const prime_factors = new Set();
    for (const n of nums) {
        for (let divisor = 2; divisor * divisor <= n; ++divisor) {
            if (n % divisor === 0) {
                prime_factors.add(divisor);
                prime_factors.add(n / divisor);
            }
        }
    }
    return prime_factors.size;
}
```
The algorithm iterates through each number in the input array `nums`. For each number, it computes divisors from 2 to the square root of the number. If a number is divisible by a divisor, both the divisor and its corresponding factor (n // divisor) are added to a set. Using a set ensures that only distinct factors are stored. Finally, the size of the set is returned as it contains the number of distinct prime factors in the product of the elements of `nums`.


# Partition String Into Substrings With Values at Most K

- slug: partition-string-into-substrings-with-values-at-most-k
- difficulty: Medium

You are given a string `s` consisting of digits from `1` to `9` and an integer `k`.

A partition of a string `s` is called **good** if:

*   Each digit of `s` is part of **exactly** one substring.
*   The value of each substring is less than or equal to `k`.

Return _the **minimum** number of substrings in a **good** partition of_ `s`. If no **good** partition of `s` exists, return `-1`.

**Note** that:

*   The **value** of a string is its result when interpreted as an integer. For example, the value of `"123 "` is `123` and the value of `"1 "` is `1`.
*   A **substring** is a contiguous sequence of characters within a string.

**Example 1:**

**Input:** s =  "165462 ", k = 60
**Output:** 4
**Explanation:** We can partition the string into substrings  "16 ",  "54 ",  "6 ", and  "2 ". Each substring has a value less than or equal to k = 60.
It can be shown that we cannot partition the string into less than 4 substrings.

**Example 2:**

**Input:** s =  "238182 ", k = 5
**Output:** -1
**Explanation:** There is no good partition for this string.

**Constraints:**

*   `1 <= s.length <= 105`
*   `s[i]` is a digit from `'1'` to `'9'`.
*   `1 <= k <= 109`

.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton\[value="Show Message"\] + .spoiler > div {margin-top:-500%;} .spoilerbutton\[value="Hide Message"\] + .spoiler {padding:5px;}

## A solution in Java

```java
public int min_partitions(String s, int k) {
    int n = s.length();
    int count = 0, idx = 0;

    while (idx < n) {
        int currentValue = 0;
        while (idx < n && currentValue * 10 + (s.charAt(idx) - '0') <= k) {
            currentValue = currentValue * 10 + (s.charAt(idx) - '0');
            idx++;
        }

        if (currentValue == 0) return -1;
        count++;
    }

    return count;
}
```
The algorithm goes through the input string `s` from left to right. We maintain a `currentValue` variable that will store the value of the substring we're currently generating. We also maintain an index `idx` variable to track the current position in the string `s`.

We loop through the string `s` with a while loop. In the inner while loop, we accumulate digits into `currentValue` until the combined value becomes larger than `k`. Once we reach the limit, we increment the `count` variable to represent a new partition and reset `currentValue`. If at any point we have `currentValue` as 0, it means that even a single digit is larger than `k`, so we return -1.

Our algorithm continues in this manner, partitioning the string into substrings until we reach the end of the string `s`. The `count` variable keeps track of the minimum number of partitions in a good partition.

## A solution in C++

```cpp
#include <string>

int min_partitions(std::string s, int k) {
    int n = s.size();
    int count = 0, idx = 0;

    while (idx < n) {
        int currentValue = 0;
        // Make sure the currentValue is below k
        while (idx < n && currentValue * 10 + (s[idx] - '0') <= k) {
            currentValue = currentValue * 10 + (s[idx] - '0');
            idx++;
        }

        if (currentValue == 0) return -1;
        count++;
    }

    return count;
}
```
The algorithm goes through the input string `s` from left to right. We maintain a `currentValue` variable that will store the value of the substring we're currently generating. We also maintain an index `idx` variable to track the current position in the string `s`.

We loop through the string `s` with a while loop. In the inner while loop, we accumulate digits into `currentValue` until the combined value becomes larger than `k`. Once we reach the limit, we increment the `count` variable to represent a new partition and reset `currentValue`. If at any point we have `currentValue` as 0, it means that even a single digit is larger than `k`, so we return -1.

Our algorithm continues in this manner, partitioning the string into substrings until we reach the end of the string `s`. The `count` variable keeps track of the minimum number of partitions in a good partition.

## A solution in Python

```python
def min_partitions(s: str, k: int) -> int:
    n = len(s)
    count = 0
    idx = 0

    while idx < n:
        currentValue = 0
        while idx < n and currentValue * 10 + int(s[idx]) <= k:
            currentValue = currentValue * 10 + int(s[idx])
            idx += 1

        if currentValue == 0:
            return -1
        count += 1

    return count
```
The algorithm goes through the input string `s` from left to right. We maintain a `currentValue` variable that will store the value of the substring we're currently generating. We also maintain an index `idx` variable to track the current position in the string `s`.

We loop through the string `s` with a while loop. In the inner while loop, we accumulate digits into `currentValue` until the combined value becomes larger than `k`. Once we reach the limit, we increment the `count` variable to represent a new partition and reset `currentValue`. If at any point we have `currentValue` as 0, it means that even a single digit is larger than `k`, so we return -1.

Our algorithm continues in this manner, partitioning the string into substrings until we reach the end of the string `s`. The `count` variable keeps track of the minimum number of partitions in a good partition.

## A solution in Javascript

```javascript
function min_partitions(s, k) {
    let n = s.length;
    let count = 0, idx = 0;

    while (idx < n) {
        let currentValue = 0;
        while (idx < n && currentValue * 10 + parseInt(s[idx]) <= k) {
            currentValue = currentValue * 10 + parseInt(s[idx]);
            idx++;
        }

        if (currentValue === 0) return -1;
        count++;
    }

    return count;
}
```
The algorithm goes through the input string `s` from left to right. We maintain a `currentValue` variable that will store the value of the substring we're currently generating. We also maintain an index `idx` variable to track the current position in the string `s`.

We loop through the string `s` with a while loop. In the inner while loop, we accumulate digits into `currentValue` until the combined value becomes larger than `k`. Once we reach the limit, we increment the `count` variable to represent a new partition and reset `currentValue`. If at any point we have `currentValue` as 0, it means that even a single digit is larger than `k`, so we return -1.

Our algorithm continues in this manner, partitioning the string into substrings until we reach the end of the string `s`. The `count` variable keeps track of the minimum number of partitions in a good partition.


# Closest Prime Numbers in Range

- slug: closest-prime-numbers-in-range
- difficulty: Medium

Given two positive integers `left` and `right`, find the two integers `num1` and `num2` such that:

*   `left <= nums1 < nums2 <= right` .
*   `nums1` and `nums2` are both **prime** numbers.
*   `nums2 - nums1` is the **minimum** amongst all other pairs satisfying the above conditions.

Return _the positive integer array_ `ans = [nums1, nums2]`. _If there are multiple pairs satisfying these conditions, return the one with the minimum_ `nums1` _value or_ `[-1, -1]` _if such numbers do not exist._

A number greater than `1` is called **prime** if it is only divisible by `1` and itself.

**Example 1:**

**Input:** left = 10, right = 19
**Output:** \[11,13\]
**Explanation:** The prime numbers between 10 and 19 are 11, 13, 17, and 19.
The closest gap between any pair is 2, which can be achieved by \[11,13\] or \[17,19\].
Since 11 is smaller than 17, we return the first pair.

**Example 2:**

**Input:** left = 4, right = 6
**Output:** \[-1,-1\]
**Explanation:** There exists only one prime number in the given range, so the conditions cannot be satisfied.

**Constraints:**

*   `1 <= left <= right <= 106`

.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton\[value="Show Message"\] + .spoiler > div {margin-top:-500%;} .spoilerbutton\[value="Hide Message"\] + .spoiler {padding:5px;}

## A solution in Java

```java
import java.util.Arrays;

public class PrimePair {
    public static boolean isPrime(int n) {
        if (n <= 1) return false;
        for (int i = 2; i * i <= n; ++i) {
            if (n % i == 0) return false;
        }
        return true;
    }

    public static int[] closestPrimePair(int left, int right) {
        int minDist = right - left + 1;
        int[] ans = {-1, -1};
        for (int i = left; i <= right; ++i) {
            if (isPrime(i)) {
                for (int j = i + 1; j <= right; ++j) {
                    if (isPrime(j) && j - i < minDist) {
                        minDist = j - i;
                        ans = new int[]{i, j};
                    }
                }
            }
        }
        return ans;
    }
}
```
The algorithm iterates through all integers in the given range and checks if they are prime using the `is_prime` or `isPrime` function. The function checks for prime numbers by testing whether a number is divisible by any integer from 2 to the square root of the number. If a number is found to be prime, it then iterates through the remaining numbers in the range and checks if they are prime. If the second number is also prime and the distance between the two numbers is less than the minimum distance found so far, the algorithm updates the minimum distance and the answer array. The answer array is returned at the end.

## A solution in C++

```cpp
#include <vector>

bool isPrime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i * i <= n; ++i) {
        if (n % i == 0) return false;
    }
    return true;
}

std::vector<int> closestPrimePair(int left, int right) {
    int minDist = right - left + 1;
    std::vector<int> ans = {-1, -1};
    for (int i = left; i <= right; ++i) {
        if (isPrime(i)) {
            for (int j = i + 1; j <= right; ++j) {
                if (isPrime(j) && j - i < minDist) {
                    minDist = j - i;
                    ans = {i, j};
                }
            }
        }
    }
    return ans;
}
```
The algorithm iterates through all integers in the given range and checks if they are prime using the `is_prime` or `isPrime` function. The function checks for prime numbers by testing whether a number is divisible by any integer from 2 to the square root of the number. If a number is found to be prime, it then iterates through the remaining numbers in the range and checks if they are prime. If the second number is also prime and the distance between the two numbers is less than the minimum distance found so far, the algorithm updates the minimum distance and the answer array. The answer array is returned at the end.

## A solution in Python

```python
def is_prime(n):
    if n <= 1:
        return False
    i = 2
    while i * i <= n:
        if n % i == 0:
            return False
        i += 1
    return True

def closest_prime_pair(left, right):
    min_dist = right - left + 1
    ans = [-1, -1]
    for i in range(left, right + 1):
        if is_prime(i):
            for j in range(i + 1, right + 1):
                if is_prime(j) and j - i < min_dist:
                    min_dist = j - i
                    ans = [i, j]
    return ans
```
The algorithm iterates through all integers in the given range and checks if they are prime using the `is_prime` or `isPrime` function. The function checks for prime numbers by testing whether a number is divisible by any integer from 2 to the square root of the number. If a number is found to be prime, it then iterates through the remaining numbers in the range and checks if they are prime. If the second number is also prime and the distance between the two numbers is less than the minimum distance found so far, the algorithm updates the minimum distance and the answer array. The answer array is returned at the end.

## A solution in Javascript

```javascript
function isPrime(n) {
    if (n <= 1) return false;
    for (let i = 2; i * i <= n; ++i) {
        if (n % i === 0) return false;
    }
    return true;
}

function closestPrimePair(left, right) {
    let minDist = right - left + 1;
    let ans = [-1, -1];
    for (let i = left; i <= right; ++i) {
        if (isPrime(i)) {
            for (let j = i + 1; j <= right; ++j) {
                if (isPrime(j) && j - i < minDist) {
                    minDist = j - i;
                    ans = [i, j];
                }
            }
        }
    }
    return ans;
}
```
The algorithm iterates through all integers in the given range and checks if they are prime using the `is_prime` or `isPrime` function. The function checks for prime numbers by testing whether a number is divisible by any integer from 2 to the square root of the number. If a number is found to be prime, it then iterates through the remaining numbers in the range and checks if they are prime. If the second number is also prime and the distance between the two numbers is less than the minimum distance found so far, the algorithm updates the minimum distance and the answer array. The answer array is returned at the end.


# Maximum Frequency Score of a Subarray

- slug: maximum-frequency-score-of-a-subarray
- difficulty: Hard

You are given an integer array `nums` and a **positive** integer `k`.

The **frequency score** of an array is the sum of the **distinct** values in the array raised to the power of their **frequencies**, taking the sum **modulo** `109 + 7`.

*   For example, the frequency score of the array `[5,4,5,7,4,4]` is `(43 + 52 + 71) modulo (109 + 7) = 96`.

Return _the **maximum** frequency score of a **subarray** of size_ `k` _in_ `nums`. You should maximize the value under the modulo and not the actual value.

A **subarray** is a contiguous part of an array.

**Example 1:**

**Input:** nums = \[1,1,1,2,1,2\], k = 3
**Output:** 5
**Explanation:** The subarray \[2,1,2\] has a frequency score equal to 5. It can be shown that it is the maximum frequency score we can have.

**Example 2:**

**Input:** nums = \[1,1,1,1,1,1\], k = 4
**Output:** 1
**Explanation:** All the subarrays of length 4 have a frequency score equal to 1.

**Constraints:**

*   `1 <= k <= nums.length <= 105`
*   `1 <= nums[i] <= 106`

## A solution in Java

```java
import java.util.HashMap;

public int maxFrequencyScore(int[] nums, int k) {
    int n = nums.length;
    int right = 0, count = 0, max_score = 0;
    long score = 0;
    HashMap<Integer, Integer> freqMap = new HashMap<Integer, Integer>();

    for (int left = 0; left < n; ++left) {
        while (right < n && count < k) {
            score = (score + (long)nums[right] * freqMap.getOrDefault(nums[right], 0)) % 1000000007;
            freqMap.put(nums[right], freqMap.getOrDefault(nums[right], 0) + 1);
            count++;
            right++;
        }

        max_score = Math.max(max_score, (int)score);

        if (count == k) {
            score -= nums[left] * (freqMap.get(nums[left]) - 1);
            freqMap.put(nums[left], freqMap.get(nums[left]) - 1);
            count--;
        }
    }

    return max_score;
}
```
1. Initialize variables `right`, `count`, `max_score`, and `score`.
2. Use a hash map `freq_map` to store the frequency of each number in the subarray.
3. Use a sliding window of size `k` to traverse through the array:
   a. Move the right pointer and increment the count and update score.
   b. When the count becomes equal to `k`:
       - Calculate the score and compare with the current max score. If the score is greater, update the max score.
       - Move the left pointer and decrement the count.
4. Return `max_score`.

The time complexity is O(n) and the space complexity is also O(n), where n is the length of the nums array.

## A solution in C++

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

int maxFrequencyScore(std::vector<int>& nums, int k) {
    int n = nums.size();
    int right = 0, count = 0, max_score = 0;
    long long score = 0;
    std::unordered_map<int, int> freqMap;

    for (int left = 0; left < n; ++left) {
        while (right < n && count < k) {
            score = (score + (long long)nums[right] * freqMap[nums[right]]) % 1000000007;
            freqMap[nums[right]]++;
            count++;
            right++;
        }

        max_score = std::max(max_score, (int)score);

        if (count == k) {
            score -= nums[left] * (freqMap[nums[left]] - 1);
            freqMap[nums[left]]--;
            count--;
        }
    }

    return max_score;
}
```
1. Initialize variables `right`, `count`, `max_score`, and `score`.
2. Use a hash map `freq_map` to store the frequency of each number in the subarray.
3. Use a sliding window of size `k` to traverse through the array:
   a. Move the right pointer and increment the count and update score.
   b. When the count becomes equal to `k`:
       - Calculate the score and compare with the current max score. If the score is greater, update the max score.
       - Move the left pointer and decrement the count.
4. Return `max_score`.

The time complexity is O(n) and the space complexity is also O(n), where n is the length of the nums array.

## A solution in Python

```python
def maxFrequencyScore(nums, k):
    n = len(nums)
    right = 0
    count = 0
    max_score = 0
    score = 0
    freq_map = {}

    for left in range(n):
        while right < n and count < k:
            score = (score + nums[right] * freq_map.get(nums[right], 0)) % 1000000007
            freq_map[nums[right]] = freq_map.get(nums[right], 0) + 1
            count += 1
            right += 1

        max_score = max(max_score, score)

        if count == k:
            score -= nums[left] * (freq_map[nums[left]] - 1)
            freq_map[nums[left]] -= 1
            count -= 1

    return max_score
```
1. Initialize variables `right`, `count`, `max_score`, and `score`.
2. Use a hash map `freq_map` to store the frequency of each number in the subarray.
3. Use a sliding window of size `k` to traverse through the array:
   a. Move the right pointer and increment the count and update score.
   b. When the count becomes equal to `k`:
       - Calculate the score and compare with the current max score. If the score is greater, update the max score.
       - Move the left pointer and decrement the count.
4. Return `max_score`.

The time complexity is O(n) and the space complexity is also O(n), where n is the length of the nums array.

## A solution in Javascript

```javascript
function maxFrequencyScore(nums, k) {
    const n = nums.length;
    let right = 0, count = 0, max_score = 0;
    let score = BigInt(0);
    const freqMap = new Map();

    for (let left = 0; left < n; ++left) {
        while (right < n && count < k) {
            score = (score + BigInt(nums[right]) * BigInt(freqMap.get(nums[right]) || 0)) % BigInt(1000000007);
            freqMap.set(nums[right], (freqMap.get(nums[right]) || 0) + 1);
            count++;
            right++;
        }

        max_score = Math.max(max_score, Number(score));

        if (count === k) {
            score -= BigInt(nums[left]) * BigInt(freqMap.get(nums[left]) - 1);
            freqMap.set(nums[left], freqMap.get(nums[left]) - 1);
            count--;
        }
    }

    return max_score;
}
```
1. Initialize variables `right`, `count`, `max_score`, and `score`.
2. Use a hash map `freq_map` to store the frequency of each number in the subarray.
3. Use a sliding window of size `k` to traverse through the array:
   a. Move the right pointer and increment the count and update score.
   b. When the count becomes equal to `k`:
       - Calculate the score and compare with the current max score. If the score is greater, update the max score.
       - Move the left pointer and decrement the count.
4. Return `max_score`.

The time complexity is O(n) and the space complexity is also O(n), where n is the length of the nums array.


# Categorize Box According to Criteria

- slug: categorize-box-according-to-criteria
- difficulty: Easy

Given four integers `length`, `width`, `height`, and `mass`, representing the dimensions and mass of a box, respectively, return _a string representing the **category** of the box_.

*   The box is `"Bulky "` if:
    *   **Any** of the dimensions of the box is greater or equal to `104`.
    *   Or, the **volume** of the box is greater or equal to `109`.
*   If the mass of the box is greater or equal to `100`, it is `"Heavy ".`
*   If the box is both `"Bulky "` and `"Heavy "`, then its category is `"Both "`.
*   If the box is neither `"Bulky "` nor `"Heavy "`, then its category is `"Neither "`.
*   If the box is `"Bulky "` but not `"Heavy "`, then its category is `"Bulky "`.
*   If the box is `"Heavy "` but not `"Bulky "`, then its category is `"Heavy "`.

**Note** that the volume of the box is the product of its length, width and height.

**Example 1:**

**Input:** length = 1000, width = 35, height = 700, mass = 300
**Output:**  "Heavy "
**Explanation:**
None of the dimensions of the box is greater or equal to 104.
Its volume = 24500000 <= 109. So it cannot be categorized as  "Bulky ".
However mass >= 100, so the box is  "Heavy ".
Since the box is not  "Bulky " but  "Heavy ", we return  "Heavy ".

**Example 2:**

**Input:** length = 200, width = 50, height = 800, mass = 50
**Output:**  "Neither "
**Explanation:**
None of the dimensions of the box is greater or equal to 104.
Its volume = 8 \* 106 <= 109. So it cannot be categorized as  "Bulky ".
Its mass is also less than 100, so it cannot be categorized as  "Heavy " either.
Since its neither of the two above categories, we return  "Neither ".

**Constraints:**

*   `1 <= length, width, height <= 105`
*   `1 <= mass <= 103`

## A solution in Java

```java
public String boxCategory(int length, int width, int height, int mass) {
    boolean bulky = length >= 10000 || width >= 10000 || height >= 10000 || (long)length * width * height >= 1000000000;
    boolean heavy = mass >= 100;

    if (bulky && heavy) return "Both ";
    if (bulky) return "Bulky ";
    if (heavy) return "Heavy ";
    return "Neither ";
}
```
The algorithm first checks if the box is bulky by verifying if any of the dimensions equal or exceed 10^4, or if the volume of the box is equal to or greater than 10^9. If the mass of the box is greater or equal to 100, then it's considered heavy.

We then use conditional statements to determine the category of the box according to the values of the bulky and heavy variables.

If both the bulky and heavy conditions are true, we return "Both ". If bulky is true and heavy is false, we return "Bulky ". If heavy is true and bulky is false, we return "Heavy ". Otherwise, if neither condition is true, we return "Neither ".

## A solution in C++

```cpp
#include <string>

std::string boxCategory(int length, int width, int height, int mass) {
    bool bulky = length >= 10000 || width >= 10000 || height >= 10000 || (long)length * width * height >= 1000000000;
    bool heavy = mass >= 100;

    if (bulky && heavy) return "Both ";
    if (bulky) return "Bulky ";
    if (heavy) return "Heavy ";
    return "Neither ";
}
```
The algorithm first checks if the box is bulky by verifying if any of the dimensions equal or exceed 10^4, or if the volume of the box is equal to or greater than 10^9. If the mass of the box is greater or equal to 100, then it's considered heavy.

We then use conditional statements to determine the category of the box according to the values of the bulky and heavy variables.

If both the bulky and heavy conditions are true, we return "Both ". If bulky is true and heavy is false, we return "Bulky ". If heavy is true and bulky is false, we return "Heavy ". Otherwise, if neither condition is true, we return "Neither ".

## A solution in Python

```python
def boxCategory(length: int, width: int, height: int, mass: int) -> str:
    bulky = length >= 10000 or width >= 10000 or height >= 10000 or int(length) * width * height >= 1000000000
    heavy = mass >= 100

    if bulky and heavy:
        return "Both "
    if bulky:
        return "Bulky "
    if heavy:
        return "Heavy "
    return "Neither "
```
The algorithm first checks if the box is bulky by verifying if any of the dimensions equal or exceed 10^4, or if the volume of the box is equal to or greater than 10^9. If the mass of the box is greater or equal to 100, then it's considered heavy.

We then use conditional statements to determine the category of the box according to the values of the bulky and heavy variables.

If both the bulky and heavy conditions are true, we return "Both ". If bulky is true and heavy is false, we return "Bulky ". If heavy is true and bulky is false, we return "Heavy ". Otherwise, if neither condition is true, we return "Neither ".

## A solution in Javascript

```javascript
function boxCategory(length, width, height, mass) {
    const bulky = length >= 10000 || width >= 10000 || height >= 10000 || length * width * height >= 1000000000;
    const heavy = mass >= 100;

    if (bulky && heavy) return "Both ";
    if (bulky) return "Bulky ";
    if (heavy) return "Heavy ";
    return "Neither ";
}
```
The algorithm first checks if the box is bulky by verifying if any of the dimensions equal or exceed 10^4, or if the volume of the box is equal to or greater than 10^9. If the mass of the box is greater or equal to 100, then it's considered heavy.

We then use conditional statements to determine the category of the box according to the values of the bulky and heavy variables.

If both the bulky and heavy conditions are true, we return "Both ". If bulky is true and heavy is false, we return "Bulky ". If heavy is true and bulky is false, we return "Heavy ". Otherwise, if neither condition is true, we return "Neither ".


# Find Consecutive Integers from a Data Stream

- slug: find-consecutive-integers-from-a-data-stream
- difficulty: Medium

For a stream of integers, implement a data structure that checks if the last `k` integers parsed in the stream are **equal** to `value`.

Implement the **DataStream** class:

*   `DataStream(int value, int k)` Initializes the object with an empty integer stream and the two integers `value` and `k`.
*   `boolean consec(int num)` Adds `num` to the stream of integers. Returns `true` if the last `k` integers are equal to `value`, and `false` otherwise. If there are less than `k` integers, the condition does not hold true, so returns `false`.

**Example 1:**

**Input**
\[ "DataStream ",  "consec ",  "consec ",  "consec ",  "consec "\]
\[\[4, 3\], \[4\], \[4\], \[4\], \[3\]\]
**Output**
\[null, false, false, true, false\]

**Explanation**
DataStream dataStream = new DataStream(4, 3); //value = 4, k = 3
dataStream.consec(4); // Only 1 integer is parsed, so returns False.
dataStream.consec(4); // Only 2 integers are parsed.
                      // Since 2 is less than k, returns False.
dataStream.consec(4); // The 3 integers parsed are all equal to value, so returns True.
dataStream.consec(3); // The last k integers parsed in the stream are \[4,4,3\].
                      // Since 3 is not equal to value, it returns False.

**Constraints:**

*   `1 <= value, num <= 109`
*   `1 <= k <= 105`
*   At most `105` calls will be made to `consec`.

## A solution in Java

```java
import java.util.*;

class DataStream {
    private int value;
    private int k;
    private Queue<Integer> stream;

    public DataStream(int value, int k) {
        this.value = value;
        this.k = k;
        this.stream = new LinkedList<>();
    }

    public boolean consec(int num) {
        stream.add(num);
        if (stream.size() > k)
            stream.poll();

        return stream.size() == k && Collections.frequency(stream, value) == k;
    }
}
```
The algorithm stores the integers in a deque or queue (in Python and JavaScript, a list can also be used) and keeps the last `k` integers stored while removing older ones. It then checks whether there are exactly `k` integers and all integers are equal to `value`. If these conditions are met, it returns `True`. Otherwise, it returns `False`.

## A solution in C++

```cpp
#include <deque>

class DataStream {
public:
    DataStream(int value, int k) : value(value), k(k) {}

    bool consec(int num) {
        stream.push_back(num);
        if (stream.size() > k)
            stream.pop_front();

        return stream.size() == k && count(stream.begin(), stream.end(), value) == k;
    }

private:
    int value;
    int k;
    std::deque<int> stream;
};
```
The algorithm stores the integers in a deque or queue (in Python and JavaScript, a list can also be used) and keeps the last `k` integers stored while removing older ones. It then checks whether there are exactly `k` integers and all integers are equal to `value`. If these conditions are met, it returns `True`. Otherwise, it returns `False`.

## A solution in Python

```python
from collections import deque

class DataStream:
    def __init__(self, value: int, k: int):
        self.value = value
        self.k = k
        self.stream = deque()

    def consec(self, num: int) -> bool:
        self.stream.append(num)
        if len(self.stream) > self.k:
            self.stream.popleft()

        return len(self.stream) == self.k and self.stream.count(self.value) == self.k
```
The algorithm stores the integers in a deque or queue (in Python and JavaScript, a list can also be used) and keeps the last `k` integers stored while removing older ones. It then checks whether there are exactly `k` integers and all integers are equal to `value`. If these conditions are met, it returns `True`. Otherwise, it returns `False`.

## A solution in Javascript

```javascript
class DataStream {
    constructor(value, k) {
        this.value = value;
        this.k = k;
        this.stream = [];
    }

    consec(num) {
        this.stream.push(num);
        if (this.stream.length > this.k)
            this.stream.shift();

        return this.stream.length === this.k && this.stream.filter(x => x === this.value).length === this.k;
    }
}
```
The algorithm stores the integers in a deque or queue (in Python and JavaScript, a list can also be used) and keeps the last `k` integers stored while removing older ones. It then checks whether there are exactly `k` integers and all integers are equal to `value`. If these conditions are met, it returns `True`. Otherwise, it returns `False`.


# Find Xor-Beauty of Array

- slug: find-xor-beauty-of-array
- difficulty: Medium

You are given a **0-indexed** integer array `nums`.

The **effective value** of three indices `i`, `j`, and `k` is defined as `((nums[i] | nums[j]) & nums[k])`.

The **xor-beauty** of the array is the XORing of **the effective values of all the possible triplets** of indices `(i, j, k)` where `0 <= i, j, k < n`.

Return _the xor-beauty of_ `nums`.

**Note** that:

*   `val1 | val2` is bitwise OR of `val1` and `val2`.
*   `val1 & val2` is bitwise AND of `val1` and `val2`.

**Example 1:**

**Input:** nums = \[1,4\]
**Output:** 5
**Explanation:**
The triplets and their corresponding effective values are listed below:
- (0,0,0) with effective value ((1 | 1) & 1) = 1
- (0,0,1) with effective value ((1 | 1) & 4) = 0
- (0,1,0) with effective value ((1 | 4) & 1) = 1
- (0,1,1) with effective value ((1 | 4) & 4) = 4
- (1,0,0) with effective value ((4 | 1) & 1) = 1
- (1,0,1) with effective value ((4 | 1) & 4) = 4
- (1,1,0) with effective value ((4 | 4) & 1) = 0
- (1,1,1) with effective value ((4 | 4) & 4) = 4
Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5.

**Example 2:**

**Input:** nums = \[15,45,20,2,34,35,5,44,32,30\]
**Output:** 34
**Explanation:** `The xor-beauty of the given array is 34.`

**Constraints:**

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

## A solution in Java

```java
public int xorBeauty(int[] nums) {
    int n = nums.length;
    int maxXOR = 1024;
    int[] counter = new int[maxXOR];

    for (int num : nums) {
        counter[num % maxXOR]++;
    }

    int xor_beauty = 0;
    for (int i = 0; i < maxXOR; i++) {
        for (int j = i; j < maxXOR; j++) {
            int k = (i | j) & (~(i ^ j));
            if (k < maxXOR && k >= j) {
                int count = counter[i] * counter[j] * (i == j ? 1 : 2);
                if (k != i && k != j) {
                    count *= counter[k];
                }
                xor_beauty ^= count;
            }
        }
    }

    return xor_beauty;
}
```
For each possible index triple (`i`, `j`, `k`), we compute the effective value `(nums[i] | nums[j]) & nums[k]`. Instead of iterating over the indices, we iterate over the actual values, which are limited by the maximum value for bitwise operations (1024).

First, we calculate the count for each value in `nums` modulo `maxXOR` and store it in an array `counter`. Then, we iterate over all pairs of distinct values `i` and `j`, and we determine `k = (i | j) & (~(i ^ j))`. If `k` is within the boundaries of our `counter` array and greater or equal to `j`, we compute the count of this triplet and XOR it with our current `xor_beauty` value.

Finally, we return the computed `xor_beauty` value.

## A solution in C++

```cpp
int xorBeauty(vector<int>& nums) {
    int n = nums.size();
    int maxXOR = 1024; // Maximum value for bitwise operations
    vector<int> counter(maxXOR, 0);

    for (int num : nums) {
        counter[num % maxXOR]++;
    }

    int xor_beauty = 0;
    for (int i = 0; i < maxXOR; i++) {
        for (int j = i; j < maxXOR; j++) {
            int k = (i | j) & (~(i ^ j));
            if (k < maxXOR && k >= j) {
                int count = counter[i] * counter[j] * (i == j ? 1 : 2);
                if (k != i && k != j) {
                    count *= counter[k];
                }
                xor_beauty ^= count;
            }
        }
    }

    return xor_beauty;
}
```
For each possible index triple (`i`, `j`, `k`), we compute the effective value `(nums[i] | nums[j]) & nums[k]`. Instead of iterating over the indices, we iterate over the actual values, which are limited by the maximum value for bitwise operations (1024).

First, we calculate the count for each value in `nums` modulo `maxXOR` and store it in an array `counter`. Then, we iterate over all pairs of distinct values `i` and `j`, and we determine `k = (i | j) & (~(i ^ j))`. If `k` is within the boundaries of our `counter` array and greater or equal to `j`, we compute the count of this triplet and XOR it with our current `xor_beauty` value.

Finally, we return the computed `xor_beauty` value.

## A solution in Python

```python
def xor_beauty(nums):
    n = len(nums)
    maxXOR = 1024
    counter = [0] * maxXOR

    for num in nums:
        counter[num % maxXOR] += 1

    xor_beauty = 0
    for i in range(maxXOR):
        for j in range(i, maxXOR):
            k = (i | j) & (~(i ^ j))
            if k < maxXOR and k >= j:
                count = counter[i] * counter[j] * (1 if i == j else 2)
                if k != i and k != j:
                    count *= counter[k]
                xor_beauty ^= count

    return xor_beauty
```
For each possible index triple (`i`, `j`, `k`), we compute the effective value `(nums[i] | nums[j]) & nums[k]`. Instead of iterating over the indices, we iterate over the actual values, which are limited by the maximum value for bitwise operations (1024).

First, we calculate the count for each value in `nums` modulo `maxXOR` and store it in an array `counter`. Then, we iterate over all pairs of distinct values `i` and `j`, and we determine `k = (i | j) & (~(i ^ j))`. If `k` is within the boundaries of our `counter` array and greater or equal to `j`, we compute the count of this triplet and XOR it with our current `xor_beauty` value.

Finally, we return the computed `xor_beauty` value.

## A solution in Javascript

```javascript
function xorBeauty(nums) {
    const n = nums.length;
    const maxXOR = 1024;
    const counter = new Array(maxXOR).fill(0);

    for (const num of nums) {
        counter[num % maxXOR]++;
    }

    let xor_beauty = 0;
    for (let i = 0; i < maxXOR; i++) {
        for (let j = i; j < maxXOR; j++) {
            const k = (i | j) & (~(i ^ j));
            if (k < maxXOR && k >= j) {
                let count = counter[i] * counter[j] * (i === j ? 1 : 2);
                if (k !== i && k !== j) {
                    count *= counter[k];
                }
                xor_beauty ^= count;
            }
        }
    }

    return xor_beauty;
}
```
For each possible index triple (`i`, `j`, `k`), we compute the effective value `(nums[i] | nums[j]) & nums[k]`. Instead of iterating over the indices, we iterate over the actual values, which are limited by the maximum value for bitwise operations (1024).

First, we calculate the count for each value in `nums` modulo `maxXOR` and store it in an array `counter`. Then, we iterate over all pairs of distinct values `i` and `j`, and we determine `k = (i | j) & (~(i ^ j))`. If `k` is within the boundaries of our `counter` array and greater or equal to `j`, we compute the count of this triplet and XOR it with our current `xor_beauty` value.

Finally, we return the computed `xor_beauty` value.