```java
import java.util.*;

class Solution {
    public int[] getOrder(int[][] tasks) {
        Integer[] taskIndices = new Integer[tasks.length];
        for (int i = 0; i < tasks.length; i++) taskIndices[i] = i;

        Arrays.sort(taskIndices, (a, b) -> tasks[a][0] - tasks[b][0]);

        PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> {
            if (a[1] == b[1]) return a[0] - b[0];
            return a[1] - b[1];
        });

        long time = 0;
        int taskIdx = 0;
        List<Integer> result = new ArrayList<>();

        while (!isEmpty(taskIndices)) {
            while (taskIdx < taskIndices.length && tasks[taskIndices[taskIdx]][0] <= time) {
                int idx = taskIndices[taskIdx];
                minHeap.add(new int[]{idx, tasks[idx][1]});
                taskIndices[taskIdx] = null;
                taskIdx++;
            }

            if (!minHeap.isEmpty()) {
                int[] task = minHeap.poll();
                time += task[1];
                result.add(task[0]);
            } else if (taskIdx < taskIndices.length) {
                time = Math.max(time, (long)tasks[taskIndices[taskIdx]][0]);
            }
        }

        return result.stream().mapToInt(Integer::intValue).toArray();
    }

    private boolean isEmpty(Integer[] arr) {
        for (Integer elem : arr) {
            if (elem != null) return false;
        }
        return true;
    }
}
```

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

vector<int> getOrder(vector<vector<int>>& tasks) {
    vector<int> taskIndices(tasks.size());
    for (int i = 0; i < tasks.size(); i++) taskIndices[i] = i;

    sort(taskIndices.begin(), taskIndices.end(), [&](int a, int b) {
        return tasks[a][0] < tasks[b][0];
    });

    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> minHeap;
    long long time = 0;
    int taskIdx = 0;
    vector<int> result;

    while (!taskIndices.empty()) {
        while (taskIdx < taskIndices.size() && tasks[taskIndices[taskIdx]][0] <= time) {
            int idx = taskIndices[taskIdx];
            minHeap.push({tasks[idx][1], idx});
            taskIdx++;
        }

        if (!minHeap.empty()) {
            auto [processingTime, index] = minHeap.top();
            minHeap.pop();
            time += processingTime;
            result.push_back(index);
            taskIndices.erase(remove(taskIndices.begin(), taskIndices.end(), index), taskIndices.end());
        } else if (taskIdx < taskIndices.size()) {
            time = max(time, (long long)tasks[taskIndices[taskIdx]][0]);
        }
    }

    return result;
}
```


```python
def get_xor_sum(arr1, arr2):
    xor_arr1 = xor_arr2 = 0
    for i in arr1:
        xor_arr1 ^= i
    for j in arr2:
        xor_arr2 ^= j
    return xor_arr1 & xor_arr2
```

```cpp
int getXORSum(std::vector<int>& arr1, std::vector<int>& arr2) {
    int xor_arr1 = 0, xor_arr2 = 0;
    for (int i : arr1) xor_arr1 ^= i;
    for (int j : arr2) xor_arr2 ^= j;
    return xor_arr1 & xor_arr2;
}
```


```python
def longest_obstacle_course(obstacles):
    dp = []
    ans = [0] * len(obstacles)

    for obstacle in obstacles:
        index = bisect_left(dp, obstacle)
        ans[index] = index + 1
        if index == len(dp):
            dp.append(obstacle)
        else:
            dp[index] = obstacle

    return ans
```

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

std::vector<int> longestObstacleCourse(std::vector<int>& obstacles) {
    std::vector<int> dp;
    std::vector<int> ans(obstacles.size());

    for (int i = 0; i < obstacles.size(); ++i) {
        auto it = std::lower_bound(dp.begin(), dp.end(), obstacles[i]);
        ans[i] = std::distance(dp.begin(), it) + 1;
        if (it == dp.end()) {
            dp.push_back(obstacles[i]);
        } else {
            *it = obstacles[i];
        }
    }

    return ans;
}
```


```python
def maxFrequency(nums, k):
    nums.sort()
    max_freq, n, total = 1, len(nums), 0
    i = 0
    for j in range(n):
        total += nums[j]
        while total < nums[j] * (j - i + 1) - k:
            total -= nums[i]
            i += 1
        max_freq = max(max_freq, j - i + 1)
    return max_freq
```

```cpp
int maxFrequency(vector<int>& nums, int k) {
    sort(nums.begin(), nums.end());
    int max_freq = 1, n = nums.size();
    long long sum = 0;
    for (int i = 0, j = 0; j < n; ++j) {
        sum += nums[j];
        while (sum < static_cast<long long>(nums[j]) * (j - i + 1) - k) {
            sum -= nums[i++];
        }
        max_freq = max(max_freq, j - i + 1);
    }
    return max_freq;
}
```


```java
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class Solution {
    private int dfs(TreeNode root, int[] count) {
        if(root == null) return 0;
        int left_sum = dfs(root.left, count);
        int right_sum = dfs(root.right, count);
        if(root.val == left_sum + right_sum) count[0]++;
        return root.val + left_sum + right_sum;
    }

    public int equalToDescendants(TreeNode root) {
        int[] count = new int[1];
        dfs(root, count);
        return count[0];
    }
}
```

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

class Solution:
    def dfs(self, root, count):
        if not root:
            return 0
        left_sum = self.dfs(root.left, count)
        right_sum = self.dfs(root.right, count)
        if root.val == left_sum + right_sum:
            count[0] += 1
        return root.val + left_sum + right_sum

    def equalToDescendants(self, root):
        count = [0]
        self.dfs(root, count)
        return count[0]
```


```java
public int minTimeToType(String word) {
    int time = 0, position = 0;
    for (char c : word.toCharArray()) {
        int next_position = c - 'a';
        int diff = Math.abs(next_position - position);
        time += Math.min(diff, 26 - diff) + 1;
        position = next_position;
    }
    return time;
}
```

azzbyxxc abcz aazzbbbbyyyxxc aazzbbbbyyyxxc cba aazzbbbbyyyxxc bza aazzbbyxxc zjpc zzy aazzbbbbyyyxxc zabc azbyxzc aazzbbbbyyyxxc abc aaxx aazzbbbyyxxc wxyzabcdefghijklmnopqrstuv axbc aazzbbbbyyyxxc abcdefghijklmnopqrstuvwxyz aazzbbbbyyyxxc azbyxc aazzbbbbyyyxxc aazzbbbbyyyxxc abc aazzbbbbyyyxxc aazzbbbbyyyxxc axbycz az aazzbbbbyyyxxc abcdefghijklmnopqrstuvwx abcx za azbxyc aazzbbbbyyyxxc aazzbbbbyyyxxc xyzx aaaa aazzbbbbyyyxxc abc y aazzbbbbyyyxxc aazzbbbbyyyxxc

```python
def minTimeToType(word: str) -> int:
    time = 0
    position = 0
    for c in word:
        next_position = ord(c) - ord('a')
        diff = abs(next_position - position)
        time += min(diff, 26 - diff) + 1
        position = next_position
    return time
```


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

public String findDifferentBinaryString(List<String> nums) {
    Set<String> set = new HashSet<>(nums);
    int n = nums.size();

    for (int i = 0; i < (1 << n); ++i) {
        StringBuilder candidate = new StringBuilder();
        for (int j = 0; j < n; ++j) {
            candidate.append(((i & (1 << j)) != 0) ? '1' : '0');
        }

        if (!set.contains(candidate.toString())) {
            return candidate.toString();
        }
    }
    return "";
}
```

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

std::string findDifferentBinaryString(std::vector<std::string>& nums) {
    std::unordered_set<std::string> s(nums.begin(), nums.end());
    int n = nums.size();

    for (int i = 0; i < (1 << n); ++i) {
        std::string candidate(n, '0');
        for (int j = 0; j < n; ++j) {
            if (i & (1 << j))
                candidate[j] = '1';
        }

        if (s.find(candidate) == s.end()) {
            return candidate;
        }
    }
    return "";
}
```


```python
def max_distance(nums1, nums2):
    i, j, max_dist = 0, 0, 0
    while i < len(nums1) and j < len(nums2):
        if i <= j and nums1[i] <= nums2[j]:
            max_dist = max(max_dist, j - i)
            j += 1
        else:
            i += 1
    return max_dist
```

```cpp
int maxDistance(vector<int>& nums1, vector<int>& nums2) {
    int i = 0, j = 0, maxDist = 0;
    while (i < nums1.size() && j < nums2.size()) {
        if (i <= j && nums1[i] <= nums2[j]) {
            maxDist = max(maxDist, j - i);
            j++;
        } else {
            i++;
        }
    }
    return maxDist;
}
```


```java
public int countGoodSubstrings(String s) {
    int count = 0;
    for (int i = 0; i < s.length() - 2; i++) {
        if (s.charAt(i) != s.charAt(i + 1) && s.charAt(i) != s.charAt(i + 2) && s.charAt(i + 1) != s.charAt(i + 2))
            count++;
    }
    return count;
}
```

```python
def count_good_substrings(s: str) -> int:
    count = 0
    for i in range(len(s) - 2):
        if s[i] != s[i + 1] and s[i] != s[i + 2] and s[i + 1] != s[i + 2]:
            count += 1
    return count
```


```python
def findMiddleIndex(nums):
    total_sum = sum(nums)
    left_sum = 0

    for i, num in enumerate(nums):
        if left_sum == total_sum - left_sum - num:
            return i
        left_sum += num

    return -1
```

```cpp
int findMiddleIndex(vector<int>& nums) {
    int total_sum = 0, left_sum = 0;

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

    for (int i = 0; i < nums.size(); i++) {
        if (left_sum == total_sum - left_sum - nums[i]) {
            return i;
        }
        left_sum += nums[i];
    }

    return -1;
}
```


```cpp
#include <vector>

std::vector<std::vector<int>> findFarmland(std::vector<std::vector<int>>& land) {
    int m = land.size(), n = land[0].size();
    std::vector<std::vector<int>> groups;

    for(int i = 0; i < m; ++i) {
        for(int j = 0; j < n; ++j) {
            if(land[i][j] == 1) {
                int r1 = i, c1 = j;
                while(j + 1 < n && land[i][j + 1] == 1) j++;
                int r2 = i, c2 = j;
                while(r2 + 1 < m && land[r2 + 1][j] == 1) r2++;
                for(int r = r1; r <= r2; ++r) {
                    for(int c = c1; c <= c2; ++c) {
                        land[r][c] = 0;
                    }
                }
                groups.push_back({r1, c1, r2, c2});
            }
        }
    }

    return groups;
}
```

```python
def findFarmland(land):
    m, n = len(land), len(land[0])
    groups = []

    for i in range(m):
        for j in range(n):
            if land[i][j] == 1:
                r1, c1 = i, j
                while j + 1 < n and land[i][j + 1] == 1:
                    j += 1
                r2, c2 = i, j
                while r2 + 1 < m and land[r2 + 1][j] == 1:
                    r2 += 1
                for r in range(r1, r2 + 1):
                    for c in range(c1, c2 + 1):
                        land[r][c] = 0
                groups.append([r1, c1, r2, c2])

    return groups
```


```python
def firstDayBeenInAllRooms(nextVisit):
    n = len(nextVisit)
    MOD = 10**9 + 7
    dp = [0] * n

    for i in range(1, n):
        dp[i] = (dp[i - 1] * 2 - dp[nextVisit[i - 1]] + 2) % MOD

    return dp[n - 1]
```

```cpp
int firstDayBeenInAllRooms(vector<int>& nextVisit) {
    int n = nextVisit.size();
    long long ans = 0, MOD = 1e9 + 7;
    vector<long long> dp(n, 0);

    for (int i = 1; i < n; ++i) {
        dp[i] = (dp[i - 1] * 2 - dp[nextVisit[i - 1]] + 2) % MOD;
    }

    return dp[n - 1];
}
```


```java
import java.util.Arrays;

public boolean canBeSorted(int[] nums) {
    int[] sorted_nums = Arrays.copyOf(nums, nums.length);
    Arrays.sort(sorted_nums);
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] != sorted_nums[i] && gcd(nums[i], sorted_nums[i]) == 1) {
            return false;
        }
    }
    return true;
}

private int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}
```

true false true true true true true true true true true true true true true true true true true false true true true true true true true true false true true true true true true true true true false true true true true true true true true true true false true true false true true true true true true true true true false true false true true true true true true true true false true

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

bool canBeSorted(std::vector<int>& nums) {
    std::vector<int> sorted_nums = nums;
    sort(sorted_nums.begin(), sorted_nums.end());
    for (size_t i = 0; i < nums.size(); ++i) {
        if (nums[i] != sorted_nums[i] && std::gcd(nums[i], sorted_nums[i]) == 1) {
            return false;
        }
    }
    return true;
}
```


```cpp
#include <vector>

int chalkReplacer(std::vector<int>& chalk, int k) {
    long long sum = 0;
    for (int i = 0; i < chalk.size(); i++) {
        sum += chalk[i];
    }
    k %= sum;
    for (int i = 0; i < chalk.size(); i++) {
        if (k < chalk[i]) {
            return i;
        }
        k -= chalk[i];
    }
    return 0;
}
```

```java
public int chalkReplacer(int[] chalk, int k) {
    long sum = 0;
    for (int i = 0; i < chalk.length; i++) {
        sum += chalk[i];
    }
    k %= sum;
    for (int i = 0; i < chalk.length; i++) {
        if (k < chalk[i]) {
            return i;
        }
        k -= chalk[i];
    }
    return 0;
}
```


```cpp
int min_operations(vector<int>& nums) {
    int n = nums.size();
    set<int> s(nums.begin(), nums.end());
    vector<int> v(s.begin(), s.end());
    int res = INT_MAX;
    int j = 0;

    for (int i = 0; i < v.size(); ++i) {
        while (j < v.size() && v[j] <= v[i] + n - 1) {
            ++j;
        }
        res = min(res, n - (j - i));
    }
    return res;
}
```

```java
public int minOperations(int[] nums) {
    int n = nums.length;
    Set<Integer> set = new HashSet<>();
    for (int num : nums) {
        set.add(num);
    }
    List<Integer> list = new ArrayList<>(set);
    Collections.sort(list);
    int res = Integer.MAX_VALUE;
    int j = 0;

    for (int i = 0; i < list.size(); ++i) {
        while (j < list.size() && list.get(j) <= list.get(i) + n - 1) {
            ++j;
        }
        res = Math.min(res, n - (j - i));
    }
    return res;
}
```


```python
from queue import PriorityQueue

def assignTasks(servers, tasks):
    n, m = len(servers), len(tasks)
    ans = [0] * m
    freeServers = PriorityQueue()

    for i in range(n):
        freeServers.put((servers[i], i))

    busyServers = PriorityQueue()
    currentTask = 0

    while currentTask < m:
        while not busyServers.empty() and busyServers.queue[0][0] <= currentTask:
            _, idx = busyServers.get()
            freeServers.put((servers[idx], idx))

        while not freeServers.empty() and currentTask < m:
            _, idx = freeServers.get()
            ans[currentTask] = idx
            busyServers.put((currentTask + tasks[currentTask], idx))
            currentTask += 1

        if freeServers.empty():
            currentTask = busyServers.queue[0][0]

    return ans
```

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

std::vector<int> assignTasks(std::vector<int>& servers, std::vector<int>& tasks) {
    int n = servers.size(), m = tasks.size();
    std::vector<int> ans(m);
    std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> freeServers;

    for (int i = 0; i < n; ++i) {
        freeServers.push({servers[i], i});
    }

    std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> busyServers;
    int currentTask = 0;

    while (currentTask < m) {
        while (!busyServers.empty() && busyServers.top().first <= currentTask) {
            freeServers.push({servers[busyServers.top().second], busyServers.top().second});
            busyServers.pop();
        }

        while (!freeServers.empty() && currentTask < m) {
            ans[currentTask] = freeServers.top().second;
            busyServers.push({currentTask + tasks[currentTask], freeServers.top().second});
            freeServers.pop();
            currentTask++;
        }

        if(freeServers.empty()) {
            currentTask = busyServers.top().first;
        }
    }

    return ans;
}
```


```python
def min_steps_to_equal_elements(nums):
    min_elem = min(nums)
    steps = 0
    for num in nums:
        steps += (num - min_elem)
    return steps
```

```cpp
int min_steps_to_equal_elements(vector<int>& nums) {
    int min_elem = *min_element(nums.begin(), nums.end());
    int steps = 0;
    for(int num : nums) {
        steps += (num - min_elem);
    }
    return steps;
}
```


```java
public int maxConsecutiveAnswers(String answerKey, int k) {
    int maxLen = 0, left = 0, TCount = 0, FCount = 0;

    for (int right = 0; right < answerKey.length(); ++right) {
        if (answerKey.charAt(right) == 'T') {
            ++TCount;
        } else {
            ++FCount;
        }

        if (Math.min(TCount, FCount) > k) {
            if (answerKey.charAt(left++) == 'T') {
                --TCount;
            } else {
                --FCount;
            }
        } else {
            maxLen = Math.max(maxLen, TCount + FCount);
        }
    }

    return maxLen;
}
```

```python
def max_consecutive_answers(answer_key: str, k: int) -> int:
    max_len, left, T_cnt, F_cnt = 0, 0, 0, 0

    for right, c in enumerate(answer_key):
        if c == 'T':
            T_cnt += 1
        else:
            F_cnt += 1

        if min(T_cnt, F_cnt) > k:
            if answer_key[left] == 'T':
                T_cnt -= 1
            else:
                F_cnt -= 1
            left += 1
        else:
            max_len = max(max_len, T_cnt + F_cnt)

    return max_len
```


```cpp
bool stoneGameIX(vector<int>& stones) {
    int cnt[3] = {0, 0, 0};
    for (int s : stones) {
        cnt[s % 3]++;
    }
    return (cnt[1] && cnt[2]) || (cnt[1] > cnt[2] ? cnt[1] > cnt[2] + 2 : cnt[2] > cnt[1] + 1);
}
```

```python
def stoneGameIX(stones: List[int]) -> bool:
    cnt = [0, 0, 0]
    for s in stones:
        cnt[s % 3] += 1
    return (cnt[1] and cnt[2]) or (cnt[1] > cnt[2] if cnt[1] > cnt[2] + 2 else cnt[2] > cnt[1] + 1)
```


```java
public int maxAlternatingSum(int[] nums) {
    long odd = 0, even = 0;
    for (int num : nums) {
        long newOdd = Math.max(even + num, odd);
        even = Math.max(odd - num, even);
        odd = newOdd;
    }
    return (int)odd;
}
```

```python
def maxAlternatingSum(nums):
    odd, even = 0, 0
    for num in nums:
        newOdd = max(even + num, odd)
        even = max(odd - num, even)
        odd = newOdd
    return odd
```


```java
import java.util.*;

public int secondMinimum(int n, int[][] edges, int time, int change) {
    List<List<Integer>> graph = new ArrayList<>();
    for (int i = 0; i <= n; i++) {
        graph.add(new ArrayList<>());
    }

    for (int[] edge : edges) {
        graph.get(edge[0]).add(edge[1]);
        graph.get(edge[1]).add(edge[0]);
    }

    int[] dist = new int[n + 1];
    int[] dist2 = new int[n + 1];
    Arrays.fill(dist, Integer.MAX_VALUE);
    Arrays.fill(dist2, Integer.MAX_VALUE);
    dist[1] = 0;

    Queue<Integer> q = new LinkedList<>();
    q.add(1);

    while (!q.isEmpty()) {
        int cur = q.poll();

        int nextDist = dist[cur] + time;
        int waitTime = (nextDist / change % 2 == 1) ? change : 0;
        nextDist += waitTime;

        for (int next : graph.get(cur)) {
            if (nextDist < dist[next]) {
                int tmp = nextDist;
                nextDist = dist[next];
                dist[next] = tmp;
                q.add(next);
            }
            if (nextDist < dist2[next]) {
                int tmp = nextDist;
                nextDist = dist2[next];
                dist2[next] = tmp;
                q.add(next);
            }
        }
    }
    return dist2[n];
}
```

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

int secondMinimum(int n, vector<vector<int>>& edges, int time, int change) {
    vector<vector<int>> graph(n + 1);
    for (const auto &edge : edges) {
        graph[edge[0]].push_back(edge[1]);
        graph[edge[1]].push_back(edge[0]);
    }

    const int INF = 1e9;
    vector<int> dist(n + 1, INF);
    vector<int> dist2(n + 1, INF);
    dist[1] = 0;

    queue<int> q;
    q.push(1);

    while (!q.empty()) {
        int cur = q.front();
        q.pop();

        int nextDist = dist[cur] + time;
        int waitTime = (nextDist / change % 2 == 1) ? change : 0;
        nextDist += waitTime;

        for (int next : graph[cur]) {
            if (nextDist < dist[next]) {
                swap(nextDist, dist[next]);
                q.push(next);
            }
            if (nextDist < dist2[next]) {
                swap(nextDist, dist2[next]);
                q.push(next);
            }
        }
    }
    return dist2[n];
}
```


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

def sortedList(head):
    if not head or not head.next:
        return head

    prev = head
    cur = head.next

    while cur:
        if cur.val < prev.val:
            prev.next = cur.next
            cur.next = head
            head = cur
            cur = prev
        else:
            prev = cur
        cur = cur.next
    return head
```

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

ListNode* sortedList(ListNode* head) {
    if (!head || !head->next) return head;

    ListNode* prev = head;
    ListNode* cur = head->next;

    while (cur) {
        if (cur->val < prev->val) {
            prev->next = cur->next;
            cur->next = head;
            head = cur;
            cur = prev;
        } else {
            prev = cur;
        }
        cur = cur->next;
    }
    return head;
}
```


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

using namespace std;

int minCost(string sentence, int k) {
    vector<string> words;
    string word;
    for (const char c : sentence) {
        if (c == ' ') {
            words.push_back(word);
            word.clear();
        } else {
            word.push_back(c);
        }
    }
    words.push_back(word);
    vector<int> dp(words.size() + 1, numeric_limits<int>::max());
    dp[0] = 0;
    for (int i = 0; i < words.size(); ++i) {
        int length = 0;
        for (int j = i; j >= 0; --j) {
            length += words[j].size();
            if (length + (i - j) <= k) {
                dp[i + 1] = min(dp[i + 1], dp[j] + (k - length - (i - j)) * (k - length - (i - j)));
            } else {
                break;
            }
            length += 1;
        }
    }
    return dp.back();
}
```

i enjoy watching stand-up comedy specials
17

i enjoy solving mathematical problems
13

i love to travel to different countries
16

i like to play basketball with my family
14

i enjoy watching stand-up comedy shows
16

i like to play guitar in my free time
15

i love to learn new programming languages
17

i like to play soccer with my friends
14

i enjoy playing video games with my friends
19

i am a big fan of science fiction books
16

```python
def minCost(sentence: str, k: int) -> int:
    words = sentence.split()
    dp = [float('inf')] * (len(words) + 1)
    dp[0] = 0
    for i in range(len(words)):
        length = 0
        j = i
        while j >= 0:
            length += len(words[j])
            if length + (i - j) <= k:
                dp[i + 1] = min(dp[i + 1], dp[j] + (k - length - (i - j)) * (k - length - (i - j)))
            else:
                break
            length += 1
            j -= 1
    return dp[-1]
```


```python
def smallest_index(nums):
    for i, num in enumerate(nums):
        if i % 10 == num:
            return i
    return -1
```

```cpp
int smallestIndex(std::vector<int>& nums) {
    for (size_t i = 0; i < nums.size(); ++i) {
        if (i % 10 == nums[i]) {
            return i;
        }
    }
    return -1;
}
```


```java
int countVowelSubstrings(String word) {
    int count = 0, a = 0, e = 0, i = 0, o = 0, u = 0;
    for (char c : word.toCharArray()) {
        if (c == 'a') a++;
        else if (c == 'e') e = a + e;
        else if (c == 'i') i = e + i;
        else if (c == 'o') o = i + o;
        else if (c == 'u') u = o + u;
    }
    return u;
}
```

aeiouuiaee uaeiou aeiouuiaoueau aeiouuiaouee aeiouuiaoueau aeiouuiaouoi aeiouuiaouuo abcdeiou aeiouuiaeuou aeiouu aeiouuiaie aeiouuu aeiouuiau aeiouuiaouuo aeiouuaeiuo aeiouuiaa aeiouuiaouea aeiouu aeiouuiaei aeiouuiauo aeiouuei aeiouuiaue aeiouuiaouoi aeiouu aeiouuiaouau aeiouuiaoue aeiouuiaio aeiouuiaoiu aeiouuiaouie aeiou aeiouuiaouoi aeiouuiaueou aeiouuiaouuo aeiouuiaouea aeiouuiaoi aeeeiiioouuua aeiouuiaeiou aeiouuiaouau aeiouuiaouea aeiouuue aeiouuiaeu bcaeiouu aeiouuiaou aeiouuiaoueau aeiouuiaouei aeiouuieu uuoeeeiiiooa aeiouuiaouee aeiouuiaouau aeiouuiaouei aeiouu aeioueia aeiouuiaouei aeiouuiaoua

```python
def count_vowel_substrings(word: str) -> int:
    count, a, e, i, o, u = 0, 0, 0, 0, 0, 0
    for c in word:
        if c == 'a': a += 1
        elif c == 'e': e = a + e
        elif c == 'i': i = e + i
        elif c == 'o': o = i + o
        elif c == 'u': u = o + u
    return u
```


```cpp
#include<vector>

int maxQuality_dfs(int node, int time_left, std::vector<int>& visited, std::vector<int>& values, std::vector<std::vector<int>>& neighbors) {
    int acc = 0;
    for (const auto& edge : neighbors[node]) {
        int neighbor = edge[0], cost = edge[1];
        if (time_left >= cost && visited[neighbor] == 0) {
            visited[neighbor] = 1;
            acc = std::max(acc, values[neighbor] + maxQuality_dfs(neighbor, time_left - cost, visited, values, neighbors));
            visited[neighbor] = 0;
        }
    }
    return acc;
}

int maxQuality(std::vector<int>& values, std::vector<std::vector<int>>& edges, int maxTime) {
    std::vector<std::vector<int>> neighbors(values.size());
    for (const auto& edge : edges) {
        neighbors[edge[0]].push_back({edge[1], edge[2]});
        neighbors[edge[1]].push_back({edge[0], edge[2]});
    }
    std::vector<int> visited(values.size(), 0);
    return maxQuality_dfs(0, maxTime, visited, values, neighbors);
}
```

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

public int maxQuality_dfs(int node, int time_left, int[] visited, int[] values, List<List<int[]>> neighbors) {
    int acc = 0;
    for (int[] edge : neighbors.get(node)) {
        int neighbor = edge[0], cost = edge[1];
        if (time_left >= cost && visited[neighbor] == 0) {
            visited[neighbor] = 1;
            acc = Math.max(acc, values[neighbor] + maxQuality_dfs(neighbor, time_left - cost, visited, values, neighbors));
            visited[neighbor] = 0;
        }
    }
    return acc;
}

public int maxQuality(int[] values, int[][] edges, int maxTime) {
    List<List<int[]>> neighbors = new ArrayList<>();
    for (int i = 0; i < values.length; i++) {
        neighbors.add(new ArrayList<>());
    }
    for (int[] edge : edges) {
        neighbors.get(edge[0]).add(new int[]{edge[1], edge[2]});
        neighbors.get(edge[1]).add(new int[]{edge[0], edge[2]});
    }
    int[] visited = new int[values.length];
    return maxQuality_dfs(0, maxTime, visited, values, neighbors);
}
```


```python
def maxTasks(tasks, workers, pills, strength):
  tasks.sort()
  workers.sort()

  cnt = 0
  i = 0
  for j in range(pills):
    while i < len(tasks) and tasks[i] > workers[j] + strength:
      i += 1
    if i < len(tasks):
      cnt += 1
      i += 1

  i = 0
  for j in range(pills, len(workers)):
    if i < len(tasks) and tasks[i] <= workers[j]:
      cnt += 1
      i += 1

  return cnt
```

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

int maxTasks(std::vector<int>& tasks, std::vector<int>& workers, int pills, int strength) {
  std::sort(tasks.begin(), tasks.end());
  std::sort(workers.begin(), workers.end());

  int cnt = 0;
  for (int i = 0, j = 0; j < pills; ++j) {
    while (i < tasks.size() && tasks[i] > workers[j] + strength) {
      ++i;
    }
    if (i < tasks.size()) {
      ++cnt;
      ++i;
    }
  }

  for (int i = 0, j = pills; i < tasks.size() && j < workers.size(); ++i) {
    if (tasks[i] <= workers[j]) {
      ++cnt;
      ++j;
    }
  }

  return cnt;
}
```


```python
def time_to_buy_tickets(tickets, k):
    time = 0
    while tickets[k] > 0:
        for i in range(len(tickets)):
            if tickets[i] > 0:
                tickets[i] -= 1
                time += 1
                if i == k and tickets[k] == 0:
                    break
    return time
```

```cpp
int time_to_buy_tickets(vector<int>& tickets, int k) {
    int time = 0;
    while (tickets[k] > 0) {
        for (int i = 0; i < tickets.size(); ++i) {
            if (tickets[i] > 0) {
                --tickets[i];
                ++time;
                if (i == k && tickets[k] == 0) {
                    break;
                }
            }
        }
    }
    return time;
}
```


```python
class Solution:
    def reverseGroup(self, head, k):
        if not head or k == 1:
            return head
        prev = None
        cur = head
        for _ in range(k):
            next = cur.next
            cur.next = prev
            prev = cur
            cur = next
        head.next = cur
        return prev

    def reverseEvenGroups(self, head):
        dummy = ListNode(0)
        dummy.next = head
        prev = dummy
        n = 0
        cur = head
        while cur:
            n += 1
            cur = cur.next
        i, k = 1, 1
        while n >= 0 and k <= n:
            if i % 2 == 0:
                tail = prev.next
                next = prev.next
                for _ in range(k):
                    next = next.next
                prev.next = self.reverseGroup(tail, k)
                tail.next = next
            n -= k
            for _ in range(k):
                prev = prev.next
            i += 1
            k += i
        return dummy.next
```

```cpp
class Solution {
public:
    ListNode* reverseGroup(ListNode* head, int k) {
        if (head == nullptr || k == 1) return head;
        ListNode* prev = nullptr;
        ListNode* cur = head;
        for (int i = 0; i < k; i++) {
            ListNode* next = cur->next;
            cur->next = prev;
            prev = cur;
            cur = next;
        }
        head->next = cur;
        return prev;
    }

    ListNode* reverseEvenGroups(ListNode* head) {
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* prev = dummy;
        int n = 0;
        for (ListNode* cur = head; cur != nullptr; cur = cur->next)
            n++;
        for (int i = 1, k = 1; n >= 0 && k <= n; i++, k += i) {
            if (i % 2 == 0) {
                ListNode* tail = prev->next;
                ListNode* next = prev->next;
                for (int j = 0; j < k; j++)
                    next = next->next;
                prev->next = reverseGroup(tail, k);
                tail->next = next;
            }
            n -= k;
            for (int j = 0; j < k && prev != nullptr; j++)
                prev = prev->next;
        }
        return dummy->next;
    }
};
```


```python
def largest_even_sum(nums, k):
    evens = sorted([num for num in nums if num % 2 == 0], reverse=True)
    odds = sorted([num for num in nums if num % 2 != 0], reverse=True)

    sum = 0
    for _ in range(k):
        if evens:
            sum += evens.pop()

    for _ in range(0, k - 1, 2):
        if odds:
            first = odds.pop()
            if odds:
                second = odds.pop()
                sum += first + second

    return sum if sum % 2 == 0 else -1
```

```java
public int largestEvenSum(int[] nums, int k) {
    List<Integer> evens = new ArrayList<>();
    List<Integer> odds = new ArrayList<>();
    for (int num : nums) {
        if (num % 2 == 0) {
            evens.add(num);
        } else {
            odds.add(num);
        }
    }
    evens.sort(Collections.reverseOrder());
    odds.sort(Collections.reverseOrder());

    int sum = 0;
    for (int i = 0; i < k && !evens.isEmpty(); i++) {
        sum += evens.remove(evens.size() - 1);
    }

    for (int i = 0; i < k - 1 && !odds.isEmpty(); i += 2) {
        int first = odds.remove(odds.size() - 1);
        if (!odds.isEmpty()) {
            int second = odds.remove(odds.size() - 1);
            sum += first + second;
        }
    }

    if (sum % 2 == 0) {
        return sum;
    } else {
        return -1;
    }
}
```


```cpp
int numSmoothDescentPeriods(vector<int>& prices) {
    int result = 0;
    int count = 0;
    for (int i = 1; i < prices.size(); ++i) {
        if (prices[i] == prices[i - 1] - 1) {
            ++count;
        } else {
            count = 0;
        }
        result += count + 1;
    }
    return result + 1;
}
```

```python
def num_smooth_descent_periods(prices):
    result = 0
    count = 0
    for i in range(1, len(prices)):
        if prices[i] == prices[i - 1] - 1:
            count += 1
        else:
            count = 0
        result += count + 1
    return result + 1
```


```python
def numberOfWeakCharacters(properties):
    properties.sort(key=lambda x: (x[0], -x[1]))

    max_defense = 0
    weak_count = 0
    for attack, defense in reversed(properties):
        if defense < max_defense:
            weak_count += 1
        else:
            max_defense = defense

    return weak_count
```

```java
import java.util.Arrays;

public int numberOfWeakCharacters(int[][] properties) {
    Arrays.sort(properties, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);

    int maxDefense = 0, weakCount = 0;
    for (int i = properties.length - 1; i >= 0; i--) {
        if (properties[i][1] < maxDefense) {
            weakCount++;
        } else {
            maxDefense = properties[i][1];
        }
    }

    return weakCount;
}
```


```java
public boolean canSortUsingSwap(int[] nums) {
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] < nums[i - 1]) {
            int temp = nums[i];
            nums[i] = nums[i - 1];
            nums[i - 1] = temp;
            if (isSorted(nums)) {
                return true;
            }
            temp = nums[i];
            nums[i] = nums[i - 1];
            nums[i - 1] = temp;
        }
    }
    return false;
}

private boolean isSorted(int[] nums) {
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] < nums[i - 1]) {
            return false;
        }
    }
    return true;
}
```

false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false

```cpp
#include <vector>

bool canSortUsingSwap(std::vector<int>& nums) {
    for (size_t i = 1; i < nums.size(); i++) {
        if (nums[i] < nums[i - 1]) {
            std::swap(nums[i], nums[i - 1]);
            if (std::is_sorted(nums.begin(), nums.end())) {
                return true;
            }
            std::swap(nums[i], nums[i - 1]);
        }
    }
    return false;
}
```


```cpp
int maxInvited(vector<int>& favorite) {
    vector<int> in_degree(favorite.size(), 0);
    for (int fav : favorite) {
        in_degree[fav]++;
    }
    int result = 0;
    for (int degree : in_degree) {
        result += max(degree - 1, 0);
    }
    return min(result + 2, (int)favorite.size());
}
```

```python
def max_invited(favorite):
    in_degree = [0] * len(favorite)
    for fav in favorite:
        in_degree[fav] += 1
    result = 0
    for degree in in_degree:
        result += max(degree - 1, 0)
    return min(result + 2, len(favorite))
```


```java
public int[][] construct2DArray(int[] original, int m, int n) {
    if (m * n != original.length) return new int[][]{};
    int[][] res = new int[m][n];
    for (int i = 0; i < original.length; ++i) {
        res[i / n][i % n] = original[i];
    }
    return res;
}
```

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

vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
    if (m * n != original.size()) return {};
    vector<vector<int>> res(m, vector<int>(n));
    for (int i = 0; i < original.size(); ++i) {
        res[i / n][i % n] = original[i];
    }
    return res;
}
```


```python
def earliestBlooms(plantTime, growTime):
    n = len(plantTime)
    processTime = list(zip(plantTime, growTime))
    processTime.sort()

    day = 0
    blooms = 0
    for p in processTime:
        day += p[0]
        blooms = max(blooms, day + p[1])
    return blooms
```

```cpp
int earliestBlooms(vector<int>& plantTime, vector<int>& growTime) {
    int n = plantTime.size();
    vector<pair<int, int>> processTime;
    for (int i = 0; i < n; ++i) {
        processTime.push_back({plantTime[i], growTime[i]});
    }
    sort(processTime.begin(), processTime.end());

    int day = 0;
    int blooms = 0;
    for (auto& p : processTime) {
        day += p.first;
        blooms = max(blooms, day + p.second);
    }
    return blooms;
}
```


```java
public int max_computer_runtime(int n, int[] batteries) {
    Arrays.sort(batteries);
    int result = 0;
    for (int i = 0; i < batteries.length; i++) {
        result = Math.max(result, Math.min(n, batteries.length - i) * batteries[i]);
    }
    return result;
}
```

```cpp
int max_computer_runtime(int n, vector<int>& batteries) {
    sort(batteries.begin(), batteries.end());
    int result = 0;
    for (int i = 0; i < batteries.size(); ++i) {
        result = max(result, min(n, int(batteries.size()) - i) * batteries[i]);
    }
    return result;
}
```


```python
def max_difference(nums):
    min_val = nums[0]
    max_diff = -1

    for i in range(1, len(nums)):
        if nums[i] > min_val:
            max_diff = max(max_diff, nums[i] - min_val)
        else:
            min_val = nums[i]

    return max_diff
```

```cpp
int maxDifference(vector<int>& nums) {
    int min_val = nums[0];
    int max_diff = -1;

    for (int i = 1; i < nums.size(); ++i) {
        if (nums[i] > min_val) {
            max_diff = max(max_diff, nums[i] - min_val);
        } else {
            min_val = nums[i];
        }
    }
    return max_diff;
}
```


```java
public boolean solvePuzzle(String colors) {
    int countA = 0;
    for (char c : colors.toCharArray()) {
        if (c == 'A') countA++;
    }
    return countA % 2 == 1;
}
```

False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False

```python
def solve_puzzle(colors: str) -> bool:
    return colors.count('A') % 2 == 1
```


```python
 from collections import Counter

def lonelyNumbers(nums):
    count = Counter(nums)
    result = []

    for k, v in count.items():
        if v == 1 and k - 1 not in count and k + 1 not in count:
            result.append(k)

    return result
```

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

public List<Integer> lonelyNumbers(int[] nums) {
    Map<Integer, Integer> count = new HashMap<>();
    List<Integer> result = new ArrayList<>();

    for (int num : nums) {
        count.put(num, count.getOrDefault(num, 0) + 1);
    }

    for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
        if (entry.getValue() == 1 && !count.containsKey(entry.getKey() - 1) && !count.containsKey(entry.getKey() + 1)) {
            result.add(entry.getKey());
        }
    }

    return result;
}
```


```cpp
#include <unordered_set>
#include <utility>

int minStraightLines(vector<vector<int>>& points) {
    int len = points.size();
    unordered_set<int> uh;
    for (int i = 0; i < len; i++) {
        for (int j = i + 1; j < len; j++) {
            if (i != j) {
                int delta_x = points[j][0] - points[i][0];
                int delta_y = points[j][1] - points[i][1];
                int gcd = __gcd(delta_x, delta_y);
                delta_x /= gcd;
                delta_y /= gcd;
                uh.insert(delta_y * 1000 + delta_x);
            }
        }
    }
    return uh.size();
}
```

```python
from math import gcd
from itertools import combinations

def minStraightLines(points):
    lines = set()
    for p1, p2 in combinations(points, 2):
        dy, dx = p2[1] - p1[1], p2[0] - p1[0]
        g = gcd(dx, dy)
        lines.add((dy // g, dx // g))
    return len(lines)
```


```python
def alice_wins(stones):
    sum_, count = 0, [0] * 3
    for stone in stones:
        sum_ += stone
        count[stone % 3] += 1
    if sum_ % 3:
        return count[sum_ % 3] % 2 == 1
    return count[1] % 2 == 0 or count[2] % 2 == 0 or count[1] == 0 or count[2] == 0
```

s =  "leetcode ", power = 7, modulo = 20, k = 2, hashValue = 0

true
true
true
true
true
true
true
true
true
true
true
true
true
true

```cpp
bool aliceWins(std::vector<int> &stones) {
    int sum = 0, count[3] = {0};
    for (int stone : stones) {
        sum += stone;
        count[stone % 3]++;
    }
    if (sum % 3) {
        return count[sum % 3] % 2 == 1;
    }
    return count[1] % 2 == 0 || count[2] % 2 == 0 || count[1] == 0 || count[2] == 0;
}
```


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

public Vector<Integer> paintingPlan(int[][] paint) {
    Vector<Integer> worklog = new Vector<>(paint.length);
    Set<Integer> painted = new HashSet<>();

    for (int i = 0; i < paint.length; i++) {
        int start = paint[i][0];
        int end = paint[i][1];
        int day_work = 0;

        for (int j = start; j < end; j++) {
            if (!painted.contains(j)) {
                painted.add(j);
                day_work++;
            }
        }

        worklog.add(day_work);
    }

    return worklog;
}
```

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

std::vector<int> paintingPlan(const std::vector<std::vector<int>>& paint) {
    std::vector<int> worklog(paint.size(), 0);
    std::set<int> painted;

    for (std::size_t i = 0; i < paint.size(); ++i) {
        int start = paint[i][0];
        int end = paint[i][1];

        for (int j = start; j < end; ++j) {
            if (painted.count(j) == 0) {
                painted.insert(j);
                worklog[i]++;
            }
        }
    }

    return worklog;
}
```


```cpp
int min_time_to_remove_illegal_goods(string s) {
    int ones = 0, twos = 0;
    for (char c : s) {
        if (c == '1') {
            twos += ones;
            ones++;
        }
    }
    return ones + min(ones, twos);
}
```

```python
def min_time_to_remove_illegal_goods(s: str) -> int:
    ones = twos = 0
    for c in s:
        if c == '1':
            twos += ones
            ones += 1
    return ones + min(ones, twos)
```


```java
import java.util.*;

public boolean areNumbersIncreasing(String s) {
    Scanner scanner = new Scanner(s);
    ArrayList<Integer> numbers = new ArrayList<>();

    while (scanner.hasNext()) {
        if (scanner.hasNextInt()) {
            int num = scanner.nextInt();
            if (!numbers.isEmpty() && numbers.get(numbers.size() - 1) >= num) {
                return false;
            }
            numbers.add(num);
        } else {
            scanner.next();
        }
    }

    return true;
}
```

```python
def are_numbers_increasing(s: str) -> bool:
    tokens = s.split()
    numbers = []

    for token in tokens:
        if token.isdigit():
            num = int(token)
            if numbers and numbers[-1] >= num:
                return False
            numbers.append(num)

    return True
```


```python
def max_beauty(items, queries):
    sorted_items = [0] * 10001
    for price, beauty in items:
        sorted_items[price] = max(sorted_items[price], beauty)

    for i in range(1, len(sorted_items)):
        sorted_items[i] = max(sorted_items[i], sorted_items[i - 1])

    return [sorted_items[query] for query in queries]
```

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

vector<int> maxBeauty(vector<vector<int>>& items, vector<int>& queries) {
    vector<int> sortedItems(10001, 0);
    for (auto& item : items) {
        sortedItems[item[0]] = max(sortedItems[item[0]], item[1]);
    }

    for (int i = 1; i < sortedItems.size(); ++i) {
        sortedItems[i] = max(sortedItems[i], sortedItems[i-1]);
    }

    vector<int> result;
    for (int query : queries) {
        result.push_back(sortedItems[query]);
    }
    return result;
}
```


```python
def count_pyramids(grid):
    m, n, count = len(grid), len(grid[0]), 0
    for i in range(1, m - 1):
        for j in range(1, n - 1):
            if grid[i][j] == grid[i - 1][j] + grid[i][j - 1] - grid[i - 1][j - 1] \
                and grid[i][j] == grid[i + 1][j] + grid[i][j + 1] - grid[i + 1][j + 1]:
                count += grid[i][j]
    return count
```

zz xxx yyyy zyz zyz zzyy yxy aabb z ab xyx abba yxyx xxy xxyy yxx yxyx yxy yyy abba zzy ab yzyy a xxx zy y yxxy yxxy xxyy aabb xxy zzy yy yzyy xyxy yyyy yzzy baab xxyy abba baab xxyy yzzy zz zy mada xyxy yxx xyxy yyy y xyx z a aabb a xyxy zzyy yy

```cpp
int countPyramids(vector<vector<int>> &grid) {
    int m = grid.size(), n = grid[0].size(), count = 0;
    for (int i = 1; i < m - 1; ++i) {
        for (int j = 1; j < n - 1; ++j) {
            if (grid[i][j] == grid[i - 1][j] + grid[i][j - 1] - grid[i - 1][j - 1]
                && grid[i][j] == grid[i + 1][j] + grid[i][j + 1] - grid[i + 1][j + 1]) {
                count += grid[i][j];
            }
        }
    }
    return count;
}
```


```java
public int timeToBuyTickets(int[] tickets, int k) {
    int time = 0;
    while (tickets[k] > 0) {
        for (int i = 0; i < tickets.length; i++) {
            if (tickets[i] > 0) {
                tickets[i]--;
                time++;
                if (i == k && tickets[k] == 0)
                    return time;
            }
        }
    }
    return time;
}
```

```cpp
int timeToBuyTickets(vector<int>& tickets, int k) {
    int time = 0;
    while (tickets[k] > 0) {
        for (int i = 0; i < tickets.size(); i++) {
            if (tickets[i] > 0) {
                tickets[i]--;
                time++;
                if (i == k && tickets[k] == 0)
                    return time;
            }
        }
    }
    return time;
}
```


```java
import java.util.*;

public class Main {
    public boolean[] checkFriends(int n, int[][] restrictions, int[][] requests) {
        List<Set<Integer>> friends = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            friends.add(new HashSet<>());
        }
        for (int[] restriction : restrictions) {
            friends.get(restriction[0]).add(restriction[1]);
            friends.get(restriction[1]).add(restriction[0]);
        }

        boolean[] result = new boolean[requests.length];
        for (int i = 0; i < requests.length; i++) {
            int a = requests[i][0];
            int b = requests[i][1];
            if (!friends.get(a).contains(b) && !friends.get(b).contains(a)) {
                friends.get(a).add(b);
                friends.get(b).add(a);
                result[i] = true;
            } else {
                result[i] = false;
            }
        }
        return result;
    }
}
```

```cpp
#include <vector>
#include <unordered_set>

using namespace std;

vector<bool> checkFriends(int n, vector<vector<int>>& restrictions, vector<vector<int>>& requests) {
    vector<unordered_set<int>> friends(n);
    for (auto& restriction : restrictions) {
        friends[restriction[0]].insert(restriction[1]);
        friends[restriction[1]].insert(restriction[0]);
    }

    vector<bool> result(requests.size());
    for (int i = 0; i < requests.size(); i++) {
        int a = requests[i][0];
        int b = requests[i][1];
        if (friends[a].count(b) == 0 && friends[b].count(a) == 0) {
            friends[a].insert(b);
            friends[b].insert(a);
            result[i] = true;
        } else {
            result[i] = false;
        }
    }
    return result;
}
```


```python
import heapq

def largest_sum_sequence(nums, k):
    min_heap = []

    for num in nums:
        heapq.heappush(min_heap, num)
        if len(min_heap) > k:
            heapq.heappop(min_heap)

    result = [0] * k
    for i in range(k-1, -1, -1):
        result[i] = heapq.heappop(min_heap)

    return result
```

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

std::vector<int> largestSumSequence(std::vector<int>& nums, int k) {
    std::priority_queue<int, std::vector<int>, std::greater<int>> min_heap;

    for (int num : nums) {
        min_heap.push(num);
        if (min_heap.size() > k) {
            min_heap.pop();
        }
    }

    std::vector<int> result(min_heap.size());
    while (!min_heap.empty()) {
        result[min_heap.size() - 1] = min_heap.top();
        min_heap.pop();
    }

    return result;
}
```


```cpp
int min_health(int damage[], int n, int armor) {
    int health = 0;
    for (int i = n - 1; i >= 0; --i) {
        health += damage[i];
        if (health > armor) {
            health -= armor;
            armor = 0;
        }
    }
    return health + 1;
}
```

```python
def min_health(damage, armor):
    health = 0
    for dmg in reversed(damage):
        health += dmg
        if health > armor:
            health -= armor
            armor = 0
    return health + 1
```


```java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Solution {
    void helper(int[] digits, ArrayList<Integer> current, Set<Integer> result, boolean[] used) {
        if (current.size() == digits.length) {
            int num = 0;
            for (int d : current) {
                num = num * 10 + d;
            }
            result.add(num);
            return;
        }
        for (int i = 0; i < digits.length; ++i) {
            if (!used[i]) {
                used[i] = true;
                current.add(digits[i]);
                helper(digits, current, result, used);
                current.remove(current.size() - 1);
                used[i] = false;
            }
        }
    }

    public List<Integer> uniquePermutations(int[] digits) {
        ArrayList<Integer> current = new ArrayList<>();
        Set<Integer> result = new HashSet<>();
        boolean[] used = new boolean[digits.length];
        java.util.Arrays.sort(digits);

        helper(digits, current, result, used);

        return result.stream().sorted().collect(Collectors.toList());
    }
}
```

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

void helper(vector<int>& digits, vector<int>& current, set<int>& result, vector<bool>& used) {
    if (current.size() == digits.size()) {
        int num = 0;
        for (int d : current) {
            num = num * 10 + d;
        }
        result.insert(num);
        return;
    }
    for (int i = 0; i < digits.size(); ++i) {
        if (!used[i]) {
            used[i] = true;
            current.push_back(digits[i]);
            helper(digits, current, result, used);
            current.pop_back();
            used[i] = false;
        }
    }
}

vector<int> uniquePermutations(vector<int>& digits) {
    vector<int> current;
    set<int> result;
    vector<bool> used(digits.size(), false);
    sort(digits.begin(), digits.end());

    helper(digits, current, result, used);

    return vector<int>(result.begin(), result.end());
}
```


```java
int minimumOperations(String current, String correct) {
    int ch = Integer.parseInt(current.substring(0, 2)), cm = Integer.parseInt(current.substring(3));
    int th = Integer.parseInt(correct.substring(0,2)), tm = Integer.parseInt(correct.substring(3));
    int ct = ch * 60 + cm, tt = th * 60 + tm;

    int operations = 0;
    while (ct < tt) {
        if (tt - ct >= 60)
            ct += 60;
        else if (tt - ct >= 15)
            ct += 15;
        else if (tt - ct >= 5)
            ct += 5;
        else
            ct += 1;

        operations++;
    }
    return operations;
}
```

```python
def minimum_operations(current: str, correct: str) -> int:
    ch, cm = map(int, current.split(':'))
    th, tm = map(int, correct.split(':'))
    ct = ch * 60 + cm
    tt = th * 60 + tm

    operations = 0
    while ct < tt:
        if tt - ct >= 60:
            ct += 60
        elif tt - ct >= 15:
            ct += 15
        elif tt - ct >= 5:
            ct += 5
        else:
            ct += 1

        operations += 1

    return operations
```


```python
from bisect import bisect_left

def maxFruits(fruits, startPos, k):
    n = len(fruits)
    left, right = [0] * (n + 1), [0] * (n + 1)
    j = 0

    for i in range(n):
        while j < n and fruits[j][0] - fruits[i][0] <= k:
            right[i + 1] += fruits[j][1]
            j += 1
        right[i + 1] += right[i]
        if j < n and fruits[j][0] - startPos <= k:
            right[0] += fruits[j][1]
            j += 1

    j = n - 1
    for i in range(n - 1, -1, -1):
        while j >= 0 and fruits[j][0] - fruits[i][0] <= k:
            left[i] += fruits[j][1]
            j -= 1
        left[i] += left[i + 1]

    ans = 0
    for i in range(n):
        rest = max(0, k - abs(fruits[i][0] - startPos))
        idx = bisect_left(fruits, [fruits[i][0] + rest, 0])
        ans = max(ans, left[i] + right[idx])

    return ans
```

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

int maxFruits(vector<vector<int>>& fruits, int startPos, int k) {
    int n = fruits.size();
    vector<int> left(n + 1, 0), right(n + 1, 0);
    int j = 0;

    for (int i = 0; i < n; i++) {
        while (j < n && fruits[j][0] - fruits[i][0] <= k) {
            right[i + 1] += fruits[j][1];
            j++;
        }
        right[i + 1] += right[i];
        if (j < n && fruits[j][0] - startPos <= k) {
            right[0] += fruits[j][1];
            j++;
        }
    }

    j = n - 1;
    for (int i = n - 1; i >= 0; i--) {
        while (j >= 0 && fruits[j][0] - fruits[i][0] <= k) {
            left[i] += fruits[j][1];
            j--;
        }
        left[i] += left[i + 1];
    }

    int ans = 0;
    for (int i = 0; i < n; i++) {
        int rest = max(0, k - abs(fruits[i][0] - startPos));
        int idx = upper_bound(fruits.begin(), fruits.end(), vector<int>{fruits[i][0] + rest, 0}) - fruits.begin();
        ans = max(ans, left[i] + right[idx]);
    }
    return ans;
}
```


```java
public int smoothDescentPeriods(int[] prices) {
    int count = 0;
    for (int i = 1; i < prices.length; ++i) {
        if (prices[i] == prices[i - 1] - 1) {
            while (i < prices.length && prices[i] == prices[i - 1] - 1) {
                i++;
            }
            count++;
        }
    }
    return count;
}
```

```cpp
#include <vector>

int smoothDescentPeriods(std::vector<int>& prices) {
    int count = 0;
    for (int i = 1; i < prices.size(); ++i) {
        if (prices[i] == prices[i - 1] - 1) {
            while (i < prices.size() && prices[i] == prices[i - 1] - 1) {
                i++;
            }
            count++;
        }
    }
    return count;
}
```


```python
from collections import defaultdict

def sum_of_intervals(arr):
    n = len(arr)
    indices = defaultdict(list)
    intervals = [0] * n

    for i in range(n):
        indices[arr[i]].append(i)

    for i in range(n):
        for index in indices[arr[i]]:
            intervals[i] += abs(index - i)

    return intervals
```

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

vector<int> sumOfIntervals(vector<int>& arr) {
    int n = arr.size();
    vector<vector<int>> indices(101);
    vector<int> intervals(n, 0);

    for (int i = 0; i < n; ++i) {
        indices[arr[i]].push_back(i);
    }

    for (int i = 0; i < n; ++i) {
        for (int index : indices[arr[i]]) {
            intervals[i] += abs(index - i);
        }
    }

    return intervals;
}
```


```python
def maxScore(scores, edges):
    adj_list = [[] for _ in range(len(scores))]
    result = -1

    for edge in edges:
        adj_list[edge[0]].append(edge[1])
        adj_list[edge[1]].append(edge[0])

    for edge in edges:
        for neighbor in adj_list[edge[0]]:
            for next in adj_list[edge[1]]:
                if next != neighbor and next != edge[0]:
                    result = max(result, scores[edge[0]] + scores[edge[1]] + scores[neighbor] + scores[next])

    return result
```

```java
public int maxScore(int[] scores, int[][] edges) {
    ArrayList<ArrayList<Integer>> adj_list = new ArrayList<>(scores.length);
    for (int i = 0; i < scores.length; i++) {
        adj_list.add(new ArrayList<>());
    }

    for (int[] edge : edges) {
        adj_list.get(edge[0]).add(edge[1]);
        adj_list.get(edge[1]).add(edge[0]);
    }

    int result = -1;
    for (int[] edge : edges) {
        for (int neighbor : adj_list.get(edge[0])) {
            for (int next : adj_list.get(edge[1])) {
                if (next != neighbor && next != edge[0]) {
                    result = Math.max(result, scores[edge[0]] + scores[edge[1]] + scores[neighbor] + scores[next]);
                }
            }
        }
    }

    return result;
}
```


```java
import java.util.*;

public int maxInvites(int[] favorite) {
    int n = favorite.length;
    int[] dp = new int[n];
    int maxInvites = 0;

    for (int i = 0; i < n; i++) {
        dp[i] = (i == favorite[favorite[i]]) ? 2 : 1;
        maxInvites = Math.max(maxInvites, dp[i]);
    }

    return maxInvites;
}
```

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

int maxInvites(std::vector<int>& favorite) {
    int n = favorite.size();
    std::vector<int> dp(n, 0);
    int max_invites = 0;

    for (int i = 0; i < n; ++i) {
        dp[i] = (i == favorite[favorite[i]]) ? 2 : 1;
        max_invites = std::max(max_invites, dp[i]);
    }

    return max_invites;
}
```


```java
import java.util.List;

public int dfs(int currCity, int remainingHighways, int costSoFar, List<List<Integer>> highways, boolean[] visited) {
    if (remainingHighways == 0) {
        return costSoFar;
    }

    visited[currCity] = true;
    int maxCost = -1;

    for (List<Integer> highway : highways) {
        int nextCity = -1;
        if (highway.get(0) == currCity && !visited[highway.get(1)]) {
            nextCity = highway.get(1);
        } else if (highway.get(1) == currCity && !visited[highway.get(0)]) {
            nextCity = highway.get(0);
        }

        if (nextCity != -1) {
            int cost = dfs(nextCity, remainingHighways - 1, costSoFar + highway.get(2), highways, visited);
            maxCost = Math.max(maxCost, cost);
        }
    }

    visited[currCity] = false;
    return maxCost;
}

public int maxCost(int n, List<List<Integer>> highways, int k) {
    boolean[] visited = new boolean[n];
    int maxCost = -1;

    for (int i = 0; i < n; i++) {
        int cost = dfs(i, k, 0, highways, visited);
        maxCost = Math.max(maxCost, cost);
    }

    return maxCost;
}
```

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

using namespace std;

int dfs(int curr_city, int remaining_highways, int cost_so_far, vector<vector<int>>& highways, vector<bool>& visited) {
    if (remaining_highways == 0) {
        return cost_so_far;
    }

    visited[curr_city] = true;
    int max_cost = -1;

    for (vector<int>& highway : highways) {
        int next_city = -1;
        if (highway[0] == curr_city && !visited[highway[1]]) {
            next_city = highway[1];
        } else if (highway[1] == curr_city && !visited[highway[0]]) {
            next_city = highway[0];
        }

        if (next_city != -1) {
            int cost = dfs(next_city, remaining_highways - 1, cost_so_far + highway[2], highways, visited);
            max_cost = max(max_cost, cost);
        }
    }

    visited[curr_city] = false;
    return max_cost;
}

int maxCost(int n, vector<vector<int>>& highways, int k) {
    vector<bool> visited(n, false);
    int max_cost = -1;

    for (int i = 0; i < n; i++) {
        int cost = dfs(i, k, 0, highways, visited);
        max_cost = max(max_cost, cost);
    }

    return max_cost;
}
```


```cpp
int splitAndMinimize(int num) {
    int a = num / 1000;
    int b = (num % 1000) / 100;
    int c = (num % 100) / 10;
    int d = num % 10;
    return ((a * 10 + c) * 10 + b) * 10 + d;
}
```


```python
def rearrange_array_around_pivot(nums, pivot):
    return sorted(nums, key=lambda x: (x >= pivot, x))
```

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

std::vector<int> rearrangeArrayAroundPivot(std::vector<int>& nums, int pivot) {
    std::partition(nums.begin(), nums.end(), [pivot](int num) { return num < pivot; });
    return nums;
}
```


```python
def lonely_numbers(nums):
    num_set = set(nums)
    lonely = []
    for num in nums:
        if num - 1 not in num_set and num + 1 not in num_set:
            lonely.append(num)
    return lonely
```

```java
import java.util.HashSet;
import java.util.ArrayList;

public ArrayList<Integer> lonelyNumbers(int[] nums) {
    HashSet<Integer> num_set = new HashSet<>();
    for (int num : nums) {
        num_set.add(num);
    }
    ArrayList<Integer> lonely = new ArrayList<>();
    for (int num : nums) {
        if (!num_set.contains(num - 1) && !num_set.contains(num + 1)) {
            lonely.add(num);
        }
    }
    return lonely;
}
```


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

public List<String> anagramOperations(String[] words) {
    List<String> result = new ArrayList<>();
    result.add(words[0]);

    for (int i = 1; i < words.length; i++) {
        char[] first = words[i].toCharArray();
        char[] second = words[i - 1].toCharArray();
        Arrays.sort(first);
        Arrays.sort(second);

        if (!Arrays.equals(first, second)) {
            result.add(words[i]);
        }
    }

    return result;
}
```

words = \[ "abba ", "baba ", "bbaa ", "cd ", "cd "\]

abc def ghi jkl mno pqr stu vwxyz ab ba cd dc ef

abc def ghi jkl mno pqr stu vwxyz ab cd ef

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

std::vector<std::string> anagramOperations(std::vector<std::string> &words) {
    for (int i = 1; i < words.size(); ++i) {
        std::string s1 = words[i];
        std::string s2 = words[i - 1];
        std::sort(s1.begin(), s1.end());
        std::sort(s2.begin(), s2.end());
        if (s1 == s2) {
            words.erase(words.begin() + i);
            --i;
        }
    }
    return words;
}
```


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

std::vector<int> closestNodes(int n, std::vector<std::vector<int>>& edges, std::vector<std::vector<int>>& query) {
    std::vector<int> answer;

    std::vector<std::vector<int>> tree(n);
    for (auto& edge : edges) {
        tree[edge[0]].push_back(edge[1]);
        tree[edge[1]].push_back(edge[0]);
    }

    auto bfs = [&](int start, int end) {
        std::queue<int> q;
        std::vector<bool> visited(n, false);
        q.push(start);
        visited[start] = true;

        while (!q.empty()) {
            int current = q.front();
            q.pop();

            if (current == end) {
                return current;
            }

            for (int neighbor : tree[current]) {
                if (!visited[neighbor]) {
                    q.push(neighbor);
                    visited[neighbor] = true;
                }
            }
        }
        return -1;
    };

    for (auto& q : query) {
        int lca = bfs(q[0], q[1]);
        int node1 = bfs(lca, q[0]);
        int node2 = bfs(lca, q[1]);
        answer.push_back(node1 == q[2] ? q[0] : q[1]);
    }

    return answer;
}
```

```python
from collections import deque

def closest_nodes(n, edges, query):
    answer = []
    tree = [[] for _ in range(n)]

    for edge in edges:
        tree[edge[0]].append(edge[1])
        tree[edge[1]].append(edge[0])

    def bfs(start, end):
        queue = deque([start])
        visited = {start}

        while queue:
            current = queue.popleft()

            if current == end:
                return current

            for neighbor in tree[current]:
                if neighbor not in visited:
                    queue.append(neighbor)
                    visited.add(neighbor)

    for q in query:
        lca = bfs(q[0], q[1])
        node1 = bfs(lca, q[0])
        node2 = bfs(lca, q[1])
        answer.append(q[0] if node1 == q[2] else q[1])

    return answer
```


```java
public int[][] visiblePeople(int[][] heights) {
    int m = heights.length, n = heights[0].length;
    int[][] answer = new int[m][n];

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            for (int k = j+1; k < n && heights[i][j] >= heights[i][k]; k++) {
                if (heights[i][j] > heights[i][k]) answer[i][j]++;
            }
            for (int k = i+1; k < m && heights[i][j] >= heights[k][j]; k++) {
                if (heights[i][j] > heights[k][j]) answer[i][j]++;
            }
        }
    }

    return answer;
}
```

```python
def visible_people(heights):
    m, n = len(heights), len(heights[0])
    answer = [[0 for _ in range(n)] for _ in range(m)]

    for i in range(m):
        for j in range(n):
            for k in range(j+1, n):
                if heights[i][j] >= heights[i][k]:
                    if heights[i][j] > heights[i][k]:
                        answer[i][j] += 1
                else:
                    break
            for k in range(i+1, m):
                if heights[i][j] >= heights[k][j]:
                    if heights[i][j] > heights[k][j]:
                        answer[i][j] += 1
                else:
                    break

    return answer
```


```java
public int minOperations(int[] nums) {
    int n = nums.length;
    int even = 0, odd = 0;

    for (int i = 0; i < n; ++i) {
        if (i % 2 == 0 && nums[i] % 2 != 0) {
            even++;
        } else if (i % 2 != 0 && nums[i] % 2 == 0) {
            odd++;
        }
    }

    return Math.min(even, odd);
}
```

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

int minOperations(std::vector<int> &nums) {
    int n = nums.size();
    int even = 0, odd = 0;

    for (int i = 0; i < n; ++i) {
        if (i % 2 == 0 && nums[i] % 2 != 0) {
            even++;
        } else if (i % 2 != 0 && nums[i] % 2 == 0) {
            odd++;
        }
    }

    return std::min(even, odd);
}
```


```java
import java.util.Arrays;

public int minimumTimeForTrips(int[] time, int totalTrips) {
    Arrays.sort(time);

    int start = 0, end = time[time.length - 1] * totalTrips;
    while (start < end) {
        int mid = start + (end - start) / 2;
        int trips = 0;
        for (int t : time) {
            trips += mid / t;
        }
        if (trips < totalTrips) {
            start = mid + 1;
        } else {
            end = mid;
        }
    }

    return start;
}
```

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

int minimumTimeForTrips(std::vector<int>& time, int totalTrips) {
    std::sort(time.begin(), time.end());

    int start = 0, end = time.back() * totalTrips;
    while (start < end) {
        int mid = start + (end - start) / 2;
        int trips = 0;
        for (int t : time) {
            trips += mid / t;
        }
        if (trips < totalTrips) {
            start = mid + 1;
        } else {
            end = mid;
        }
    }

    return start;
}
```


```cpp
#include <vector>

int minHeightJump(const std::vector<int>& nums, const std::vector<int>& costs) {
    int n = nums.size();
    std::vector<int> dp(n, 1e9);

    dp[0] = 0;
    for (int i = 1; i < n; ++i) {
        int j = i - 1;
        while (j >= 0) {
            if ((nums[j] <= nums[i] && (j == 0 || nums[j - 1] < nums[i])) || (nums[j] > nums[i] && (j == 0 || nums[j - 1] >= nums[i]))) {
                dp[i] = std::min(dp[i], dp[j] + costs[i]);
            }
            --j;
        }
    }
    return dp[n - 1];
}
```

```python
def minHeightJump(nums, costs):
    n = len(nums)
    dp = [float('inf')] * n

    dp[0] = 0
    for i in range(1, n):
        for j in range(i - 1, -1, -1):
            if ((nums[j] <= nums[i] and (j == 0 or nums[j - 1] < nums[i])) or (nums[j] > nums[i] and (j == 0 or nums[j - 1] >= nums[i]))):
                dp[i] = min(dp[i], dp[j] + costs[i])

    return dp[n - 1]
```


```java
public int countSubarrays(int[] nums, long k) {
    int n = nums.length;
    int left = 0, right = 0;
    long sum = 0, count = 0;

    while (right < n) {
        sum += nums[right];
        while (sum * (right - left + 1) >= k) {
            sum -= nums[left];
            left++;
        }
        count += right - left + 1;
        right++;
    }

    return (int)count;
}
```

```python
def countSubarrays(nums: List[int], k: int) -> int:
    n = len(nums)
    left, right = 0, 0
    sum_, count = 0, 0

    while right < n:
        sum_ += nums[right]
        while sum_ * (right - left + 1) >= k:
            sum_ -= nums[left]
            left += 1
        count += right - left + 1
        right += 1

    return count
```


```java
double taxAmount(int[][] brackets, int income) {
    double tax = 0;
    int prev_upper = 0;
    for (int[] bracket : brackets) {
        int upper = bracket[0];
        double percent = bracket[1] / 100.0;
        tax += (Math.min(upper, income) - prev_upper) * percent;
        prev_upper = upper;
        if (income <= upper) break;
    }
    return tax;
}
```

```python
def tax_amount(brackets, income):
    tax = 0
    prev_upper = 0
    for upper, percent in brackets:
        tax += (min(upper, income) - prev_upper) * (percent / 100)
        prev_upper = upper
        if income <= upper:
            break
    return tax
```


```python
def max_count_target(nums, key):
    count = {}
    max_count = 0
    max_target = -1
    for i in range(1, len(nums)):
        if nums[i - 1] == key:
            count[nums[i]] = count.get(nums[i], 0) + 1
            if count[nums[i]] > max_count:
                max_count = count[nums[i]]
                max_target = nums[i]
    return max_target
```

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

int maxCountTarget(const std::vector<int>& nums, int key) {
    std::unordered_map<int, int> count;
    int max_count = 0;
    int max_target = -1;
    for (size_t i = 1; i < nums.size(); ++i) {
        if (nums[i - 1] == key) {
            count[nums[i]]++;
            if (count[nums[i]] > max_count) {
                max_count = count[nums[i]];
                max_target = nums[i];
            }
        }
    }
    return max_target;
}
```


```cpp
int countStarsExceptBetweenPair(const std::string& s) {
    int count = 0;
    int pipeCount = 0;

    for (char c : s) {
        if (c == '|') {
            pipeCount++;
        } else if (c == '*' && pipeCount % 2 == 0) {
            count++;
        }
    }

    return count;
}
```

```python
def count_stars_except_between_pair(s: str) -> int:
    count = 0
    pipe_count = 0

    for c in s:
        if c == '|':
            pipe_count += 1
        elif c == '*' and pipe_count % 2 == 0:
            count += 1

    return count
```


```java
int countCollisions(String directions) {
    int collisionCount = 0, leftCount = 0;

    for (char direction : directions.toCharArray()) {
        if (direction == 'L') {
            leftCount++;
        } else if (direction == 'R') {
            collisionCount += leftCount;
        }
    }

    return collisionCount;
}
```

```python
def count_collisions(directions: str) -> int:
    collision_count = 0
    left_count = 0

    for direction in directions:
        if direction == 'L':
            left_count += 1
        elif direction == 'R':
            collision_count += left_count

    return collision_count
```


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

int dfs(int node, int parent, vector<int>& xor_values, vector<vector<int>>& tree) {
    int xor_value = xor_values[node];
    for (int child : tree[node]) {
        if (child != parent) {
            xor_value ^= dfs(child, node, xor_values, tree);
        }
    }
    return xor_value;
}

int minimumScore(vector<int>& nums, vector<vector<int>>& edges) {
    int n = nums.size();
    vector<vector<int>> tree(n);

    for (vector<int>& edge : edges) {
        tree[edge[0]].push_back(edge[1]);
        tree[edge[1]].push_back(edge[0]);
    }

    vector<int> xor_values(n);
    for (int i = 0; i < n; ++i) {
        xor_values[i] = dfs(i, -1, nums, tree);
    }

    int ans = INT_MAX;
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            int xor1 = xor_values[i];
            int xor2 = xor_values[j] ^ nums[i];
            int xor3 = nums[i] ^ nums[j];
            int max_xor = max({xor1, xor2, xor3});
            int min_xor = min({xor1, xor2, xor3});
            ans = min(ans, max_xor - min_xor);
        }
    }

    return ans;
}
```

```python
def dfs(node, parent, xor_values, tree):
    xor_value = xor_values[node]
    for child in tree[node]:
        if child != parent:
            xor_value ^= dfs(child, node, xor_values, tree)
    return xor_value

def minimumScore(nums, edges):
    n = len(nums)
    tree = [[] for _ in range(n)]

    for edge in edges:
        tree[edge[0]].append(edge[1])
        tree[edge[1]].append(edge[0])

    xor_values = [dfs(i, -1, nums, tree) for i in range(n)]

    ans = float('inf')
    for i in range(n):
        for j in range(i + 1, n):
            xor1 = xor_values[i]
            xor2 = xor_values[j] ^ nums[i]
            xor3 = nums[i] ^ nums[j]
            max_xor = max(xor1, xor2, xor3)
            min_xor = min(xor1, xor2, xor3)
            ans = min(ans, max_xor - min_xor)

    return ans
```


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

std::string largestSwap(std::string num) {
    std::string even_digits = "";
    std::string odd_digits = "";

    for (char c : num) {
        if ((c - '0') % 2 == 0) {
            even_digits.push_back(c);
        } else {
            odd_digits.push_back(c);
        }
    }

    std::sort(even_digits.rbegin(), even_digits.rend());
    std::sort(odd_digits.rbegin(), odd_digits.rend());

    std::string result = "";
    size_t even_index = 0, odd_index = 0;

    for (char c : num) {
        if ((c - '0') % 2 == 0) {
            result.push_back(even_digits[even_index++]);
        } else {
            result.push_back(odd_digits[odd_index++]);
        }
    }

    return result;
}

int largestSwapPermutations(int num) {
    std::string num_str = std::to_string(num);
    return std::stoi(largestSwap(num_str));
}
```

```java
import java.util.Arrays;

public int largestSwapPermutations(int num) {
    String numStr = String.valueOf(num);
    char[] evenDigits = numStr.replaceAll("[13579]", "").toCharArray();
    char[] oddDigits = numStr.replaceAll("[02468]", "").toCharArray();

    Arrays.sort(evenDigits);
    Arrays.sort(oddDigits);

    StringBuilder result = new StringBuilder();

    for (char c : numStr.toCharArray()) {
        if (Character.getNumericValue(c) % 2 == 0) {
            result.insert(0, evenDigits[evenDigits.length - 1]);
            evenDigits = Arrays.copyOf(evenDigits, evenDigits.length - 1);
        } else {
            result.insert(0, oddDigits[oddDigits.length - 1]);
            oddDigits = Arrays.copyOf(oddDigits, oddDigits.length - 1);
        }
    }

    return Integer.parseInt(result.toString());
}
```


```java
public String addParentheses(String expression) {
    return "(" + expression + ")";
}
```

```python
def add_parentheses(expression: str) -> str:
    return f"({expression})"
```


```python
def evalTree(root: 'TreeNode') -> bool:
    if not root.left and not root.right:
        return root.val == 1
    left = evalTree(root.left)
    right = evalTree(root.right)

    if root.val == 2:
        return left or right
    return left and right
```

true false true true true false false true false true false true false true true false true false false true true true true false true true false true false false false true true true true true false true true false false true false true

```cpp
bool evalTree(TreeNode* root) {
    if (!root->left && !root->right)
        return root->val;
    bool left = evalTree(root->left);
    bool right = evalTree(root->right);

    if (root->val == 2)
        return left || right;
    return left && right;
}
```


```java
import java.util.Arrays;

public int lastPassengerTime(int[] buses, int[] passengers, int capacity) {
    Arrays.sort(buses);
    Arrays.sort(passengers);

    int lastIndex = 0;
    for (int bus : buses) {
        int cnt = 0;
        while (lastIndex < passengers.length && passengers[lastIndex] <= bus && cnt < capacity) {
            cnt++;
            lastIndex++;
        }
    }

    return lastIndex == 0 ? buses[0] - 1 : passengers[lastIndex - 1] - 1;
}
```

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

int lastPassengerTime(vector<int> &buses, vector<int> &passengers, int capacity) {
    sort(buses.begin(), buses.end());
    sort(passengers.begin(), passengers.end());

    int lastIndex = 0;
    for (int bus : buses) {
        int cnt = 0;
        while (lastIndex < passengers.size() && passengers[lastIndex] <= bus && cnt < capacity) {
            cnt++;
            lastIndex++;
        }
    }

    return lastIndex == 0 ? buses[0] - 1 : passengers[lastIndex - 1] - 1;
}
```


```cpp
int minSumOfSquaredDifference(vector<int>& nums1, vector<int>& nums2, int k1, int k2) {
    int64_t res = 0;
    for (int i = 0; i < nums1.size(); ++i) {
        int diff = abs(nums1[i] - nums2[i]);
        int steps = min(k1 + k2, diff);
        diff -= steps;
        k1 -= min(k1, steps);
        res += 1LL * diff * diff;
    }
    return (int)res;
}
```

```python
def min_sum_of_squared_difference(nums1, nums2, k1, k2):
    res = 0
    for i in range(len(nums1)):
        diff = abs(nums1[i] - nums2[i])
        steps = min(k1 + k2, diff)
        diff -= steps
        k1 -= min(k1, steps)
        res += diff * diff
    return res
```


```cpp
int findSubarrayLength(vector<int>& nums, int threshold) {
    int n = nums.size();
    int left = 0, right = 0, sum = 0;
    int maxLength = -1;

    while (right < n) {
        sum += nums[right];
        while (sum * (right - left + 1) < threshold * (right - left + 1)) {
            sum -= nums[left];
            left++;
        }
        maxLength = max(maxLength, right - left + 1);
        right++;
    }

    return maxLength;
}
```

```python
def find_subarray_length(nums, threshold):
    n = len(nums)
    left = 0
    right = 0
    total = 0
    max_length = -1

    while right < n:
        total += nums[right]
        while total * (right - left + 1) < threshold * (right - left + 1):
            total -= nums[left]
            left += 1
        max_length = max(max_length, right - left + 1)
        right += 1

    return max_length
```


```java
public int minSeconds(int[] amount) {
    int total = amount[0] + amount[1] + amount[2];
    int largestTwo = Math.max(amount[0] + amount[1], Math.max(amount[1] + amount[2], amount[0] + amount[2]));
    return (total + 1) / 2 - (largestTwo + 1) / 2 + largestTwo;
}
```

```python
def min_seconds(amount: List[int]) -> int:
    total = sum(amount)
    largest_two = max(amount[0] + amount[1], amount[1] + amount[2], amount[0] + amount[2])
    return (total + 1) // 2 - (largest_two + 1) // 2 + largest_two
```


```cpp
int numOfArrays(int n, int maxValue) {
    const int mod = 1e9 + 7;
    vector<int> dp(maxValue + 1, 0);

    for (int i = 1; i <= maxValue; i++) {
        dp[i] = i;
    }

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

    return dp[maxValue];
}
```

```java
public int numOfArrays(int n, int maxValue) {
    final int mod = 1_000_000_007;
    int[] dp = new int[maxValue + 1];

    for (int i = 1; i <= maxValue; i++) {
        dp[i] = i;
    }

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

    return dp[maxValue];
}
```


```java
public int minSwaps(int[] nums) {
    int n = nums.length;
    int minPos = 0, maxPos = 0, swaps = 0;

    for (int i = 1; i < n; i++) {
        if (nums[i] <= nums[minPos])
            minPos = i;
        if (nums[i] >= nums[maxPos])
            maxPos = i;
    }

    swaps = minPos + (n - 1 - maxPos);
    if (minPos < maxPos) swaps--;

    return swaps;
}
```

```cpp
int minSwaps(vector<int>& nums) {
    int n = nums.size();
    int minPos = 0, maxPos = 0, swaps = 0;

    for (int i = 1; i < n; i++) {
        if (nums[i] <= nums[minPos])
            minPos = i;
        if (nums[i] >= nums[maxPos])
            maxPos = i;
    }

    swaps = minPos + (n - 1 - maxPos);
    if (minPos < maxPos) swaps--;

    return swaps;
}
```


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

vector<int> countPairsLeftovers(vector<int>& nums) {
    vector<int> counter(101, 0);
    int pairs = 0, leftovers = 0;

    for (int n : nums) {
        counter[n]++;
    }

    for (int count : counter) {
        pairs += count / 2;
        leftovers += count % 2;
    }

    return {pairs, leftovers};
}
```

```python
def count_pairs_leftovers(nums):
    counter = [0] * 101
    pairs, leftovers = 0, 0

    for n in nums:
        counter[n] += 1

    for count in counter:
        pairs += count // 2
        leftovers += count % 2

    return [pairs, leftovers]
```


```cpp
int maxSumNumbersWithEqualSumOfDigits(vector<int>& nums) {
    unordered_map<int, int> digit_sum_to_max;
    int ans = -1;

    for (int num : nums) {
        int sum_of_digits = 0;
        for (int temp = num; temp; temp /= 10) {
            sum_of_digits += temp % 10;
        }

        int prev_max = digit_sum_to_max[sum_of_digits];
        if (prev_max) {
            ans = max(ans, num + prev_max);
        }
        digit_sum_to_max[sum_of_digits] = max(num, prev_max);
    }

    return ans;
}
```

```python
def max_sum_numbers_with_equal_sum_of_digits(nums):
    digit_sum_to_max = {}
    ans = -1

    for num in nums:
        sum_of_digits = sum(map(int, str(num)))

        prev_max = digit_sum_to_max.get(sum_of_digits, 0)
        if prev_max:
            ans = max(ans, num + prev_max)

        digit_sum_to_max[sum_of_digits] = max(num, prev_max)

    return ans
```


```java
public int minDeletions(int[] nums, int[] numsDivide) {
    int res = Integer.MAX_VALUE;
    for (int num : nums) {
        int cnt = 0;
        boolean found = true;
        for (int d : numsDivide) {
            if (d % num != 0) {
                found = false;
                break;
            }
        }
        if (found) {
            for (int n : nums) {
                if (n == num) {
                    cnt++;
                }
            }
            res = Math.min(res, nums.length - cnt);
        }
    }
    return res == Integer.MAX_VALUE ? -1 : res;
}
```

```cpp
int minDeletions(vector<int>& nums, vector<int>& numsDivide) {
    int res = INT_MAX;
    for (int num : nums) {
        int cnt = 0;
        bool found = true;
        for (int d : numsDivide) {
            if (d % num != 0) {
                found = false;
                break;
            }
        }
        if (found) {
            for (int n : nums) {
                if (n == num) {
                    cnt++;
                }
            }
            res = min(res, (int)nums.size() - cnt);
        }
    }
    return res == INT_MAX ? -1 : res;
}
```


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

std::string bestPokerHand(std::vector<int> &ranks, std::vector<char> &suits) {
    std::map<int, int> rank_count;
    std::map<char, int> suit_count;
    for (int i = 0; i < ranks.size(); ++i) {
        rank_count[ranks[i]]++;
        suit_count[suits[i]]++;
    }
    if (suit_count.size() == 1) return "Flush ";
    if (rank_count.size() == 3) return "Three of a Kind ";
    for (const auto &pair : rank_count) {
        if (pair.second == 2) return "Pair ";
    }
    return "High Card ";
}
```

High Card
Pair
High Card
High Card
High Card
High Card
High Card
High Card
High Card
High Card
High Card
High Card
High Card
High Card
High Card
High Card
High Card
High Card
Flush
High Card
Flush
High Card
High Card
High Card
Pair
High Card
High Card
High Card
Pair
High Card
High Card
High Card
Pair
Flush
High Card
High Card
High Card
High Card
Three of a Kind

```python
def best_poker_hand(ranks, suits):
    rank_count = {}
    suit_count = {}
    for rank, suit in zip(ranks, suits):
        rank_count[rank] = rank_count.get(rank, 0) + 1
        suit_count[suit] = suit_count.get(suit, 0) + 1
    if len(suit_count) == 1:
        return "Flush "
    if len(rank_count) == 3:
        return "Three of a Kind "
    for value in rank_count.values():
        if value == 2:
            return "Pair "
    return "High Card "
```


```java
public int numberOfSubarraysWithZeroes(int[] nums) {
    int count = 0;
    int zeroCount = 0;

    for (int num : nums) {
        if (num == 0) {
            zeroCount++;
            count += zeroCount;
        } else {
            zeroCount = 0;
        }
    }
    return count;
}
```

```cpp
int numberOfSubarraysWithZeroes(vector<int>& nums) {
    int count = 0;
    int zeroCount = 0;

    for (int num : nums) {
        if (num == 0) {
            zeroCount++;
            count += zeroCount;
        } else {
            zeroCount = 0;
        }
    }
    return count;
}
```


```python
def shortest_unrollable_sequence(rolls, k):
    count = [0] * (k + 1)
    for roll in rolls:
        count[roll] += 1

    len_ = 1
    while True:
        max_subsequences = 1
        for i in range(1, k + 1):
            max_subsequences *= count[i] + (1 if len_ == 1 else 0)

        if max_subsequences < len_ * len(rolls):
            return len_

        len_ += 1
```

```cpp
int shortestUnrollableSequence(vector<int>& rolls, int k) {
    vector<int> count(k + 1);
    for (int roll : rolls) {
        count[roll]++;
    }

    int len = 1;
    while (true) {
        int max_subsequences = 1;
        for (int i = 1; i <= k; i++) {
            max_subsequences *= count[i] + (len == 1);
        }

        if (max_subsequences < len * rolls.size()) {
            return len;
        }

        len++;
    }
}
```


```java
public int countEqualRowColumnPairs(int[][] grid) {
    int n = grid.length;
    int ans = 0;

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            boolean equal = true;
            for (int k = 0; k < n; ++k) {
                if (grid[i][k] != grid[k][j]) {
                    equal = false;
                    break;
                }
            }
            if (equal) {
                ++ans;
            }
        }
    }

    return ans;
}
```

```python
def countEqualRowColumnPairs(grid: List[List[int]]) -> int:
   n = len(grid)
   ans = 0

   for i in range(n):
      for j in range(n):
         equal = True
         for k in range(n):
             if grid[i][k] != grid[k][j]:
                 equal = False
                 break
         if equal:
             ans += 1

   return ans
```


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

int countExcellentPairs(std::vector<int>& nums, int k) {
    std::unordered_map<int, int> frequency;
    for (int num : nums) {
        frequency[num]++;
    }

    int count = 0;
    for (auto it1 = frequency.begin(); it1 != frequency.end(); it1++) {
        for (auto it2 = frequency.begin(); it2 != frequency.end(); it2++) {
            if ((__builtin_popcount(it1->first | it2->first) + __builtin_popcount(it1->first & it2->first)) >= k) {
                count += (it1->first == it2->first) ? it1->second * (it1->second - 1) / 2 : it1->second * it2->second;
            }
        }
    }

    return count;
}
```

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

public int countExcellentPairs(int[] nums, int k) {
    HashMap<Integer, Integer> frequency = new HashMap<>();
    for (int num : nums) {
        frequency.put(num, frequency.getOrDefault(num, 0) + 1);
    }

    int count = 0;
    for (Map.Entry<Integer, Integer> entry1 : frequency.entrySet()) {
        for (Map.Entry<Integer, Integer> entry2 : frequency.entrySet()) {
            int num1 = entry1.getKey();
            int num2 = entry2.getKey();
            int setBits = Integer.bitCount(num1 | num2) + Integer.bitCount(num1 & num2);
            if (setBits >= k) {
                count += (num1 == num2) ? entry1.getValue() * (entry1.getValue() - 1) / 2 : entry1.getValue() * entry2.getValue();
            }
        }
    }

    return count;
}
```


```java
int maxBooks(int[] books) {
    int n = books.length;
    int max_books = 0;

    for (int l = 0; l < n; ++l) {
        int r = l + 1, books_taken = books[l], min_taken = books[l];
        max_books = Math.max(max_books, books_taken);

        while (r < n) {
            min_taken = Math.min(min_taken, books[r]);
            books_taken += min_taken;
            max_books = Math.max(max_books, books_taken);

            if (min_taken <= 1) break; // Can't decrease further
            ++r;
        }
    }

    return max_books;
}
```

```python
def max_books(books):
    n = len(books)
    max_books = 0

    for l in range(n):
        r = l + 1
        books_taken = books[l]
        min_taken = books[l]
        max_books = max(max_books, books_taken)

        while r < n:
            min_taken = min(min_taken, books[r])
            books_taken += min_taken
            max_books = max(max_books, books_taken)

            if min_taken <= 1:
                break  # Can't decrease further
            r += 1

    return max_books
```


```cpp
int minOperations(vector<int>& nums) {
    int count = 0;
    std::sort(nums.begin(), nums.end());

    for (int i = 0; i < nums.size(); ++i) {
        if (nums[i] > 0) {
            count += nums.end() - (std::upper_bound(nums.begin() + i, nums.end(), nums[i]));
            i = (std::upper_bound(nums.begin(), nums.end(), nums[i])) - nums.begin() - 1;
        }
    }

    return count;
}
```

```python
def minOperations(nums):
    count = 0
    nums.sort()
    i = 0

    while i < len(nums):
        if nums[i] > 0:
            target = nums[i]
            while i < len(nums) and nums[i] == target:
                i += 1
            count += 1
        else:
            i += 1

    return count
```


```cpp
int max_groups(vector<int>& grades) {
    int len = grades.size();
    vector<int> dp(len, 1);

    sort(grades.begin(), grades.end());

    for (int i = 0; i < len; ++i) {
        for (int j = 0; j < i; ++j) {
            if (grades[i] + dp[j] * grades[j] > (i+1) * grades[j]) {
                dp[i] = dp[j] + 1;
            }
        }
    }

    return dp[len-1];
}
```

```python
def max_groups(grades):
    grades.sort()

    dp = [1] * len(grades)

    for i in range(len(grades)):
        for j in range(i):
            if grades[i] + dp[j] * grades[j] > (i+1) * grades[j]:
                dp[i] = dp[j] + 1

    return dp[-1]
```


```java
public int findLongestCycle(int[] edges) {
    int n = edges.length;
    boolean[] visited = new boolean[n];
    int longest_cycle = -1;

    for (int i = 0; i < n; ++i) {
        if (!visited[i]) {
            int length = 0;
            int node = i;

            while (!visited[node] && edges[node] != -1) {
                visited[node] = true;
                length++;
                node = edges[node];
            }

            if (edges[node] == i) {
                longest_cycle = Math.max(longest_cycle, length);
            }
        }
    }

    return longest_cycle;
}
```

```python
def findLongestCycle(edges):
    n = len(edges)
    visited = [False] * n
    longest_cycle = -1

    for i in range(n):
        if not visited[i]:
            length = 0
            node = i

            while not visited[node] and edges[node] != -1:
                visited[node] = True
                length += 1
                node = edges[node]

            if edges[node] == i:
                longest_cycle = max(longest_cycle, length)

    return longest_cycle
```


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

vector<int> minStopCosts(vector<int>& regular, vector<int>& express, int expressCost) {
    int n = regular.size();
    vector<int> costs(n);
    int regular_sum = 0, express_sum = expressCost;

    for (int i = 0; i < n; ++i) {
        regular_sum += regular[i];
        express_sum += express[i];
        costs[i] = min(regular_sum, express_sum + expressCost);
    }

    return costs;
}
```

```python
def min_stop_costs(regular, express, express_cost):
    n = len(regular)
    costs = [0] * n
    regular_sum, express_sum = 0, express_cost

    for i in range(n):
        regular_sum += regular[i]
        express_sum += express[i]
        costs[i] = min(regular_sum, express_sum + express_cost)

    return costs
```


```java
import java.util.*;

class Main {
    public static List<List<Integer>> sumWeights(List<List<Integer>> items1, List<List<Integer>> items2) {
        Map<Integer, Integer> weightSums = new TreeMap<>();
        List<List<Integer>> result = new ArrayList<>();

        for (List<Integer> item : items1) {
            weightSums.put(item.get(0), weightSums.getOrDefault(item.get(0), 0) + item.get(1));
        }
        for (List<Integer> item : items2) {
            weightSums.put(item.get(0), weightSums.getOrDefault(item.get(0), 0) + item.get(1));
        }

        for (Map.Entry<Integer, Integer> entry : weightSums.entrySet()) {
            result.add(Arrays.asList(entry.getKey(), entry.getValue()));
        }

        return result;
    }
}
```

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

vector<vector<int>> sumWeights(vector<vector<int>>& items1, vector<vector<int>>& items2) {
    map<int, int> weightSums;
    vector<vector<int>> result;

    for (const auto& item : items1) {
        weightSums[item[0]] += item[1];
    }
    for (const auto& item : items2) {
        weightSums[item[0]] += item[1];
    }

    for (const auto& entry : weightSums) {
        result.push_back({entry.first, entry.second});
    }

    return result;
}
```


```java
public int minDaysToCompleteTasks(int[] tasks, int space) {
    HashMap<Integer, Integer> taskLastComplete = new HashMap<>();
    int days = 0;

    for (int task : tasks) {
        if (taskLastComplete.containsKey(task)) {
            int passedDays = days - taskLastComplete.get(task);
            if (passedDays < space) {
                days += space - passedDays;
            }
        }
        days++;
        taskLastComplete.put(task, days);
    }

    return days;
}
```

```cpp
int min_days_to_complete_tasks(vector<int>& tasks, int space) {
    unordered_map<int, int> task_last_complete;
    int days = 0;

    for (int task : tasks) {
        if (task_last_complete.find(task) != task_last_complete.end()) {
            int passed_days = days - task_last_complete[task];
            if (passed_days < space) {
                days += space - passed_days;
            }
        }
        task_last_complete[task] = ++days;
    }

    return days;
}
```


```java
public int minOperations(int[] nums) {
    int operations = 0;
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] <= nums[i - 1]) {
            int diff = nums[i - 1] - nums[i] + 1;
            operations += Math.ceil(Math.log(diff) / Math.log(2));
            nums[i] += diff;
        }
    }
    return operations;
}
```

```cpp
int minOperations(vector<int>& nums) {
    int operations = 0;
    for (int i = 1; i < nums.size(); i++) {
        if (nums[i] <= nums[i - 1]) {
            int diff = nums[i - 1] - nums[i] + 1;
            operations += ceil(log2(diff));
            nums[i] += diff;
        }
    }
    return operations;
}
```


```java
public int countArithmeticTriplets(int[] nums, int diff) {
    int count = 0;
    HashMap<Integer, Integer> mp = new HashMap<>();
    for (int num : nums) {
        if (mp.containsKey(num - diff))
            count += mp.get(num - diff);
        mp.put(num, mp.getOrDefault(num, 0) + 1);
    }
    return count;
}
```

```cpp
int countArithmeticTriplets(vector<int> &nums, int diff) {
    int count = 0;
    unordered_map<int, int> mp;
    for (int num : nums) {
        if (mp.count(num - diff))
            count += mp[num - diff];
        mp[num]++;
    }
    return count;
}
```


```python
from collections import defaultdict

def max_nodes_without_restricted(n, edges, restricted):
    tree = defaultdict(list)
    blocked_nodes = set(restricted)

    for a, b in edges:
        tree[a].append(b)
        tree[b].append(a)

    max_nodes = [0]

    def dfs(node, depth, parent):
        if node in blocked_nodes:
            return
        max_nodes[0] = max(max_nodes[0], depth)
        for child in tree[node]:
            if child != parent:
                dfs(child, depth + 1, node)

    dfs(0, 1, -1)
    return max_nodes[0]
```

```java
import java.util.*;

public int maxNodesWithoutRestricted(int n, int[][] edges, int[] restricted) {
    Map<Integer, List<Integer>> tree = new HashMap<>();
    Set<Integer> blockedNodes = new HashSet<>();
    for (int r : restricted) blockedNodes.add(r);

    for (int[] edge : edges) {
        tree.putIfAbsent(edge[0], new ArrayList<>());
        tree.putIfAbsent(edge[1], new ArrayList<>());
        tree.get(edge[0]).add(edge[1]);
        tree.get(edge[1]).add(edge[0]);
    }

    int[] maxNodes = new int[1];

    dfs(0, 1, -1, tree, blockedNodes, maxNodes);
    return maxNodes[0];
}

private void dfs(int node, int depth, int parent, Map<Integer, List<Integer>> tree, Set<Integer> blockedNodes, int[] maxNodes) {
    if (blockedNodes.contains(node)) return;
    maxNodes[0] = Math.max(maxNodes[0], depth);
    for (int child : tree.get(node)) {
        if (child != parent) dfs(child, depth + 1, node, tree, blockedNodes, maxNodes);
    }
}
```


```java
import java.util.HashMap;

public static boolean valid_partition(int[] nums) {
    HashMap<Integer, Integer> count = new HashMap<>();
    for (int num : nums) {
        count.put(num, count.getOrDefault(num, 0) + 1);
    }
    for (int num : count.keySet()) {
        int cnt = count.get(num);
        if (cnt == 2 || cnt == 3 || (count.containsKey(num - 1) && count.containsKey(num + 1))) {
            return true;
        }
    }
    return false;
}
```

False True False False True False False False False False False False False False False False False True False True False True False False False False True False False False True False False False False True False False False False True

```python
def valid_partition(nums):
    count = {}
    for num in nums:
        count[num] = count.get(num, 0) + 1
    for num, cnt in count.items():
        if cnt == 2 or cnt == 3 or (num - 1 in count and num + 1 in count):
            return True
    return False
```