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

bool isValidIPv4(const std::string& part);
bool isValidIPv6(const std::string& part);

std::string validateIP(const std::string& queryIP) {
    std::stringstream ss(queryIP);
    std::string part;
    int partsCount = 0;

    if (queryIP.find(':') == std::string::npos) {
        while (getline(ss, part, '.')) {
            if (!isValidIPv4(part)) return "Neither";
            partsCount++;
        }
        if (partsCount == 4) return "IPv4";
    } else {
        while (getline(ss, part, ':')) {
            if (!isValidIPv6(part)) return "Neither";
            partsCount++;
        }
        if (partsCount == 8) return "IPv6";
    }

    return "Neither";
}

bool isValidIPv4(const std::string& part) {
    if (part.empty() || part.size() > 3) return false;
    if (part.size() > 1 && part[0] == '0') return false;

    int num = 0;
    for (char ch : part) {
        if (!isdigit(ch)) return false;
        num = num * 10 + (ch - '0');
    }

    return num >= 0 && num <= 255;
}

bool isValidIPv6(const std::string& part) {
    if (part.empty() || part.size() > 4) return false;

    for (char ch : part) {
        if (!isxdigit(ch)) return false;
    }

    return true;
}
```

Neither IPv4 Neither IPv4 Neither IPv4 IPv4 Neither IPv4 Neither Neither Neither Neither Neither Neither Neither

```java
public String validateIP(String queryIP) {
    String[] ipv4Parts = queryIP.split("\\.", -1);
    String[] ipv6Parts = queryIP.split(":", -1);

    if (ipv4Parts.length == 4) {
        if (isValidIPv4(ipv4Parts)) return "IPv4";
    } else if (ipv6Parts.length == 8) {
        if (isValidIPv6(ipv6Parts)) return "IPv6";
    }

    return "Neither";
}

private boolean isValidIPv4(String[] parts) {
    for (String part : parts) {
        if (part.length() == 0 || part.length() > 3 || (part.length() > 1 && part.charAt(0) == '0')) return false;

        int num = 0;
        for (char ch : part.toCharArray()) {
            if (!Character.isDigit(ch)) return false;
            num = num * 10 + (ch - '0');
        }

        if (num < 0 || num > 255) return false;
    }

    return true;
}

private boolean isValidIPv6(String[] parts) {
    for (String part : parts) {
        if (part.length() == 0 || part.length() > 4) return false;

        for (char ch : part.toCharArray()) {
            if (!Character.isDigit(ch) && !(ch >= 'a' && ch <= 'f') && !(ch >= 'A' && ch <= 'F')) return false;
        }
    }

    return true;
}
```


```java
public boolean isConvex(int[][] points) {
    int n = points.length;
    int pre = 0, cur = 0;

    for (int i = 0; i < n; ++i) {
        int x1 = points[(i + 1) % n][0] - points[i][0];
        int y1 = points[(i + 1) % n][1] - points[i][1];
        int x2 = points[(i + 2) % n][0] - points[(i + 1) % n][0];
        int y2 = points[(i + 2) % n][1] - points[(i + 1) % n][1];
        cur = x1 * y2 - x2 * y1;

        if (cur == 0)
            continue;
        if (cur * pre < 0)
            return false;
        pre = cur;
    }

    return true;
}
```

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

```python
def isConvex(points):
    n = len(points)
    pre = cur = 0

    for i in range(n):
        x1 = points[(i + 1) % n][0] - points[i][0]
        y1 = points[(i + 1) % n][1] - points[i][1]
        x2 = points[(i + 2) % n][0] - points[(i + 1) % n][0]
        y2 = points[(i + 2) % n][1] - points[(i + 1) % n][1]
        cur = x1 * y2 - x2 * y1

        if cur == 0:
            continue
        if cur * pre < 0:
            return False
        pre = cur

    return True
```


```cpp
std::string encode(std::string s) {
    int n = s.length();
    for (int i = n / 2; i > 0; i--) {
        if (n % i == 0) {
            int reps = n / i;
            std::string sub = s.substr(0, i);
            std::string composed = "";
            for (int j = 0; j < reps; j++) {
                composed += sub;
            }
            if (s == composed) {
                return std::to_string(reps) + "[" + sub + "]";
            }
        }
    }
    return s;
}
```

```python
def encode(s: str) -> str:
    n = len(s)
    for i in range(n // 2, 0, -1):
        if n % i == 0:
            reps = n // i
            sub = s[:i]
            composed = sub * reps
            if s == composed:
                return f"{reps}[{sub}]"
    return s
```


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

public class Solution {
    public boolean isConcatenated(String word, Set<String> wordDict) {
        int n = word.length();
        boolean[] dp = new boolean[n + 1];
        dp[0] = true;

        for (int i = 1; i <= n; ++i) {
            for (int j = 0; j < i; ++j) {
                if (dp[j] && wordDict.contains(word.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[n];
    }

    public List<String> findAllConcatenatedWords(String[] words) {
        Set<String> wordDict = new HashSet<>();
        for (String word : words) {
            wordDict.add(word);
        }

        List<String> result = new ArrayList<>();
        for (String word : words) {
            if (isConcatenated(word, wordDict)) {
                result.add(word);
            }
        }

        return result;
    }
}
```

words = \[ "cat ", "cats ", "catsdogcats ", "dog ", "dogcatsdog ", "hippopotamuses ", "rat ", "ratcatdogcat "\]

\[ "catsdogcats ", "dogcatsdog ", "ratcatdogcat "\]

cat cats catsdogcats dog dogcatsdog hippopotamuses rat ratcatdogcat cat dog cat dog cat dog catsdogcats

cat cats catsdogcats dog dogcatsdog hippopotamuses rat ratcatdogcat dog

cat cats catsdogcats dog dogcatsdog hippopotamuses rat ratcatdogcat cat dog catsdogcats

cat cats catsdogcats dog dogcatsdog hippopotamuses rat ratcatdogcat cat dog cat dog cat dog dog

cat cats catsdogcats dog dogcatsdog hippopotamuses rat ratcatdogcat cat dog cat dog dog

cat cats catsdogcats dog dogcatsdog hippopotamuses rat ratcatdogcat cat dog cat dog catsdogcats

cat cats catsdogcats dog dogcatsdog hippopotamuses rat ratcatdogcat catsdogcats

cat cats catsdogcats dog dogcatsdog hippopotamuses rat ratcatdogcat cat dog dog

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'cat ', 'dog ', 'cat ', 'dog ', 'dog ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'cat ', 'dog ', 'dog ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'cat ', 'dog ', 'cat ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'cat ', 'dog ', 'cat ', 'dog ', 'cat ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'cat ', 'dog ', 'cat ', 'dog ', 'cat ', 'dog ', 'dog ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'cat ', 'dog ', 'cat ', 'dog ', 'catsdogcats ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'cat ', 'dog ', 'cat ', 'dog ', 'cat ', 'dog ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'catsdogcats ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'cat ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'cat ', 'dog ', 'cat ', 'dog ', 'cat ', 'dog ', 'catsdogcats ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'cat ', 'dog ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'cat ', 'dog ', 'catsdogcats ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'cat ', 'dog ', 'cat ', 'dog ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'dog ']

['cat ', 'cats ', 'catsdogcats ', 'dog ', 'dogcatsdog ', 'hippopotamuses ', 'rat ', 'ratcatdogcat ', 'cat ', 'dog ', 'cat ', 'dog ', 'cat ', 'dog ', 'cat ']

```python
def is_concatenated(word, word_dict):
    n = len(word)
    dp = [False] * (n + 1)
    dp[0] = True

    for i in range(1, n + 1):
        for j in range(i):
            if dp[j] and word[j:i] in word_dict:
                dp[i] = True
                break

    return dp[n]

def find_all_concatenated_words(words):
    word_dict = set(words)
    result = []

    for word in words:
        if is_concatenated(word, word_dict):
            result.append(word)

    return result
```


```java
import java.util.Arrays;

public class Solution {
    public boolean makesquare(int[] matchsticks) {
        if (matchsticks == null || matchsticks.length < 4) return false;
        int sum = 0;
        for (int matchstick : matchsticks) sum += matchstick;
        if (sum % 4 != 0) return false;
        int target = sum / 4;
        Arrays.sort(matchsticks);
        reverse(matchsticks);
        int[] sums = new int[4];
        return dfs(matchsticks, sums, target, 0);
    }

    private void reverse(int[] nums) {
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left++;
            right--;
        }
    }

    private boolean dfs(int[] matchsticks, int[] sums, int target, int index) {
        if (index == matchsticks.length) {
            return sums[0] == target && sums[1] == target && sums[2] == target;
        }
        for (int i = 0; i < 4; i++) {
            if (sums[i] + matchsticks[index] <= target) {
                sums[i] += matchsticks[index];
                if (dfs(matchsticks, sums, target, index + 1)) return true;
                sums[i] -= matchsticks[index];
            }
        }
        return false;
    }
}
```

false true false false false false 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 true false false false 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 true false false false false false false false false false false false

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

bool makesquare(std::vector<int>& matchsticks) {
    if (matchsticks.size() < 4) return false;
    int sum = std::accumulate(matchsticks.begin(), matchsticks.end(), 0);
    if (sum % 4) return false;
    int target = sum / 4;
    std::sort(matchsticks.rbegin(), matchsticks.rend());
    std::vector<int> sums(4, 0);
    return dfs(matchsticks, sums, target, 0);
}

bool dfs(std::vector<int>& matchsticks, std::vector<int>& sums, int target, int index) {
    if (index == matchsticks.size()) {
        return sums[0] == target && sums[1] == target && sums[2] == target;
    }
    for (int i = 0; i < 4; ++i) {
        if (sums[i] + matchsticks[index] <= target) {
            sums[i] += matchsticks[index];
            if (dfs(matchsticks, sums, target, index + 1)) return true;
            sums[i] -= matchsticks[index];
        }
    }
    return false;
}
```


```java
import java.util.Arrays;

public int findMaxForm(String[] strs, int m, int n) {
    int[][] dp = new int[m + 1][n + 1];

    for (String str: strs) {
        int ones = (int) str.chars().filter(ch -> ch == '1').count();
        int zeros = str.length() - ones;

        for (int i = m; i >= zeros; --i) {
            for (int j = n; j >= ones; --j) {
                dp[i][j] = Math.max(dp[i][j], dp[i - zeros][j - ones] + 1);
            }
        }
    }
    return dp[m][n];
}
```

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

int findMaxForm(std::vector<std::string>& strs, int m, int n) {
    std::vector<std::vector<int>> dp(m + 1, std::vector<int>(n + 1));

    for (const std::string& str: strs) {
        int ones = std::count(str.begin(), str.end(), '1');
        int zeros = str.length() - ones;

        for (int i = m; i >= zeros; --i) {
            for (int j = n; j >= ones; --j) {
                dp[i][j] = std::max(dp[i][j], dp[i - zeros][j - ones] + 1);
            }
        }
    }
    return dp[m][n];
}
```


```python
def findRadius(houses, heaters):
    houses.sort()
    heaters.sort()
    result, i = 0, 0

    for house in houses:
        while i < len(heaters) - 1 and abs(heaters[i + 1] - house) <= abs(heaters[i] - house):
            i += 1
        result = max(result, abs(heaters[i] - house))

    return result
```

```java
public int findRadius(int[] houses, int[] heaters) {
    Arrays.sort(houses);
    Arrays.sort(heaters);
    int result = 0;
    int i = 0;

    for (int house : houses) {
        while (i < heaters.length - 1 &&
               Math.abs(heaters[i + 1] - house) <= Math.abs(heaters[i] - house)) {
            i++;
        }
        result = Math.max(result, Math.abs(heaters[i] - house));
    }
    return result;
}
```


```python
def find_complement(num: int) -> int:
    bit_length = 0
    mask = num
    while mask > 0:
        mask >>= 1
        bit_length += 1
    all_ones = (1 << bit_length) - 1

    return num ^ all_ones
```

```java
public int findComplement(int num) {
    int bitLength = 0;
    int mask = num;
    while (mask > 0) {
        mask >>= 1;
        bitLength++;
    }
    int allOnes = (1 << bitLength) - 1;

    return num ^ allOnes;
}
```


```java
import java.util.TreeMap;

public double[] medianSlidingWindow(int[] nums, int k) {
    TreeMap<Integer, Integer> window = new TreeMap<>();
    int n = nums.length;
    double[] result = new double[n - k + 1];

    for (int i = 0; i < k; i++) {
        window.put(nums[i], window.getOrDefault(nums[i], 0) + 1);
    }

    for (int i = k; i <= n; i++) {
        int cnt = 0, mid1 = 0, mid2 = 0;
        for (Integer num : window.keySet()) {
            cnt += window.get(num);
            if (cnt >= (k + 1) / 2 && mid1 == 0) {
                mid1 = num;
            }
            if (cnt >= (k + 2) / 2) {
                mid2 = num;
                break;
            }
        }

        result[i - k] = ((double) mid1 + mid2) / 2;

        if (i < n) {
            window.put(nums[i], window.getOrDefault(nums[i], 0) + 1);
            window.put(nums[i - k], window.get(nums[i - k]) - 1);
            if (window.get(nums[i - k]) == 0) {
                window.remove(nums[i - k]);
            }
        }
    }

    return result;
}
```

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

std::vector<double> medianSlidingWindow(std::vector<int>& nums, int k) {
    std::multiset<int> window(nums.begin(), nums.begin() + k);
    auto mid = std::next(window.begin(), k / 2);
    std::vector<double> medians;

    for (int i = k;; i++) {
        medians.push_back((double(*mid) + *std::prev(mid, 1 - k % 2)) / 2);

        if (i == nums.size()) {
            return medians;
        }
        window.insert(nums[i]);
        if (nums[i] < *mid) {
            mid--;
        }
        if (nums[i - k] <= *mid) {
            mid++;
        }
        window.erase(window.lower_bound(nums[i - k]));
    }
}
```


```cpp
#include <cctype>
#include <string>
using namespace std;

string licenseKeyFormatting(string s, int k) {
    string result = "";
    int count = 0;
    for (int i = s.size() - 1; i >= 0; i--) {
        if (s[i] != '-') {
            if (count == k) {
                result.push_back('-');
                count = 0;
            }
            result.push_back(toupper(s[i]));
            count++;
        }
    }
    reverse(result.begin(), result.end());
    return result;
}
```

```java
public String licenseKeyFormatting(String s, int k) {
    StringBuilder result = new StringBuilder();
    int count = 0;
    for (int i = s.length() - 1; i >= 0; i--) {
        if (s.charAt(i) != '-') {
            if (count == k) {
                result.append('-');
                count = 0;
            }
            result.append(Character.toUpperCase(s.charAt(i)));
            count++;
        }
    }
    return result.reverse().toString();
}
```


```python
def findMaxConsecutiveOnes(nums):
    max_consecutive, current_consecutive = 0, 0
    for num in nums:
        current_consecutive = current_consecutive + 1 if num == 1 else 0
        max_consecutive = max(max_consecutive, current_consecutive)
    return max_consecutive
```

```java
public int findMaxConsecutiveOnes(int[] nums) {
    int maxConsecutive = 0, currentConsecutive = 0;
    for (int num : nums) {
        currentConsecutive = (num == 1) ? currentConsecutive + 1 : 0;
        maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
    }
    return maxConsecutive;
}
```


```java
public int findMaxConsecutiveOnes(int[] nums) {
    int maxCount = 0, countZeros = 0, left = 0;
    for (int right = 0; right < nums.length; ++right) {
        if (nums[right] == 0) countZeros++;
        while (countZeros > 1) {
            if (nums[left++] == 0) countZeros--;
        }
        maxCount = Math.max(maxCount, right - left + 1);
    }
    return maxCount;
}
```

```cpp
int findMaxConsecutiveOnes(vector<int>& nums) {
    int max_count = 0, count_zeros = 0, left = 0;
    for (int right = 0; right < nums.size(); ++right) {
        if (nums[right] == 0) count_zeros++;
        while (count_zeros > 1) {
            if (nums[left++] == 0) count_zeros--;
        }
        max_count = max(max_count, right - left + 1);
    }
    return max_count;
}
```


```python
from collections import Counter

def find_min_step(board: str, hand: str) -> int:
    def find_min_step_helper(board, memo, hand):
        if not board:
            return 0
        if board in memo:
            return memo[board]

        result = float('inf')
        i = 0
        while i < len(board):
            j = i
            while j < len(board) and board[i] == board[j]:
                j += 1

            color = board[i]
            required = 3 - (j - i)
            if hand[color] >= required:
                hand[color] -= required
                next_board = board[:i] + board[j:]
                tmp = find_min_step_helper(next_board, memo, hand)
                if tmp != -1:
                    result = min(result, tmp + required)
                hand[color] += required
            i = j

        memo[board] = -1 if result == float('inf') else result
        return memo[board]

    hand_count = Counter(hand)
    memo = {}
    return find_min_step_helper(board, memo, hand_count)
```

```java
import java.util.*;

class Solution {
    public int findMinStep(String board, String hand) {
        HashMap<Character, Integer> handMap = new HashMap<>();
        for (char c : hand.toCharArray()) handMap.put(c, handMap.getOrDefault(c, 0) + 1);

        return findMinStepHelper(board, new HashMap<String, Integer>(), handMap);
    }

    private int findMinStepHelper(String board, HashMap<String, Integer> memo, HashMap<Character, Integer> hand) {
        if (board.isEmpty()) return 0;
        if (memo.containsKey(board)) return memo.get(board);

        int result = Integer.MAX_VALUE;
        for (int i = 0, j = 0; i < board.length(); i = j) {
            while (j < board.length() && board.charAt(i) == board.charAt(j)) ++j;
            char color = board.charAt(i);
            int required = 3 - (j - i);
            if (hand.getOrDefault(color, 0) >= required) {
                hand.put(color, hand.get(color) - required);
                String nextBoard = board.substring(0, i) + board.substring(j);
                int tmp = findMinStepHelper(nextBoard, memo, hand);
                if (tmp != -1) result = Math.min(result, tmp + required);
                hand.put(color, hand.get(color) + required);
            }
        }

        int res = (result == Integer.MAX_VALUE) ? -1 : result;
        memo.put(board, res);
        return res;
    }
}
```


```java
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
    int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    Queue<int[]> q = new LinkedList<>();
    q.add(start);
    while (!q.isEmpty()) {
        int[] curr = q.poll();
        int x = curr[0], y = curr[1];
        if (x == destination[0] && y == destination[1]) return true;
        for (int[] dir : dirs) {
            int i = x, j = y;
            while (i + dir[0] >= 0 && i + dir[0] < maze.length && j + dir[1] >= 0 && j + dir[1] < maze[0].length && maze[i + dir[0]][j + dir[1]] == 0) {
                i += dir[0];
                j += dir[1];
            }
            if (maze[i][j] == 0) {
                maze[i][j] = 1;
                q.add(new int[]{i, j});
            }
        }
    }
    return false;
}
```

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

```python
def hasPath(maze, start, destination):
    dirs = ((0, 1), (0, -1), (1, 0), (-1, 0))
    q = [start]
    while q:
        x, y = q.pop(0)
        if x == destination[0] and y == destination[1]:
            return True
        for dx, dy in dirs:
            i, j = x, y
            while 0 <= i + dx < len(maze) and 0 <= j + dy < len(maze[0]) and maze[i + dx][j + dy] == 0:
                i += dx
                j += dy
            if maze[i][j] == 0:
                maze[i][j] = 1
                q.append((i, j))
    return False
```


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

public List<List<Integer>> findSubsequences(int[] nums) {
    Set<List<Integer>> res = new HashSet<>();
    List<Integer> path = new ArrayList<>();
    dfs(nums, 0, path, res);
    return new ArrayList<>(res);
}

private void dfs(int[] nums, int start, List<Integer> path, Set<List<Integer>> res) {
    if (path.size() >= 2) {
        res.add(new ArrayList<>(path));
    }
    for (int i = start; i < nums.length; i++) {
        if (!path.isEmpty() && path.get(path.size() - 1) > nums[i]) {
            continue;
        }
        path.add(nums[i]);
        dfs(nums, i + 1, path, res);
        path.remove(path.size() - 1);
    }
}
```


```python
def constructRectangle(area: int) -> List[int]:
    width = int(area**0.5)
    while area % width != 0:
        width -= 1
    length = area // width
    return [length, width]
```

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

std::vector<int> constructRectangle(int area) {
    int width = std::sqrt(area);
    while(area % width != 0) {
        width -= 1;
    }
    int length = area / width;
    return {length, width};
}
```


```java
public int reversePairs(int[] nums) {
    return mergeSort(nums, 0, nums.length - 1, new int[nums.length]);
}

private int mergeSort(int[] nums, int left, int right, int[] temp) {
    if (left >= right) {
        return 0;
    }
    int mid = left + (right - left) / 2;
    int count = mergeSort(nums, left, mid, temp) + mergeSort(nums, mid + 1, right, temp);
    count += merge(nums, left, mid, right, temp);

    return count;
}

private int merge(int[] nums, int left, int mid, int right, int[] temp) {
    int count = 0;
    System.arraycopy(nums, left, temp, left, right - left + 1);
    int j = mid + 1;
    for (int i = left; i <= mid; i++) {
        while (j <= right && (long) nums[i] > 2L * nums[j]) {
            j++;
        }
        count += j - (mid + 1);
    }
    int i = left;
    j = mid + 1;
    int k = left;
    while (i <= mid && j <= right) {
        if (temp[i] <= temp[j]) {
            nums[k++] = temp[i++];
        } else {
            nums[k++] = temp[j++];
        }
    }
    while (i <= mid) {
        nums[k++] = temp[i++];
    }
    while (j <= right) {
        nums[k++] = temp[j++];
    }

    return count;
}
```

```cpp
#include <vector>

int merge(std::vector<int>& nums, std::vector<int>& temp, int left, int mid, int right) {
    int count = 0;
    int j = mid;
    for (int i = left; i < mid; i++) {
        while (j <= right && (long long)nums[i] > 2LL * nums[j]) {
            j++;
        }
        count += j - mid;
    }
    std::merge(nums.begin() + left, nums.begin() + mid, nums.begin() + mid, nums.begin() + right + 1, temp.begin() + left);

    return count;
}

int countReversePairs(std::vector<int>& nums, std::vector<int>& temp, int left, int right) {
    if (left >= right) {
        return 0;
    }
    int mid = left + (right - left) / 2;
    int count = countReversePairs(nums, temp, left, mid) + countReversePairs(nums, temp, mid + 1, right);
    count += merge(nums, temp, left, mid + 1, right);
    std::copy(temp.begin() + left, temp.begin() + right + 1, nums.begin() + left);

    return count;
}

int reversePairs(std::vector<int>& nums) {
    std::vector<int> temp(nums.size());
    return countReversePairs(nums, temp, 0, nums.size() - 1);
}
```


```python
def findTargetSumWays(nums, target):
    total_sum = sum(nums)
    if total_sum < target or (total_sum + target) % 2 != 0:
        return 0
    target_sum = (total_sum + target) // 2
    dp = [0] * (target_sum + 1)
    dp[0] = 1
    for num in nums:
        for j in range(target_sum, num - 1, -1):
            dp[j] += dp[j - num]
    return dp[target_sum]
```

```cpp
#include <vector>

int findTargetSumWays(std::vector<int>& nums, int target) {
    int sum = 0;
    for (int num : nums) sum += num;
    if (sum < target || (sum + target) % 2 != 0) return 0;
    int target_sum = (sum + target) / 2;
    std::vector<int> dp(target_sum + 1, 0);
    dp[0] = 1;
    for (int num : nums) {
        for (int j = target_sum; j >= num; j--) {
            dp[j] += dp[j - num];
        }
    }
    return dp[target_sum];
}
```


```python
def next_greater_element(nums1, nums2):
    next_greater = {}
    stack = []

    for num in nums2:
        while stack and stack[-1] < num:
            next_greater[stack.pop()] = num
        stack.append(num)

    return [next_greater.get(n, -1) for n in nums1]
```

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

std::vector<int> nextGreaterElement(std::vector<int>& nums1, std::vector<int>& nums2) {
    std::unordered_map<int, int> nextGreater;
    std::stack<int> stk;

    for (int num : nums2) {
        while (!stk.empty() && stk.top() < num) {
            nextGreater[stk.top()] = num;
            stk.pop();
        }
        stk.push(num);
    }

    std::vector<int> result(nums1.size());
    for (size_t i = 0; i < nums1.size(); ++i) {
        result[i] = nextGreater.count(nums1[i]) ? nextGreater[nums1[i]] : -1;
    }

    return result;
}
```


```java
import java.util.*;

class Solution {
    public String findShortestWay(int[][] maze, int[] ball, int[] hole) {
        int m = maze.length, n = maze[0].length;
        int[][] dist = new int[m][n];
        for (int i = 0; i < m; ++i) Arrays.fill(dist[i], Integer.MAX_VALUE);
        String[] dirs = {"d", "l", "r", "u"};
        int[][] dirs_vector = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}};
        dist[ball[0]][ball[1]] = 0;
        PriorityQueue<int[]> pq = new PriorityQueue<>((p1, p2) -> p1[0] != p2[0] ? p1[0] - p2[0] : p1[1] - p2[1]);
        pq.offer(new int[]{0, 0});

        while (!pq.isEmpty()) {
            int cur_dist = pq.peek()[0], cur_d = pq.peek()[1];
            String cur_path = pq.poll()[2];
            int x = ball[0], y = ball[1];
            for (char c : cur_path.toCharArray()) {
                if (c == 'd') x += dirs_vector[0][0];
                if (c == 'l') y += dirs_vector[1][1];
                if (c == 'r') y += dirs_vector[2][1];
                if (c == 'u') x += dirs_vector[3][0];
            }
            if (x == hole[0] && y == hole[1]) return cur_path;

            for (int k = 0; k < 4; ++k) {
                int dist_move = 0, r = x, c = y;
                while (r >= 0 && r < m && c >= 0 && c < n && maze[r][c] == 0 && (r != hole[0] || c != hole[1])) {
                    r += dirs_vector[k][0];
                    c += dirs_vector[k][1];
                    ++dist_move;
                }
                r -= dirs_vector[k][0];
                c -= dirs_vector[k][1];
                --dist_move;

                if (dist[x][y] + dist_move < dist[r][c]) {
                    dist[r][c] = dist[x][y] + dist_move;
                    pq.offer(new int[]{cur_dist + dist_move, cur_d * 4 + k, cur_path + dirs[k]});
                }
            }
        }

        return "impossible";
    }
}
```

"impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible" "impossible"

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

using namespace std;

class Solution {
public:
    string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {
        int m = maze.size(), n = maze[0].size();
        vector<vector<int>> dist(m, vector<int>(n, INT_MAX));
        vector<string> dirs = {"d", "l", "r", "u"};
        vector<vector<int>> dirs_vector = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}};
        string res = "";
        dist[ball[0]][ball[1]] = 0;
        auto cmp = [&](const auto& p1, const auto& p2){
            return p1.first > p2.first || (p1.first == p2.first && p1.second > p2.second);
        };
        priority_queue<pair<int, string>, vector<pair<int, string>>, decltype(cmp)> pq(cmp);
        pq.push({0, ""});

        while (!pq.empty()) {
            int cur_dist = pq.top().first;
            string cur_path = pq.top().second;
            int x = ball[0], y = ball[1];
            for (char c : cur_path) {
                if (c == 'd') x += dirs_vector[0][0];
                if (c == 'l') y += dirs_vector[1][1];
                if (c == 'r') y += dirs_vector[2][1];
                if (c == 'u') x += dirs_vector[3][0];
            }
            pq.pop();
            if (x == hole[0] && y == hole[1]) return cur_path;

            for (int k = 0; k < 4; ++k) {
                int dist_move = 0, r = x, c = y;
                while (r >= 0 && r < m && c >= 0 && c < n && maze[r][c] == 0 && (r != hole[0] || c != hole[1])) {
                    r += dirs_vector[k][0];
                    c += dirs_vector[k][1];
                    ++dist_move;
                }
                r -= dirs_vector[k][0];
                c -= dirs_vector[k][1];
                --dist_move;

                if (dist[x][y] + dist_move < dist[r][c]) {
                    dist[r][c] = dist[x][y] + dist_move;
                    pq.push({cur_dist + dist_move, cur_path + dirs[k]});
                }
            }
        }

        return "impossible";
    }
};
```


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

public class Solution {
    public String[] findWords(String[] words) {
        HashSet<Character>[] rows = new HashSet[] {
            new HashSet<Character>() {{
                add('q'); add('w'); add('e'); add('r'); add('t');
                add('y'); add('u'); add('i'); add('o'); add('p');
            }},
            new HashSet<Character>() {{
                add('a'); add('s'); add('d'); add('f'); add('g');
                add('h'); add('j'); add('k'); add('l');
            }},
            new HashSet<Character>() {{
                add('z'); add('x'); add('c'); add('v'); add('b');
                add('n'); add('m');
            }}
        };
        List<String> res = new ArrayList<>();

        for (String word : words) {
            int row = -1;
            for (int i = 0; i < 3; i++) {
                if (rows[i].contains(Character.toLowerCase(word.charAt(0)))) {
                    row = i;
                    break;
                }
            }

            boolean isOneRow = true;
            for (char letter : word.toCharArray()) {
                if (!rows[row].contains(Character.toLowerCase(letter))) {
                    isOneRow = false;
                    break;
                }
            }

            if (isOneRow)
                res.add(word);
        }

        return res.toArray(new String[0]);
    }
}
```

words = \[ "Hello ", "Alaska ", "Dad ", "Peace "\]

Qwertyuiop QwertyuiopQwertyuiop QwertyuiopQ Qwertyuiop1 QwertyuiopA QwertyuiopZ Qwertyuiop!

Hello Alaska Dad Peace Qwerty Yuiop ASDF ZXcvbnm

ZXCVBNM ZXCVBNMZXCVBNM ZXCVBNMQ ZXCVBNM1 ZXCVBNMA ZXCVBNMZ ZXCVBNM!

Qaz Wsxcde Edcrfv Rtgbn Tgvbnm Yhnujm Ujmik Ikolp

ASDFGHJKL ASDFGHJKLASDFGHJKL ASDFGHJKLQ ASDFGHJKL1 ASDFGHJKLA ASDFGHJKLZ ASDFGHJKL!

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

vector<string> findWords(vector<string>& words) {
    vector<unordered_set<char>> rows = {
        {'q','w','e','r','t','y','u','i','o','p'},
        {'a','s','d','f','g','h','j','k','l'},
        {'z','x','c','v','b','n','m'}
    };
    vector<string> result;

    for (const auto& word : words) {
        int row = -1;
        for (int i = 0; i < 3; ++i) {
            if (rows[i].count(tolower(word[0])) > 0) {
                row = i;
                break;
            }
        }

        bool isOneRow = true;
        for (const auto& letter : word) {
            if (rows[row].count(tolower(letter)) == 0) {
                isOneRow = false;
                break;
            }
        }

        if (isOneRow) {
            result.push_back(word);
        }
    }

    return result;
}
```


```python
def findMode(root):
    def InOrder(node):
        if not node: return
        yield from InOrder(node.left)
        yield node.val
        yield from InOrder(node.right)

    counts = collections.Counter(InOrder(root))
    max_count = max(counts.values(), default=0)
    return [k for k, v in counts.items() if v == max_count]
```

```java
public List<Integer> findMode(TreeNode root) {
    List<Integer> modes = new ArrayList<>();
    if (root == null) return modes;

    Map<Integer, Integer> frequencyMap = new HashMap<>();
    Stack<TreeNode> stack = new Stack<>();
    TreeNode currentNode = root;
    int maxFrequency = 0;

    while (currentNode != null || !stack.isEmpty()) {
        while (currentNode != null) {
            stack.add(currentNode);
            currentNode = currentNode.left;
        }
        currentNode = stack.pop();
        frequencyMap.put(currentNode.val, frequencyMap.getOrDefault(currentNode.val, 0) + 1);
        maxFrequency = Math.max(maxFrequency, frequencyMap.get(currentNode.val));
        currentNode = currentNode.right;
    }

    for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
        if (entry.getValue() == maxFrequency) modes.add(entry.getKey());
    }

    return modes;
}
```


```python
import heapq

def findMaximizedCapital(k: int, w: int, profits, capital) -> int:
    project_pool = list(zip(capital, profits))
    project_pool.sort(reverse=True)

    profit_pool = []

    while k:
        while project_pool and project_pool[-1][0] <= w:
            heapq.heappush(profit_pool, -project_pool.pop()[1])

        if not profit_pool:
            break

        w -= heapq.heappop(profit_pool)
        k -= 1

    return w
```

```java
import java.util.PriorityQueue;
import java.util.Arrays;

public class Solution {
    public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
        int[][] project_pool = new int[profits.length][2];

        for (int i = 0; i < profits.length; i++) {
            project_pool[i] = new int[] {capital[i], profits[i]};
        }

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

        PriorityQueue<Integer> profit_pool = new PriorityQueue<>((a, b) -> b - a);
        int index = 0;

        for (int i = 0; i < k; i++) {
            while (index < project_pool.length &&
                   project_pool[index][0] <= w) {
                profit_pool.add(project_pool[index++][1]);
            }

            if (!profit_pool.isEmpty()) {
                w += profit_pool.poll();
            } else {
                break;
            }
        }

        return w;
    }
}
```


```cpp
#include <vector>
#include <stack>

std::vector<int> nextGreaterElements(std::vector<int>& nums) {
    std::vector<int> result(nums.size(), -1);
    std::stack<int> s;

    for (int i = 0; i < nums.size() * 2; ++i) {
        int index = i % nums.size();
        while (!s.empty() && nums[s.top()] < nums[index]) {
            result[s.top()] = nums[index];
            s.pop();
        }
        if (i < nums.size()) {
            s.push(index);
        }
    }
    return result;
}
```

```python
def nextGreaterElements(nums):
    result = [-1] * len(nums)
    stack = []

    for i in range(len(nums) * 2):
        index = i % len(nums)
        while stack and nums[stack[-1]] < nums[index]:
            result[stack.pop()] = nums[index]
        if i < len(nums):
            stack.append(index)

    return result
```


```python
def convert_to_base7(num: int) -> str:
    if num == 0:
        return "0"
    result = ""
    negative = num < 0
    if negative:
        num *= -1
    while num > 0:
        result = str(num % 7) + result
        num //= 7
    return "-" + result if negative else result
```

```java
public String convertToBase7(int num) {
    if (num == 0) return "0";
    StringBuilder result = new StringBuilder();
    boolean negative = num < 0;
    if (negative) num *= -1;
    while (num > 0) {
        result.insert(0, num % 7);
        num /= 7;
    }
    return negative ? "-" + result.toString() : result.toString();
}
```


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

using namespace std;

int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
    int m = maze.size(), n = maze[0].size();
    vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    vector<vector<int>> dist(m, vector<int> (n, -1));

    queue<pair<int, int>> q;

    dist[start[0]][start[1]] = 0;
    q.push({start[0], start[1]});

    while (!q.empty()) {
        int x = q.front().first, y = q.front().second;
        q.pop();

        for (auto dir : directions) {
            int newX = x + dir.first;
            int newY = y + dir.second;
            int step = 0;

            while (newX >= 0 && newX < m && newY >= 0 && newY < n && maze[newX][newY] == 0) {
                newX += dir.first;
                newY += dir.second;
                step++;
            }

            newX -= dir.first;
            newY -= dir.second;

            if (dist[newX][newY] == -1 || dist[x][y] + step < dist[newX][newY]) {
                dist[newX][newY] = dist[x][y] + step;
                q.push({newX, newY});
            }
        }
    }

    return dist[destination[0]][destination[1]];
}
```

```java
import java.util.PriorityQueue;

public int shortestDistance(int[][] maze, int[] start, int[] destination) {
    int m = maze.length, n = maze[0].length;
    int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    int[][] dist = new int[m][n];

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            dist[i][j] = -1;
        }
    }

    PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> a[2] - b[2]);

    dist[start[0]][start[1]] = 0;
    q.offer(new int[]{start[0], start[1], 0});

    while (!q.isEmpty()) {
        int[] cur = q.poll();
        int x = cur[0], y = cur[1];

        for (int[] dir : directions) {
            int newX = x + dir[0];
            int newY = y + dir[1];
            int step = 0;

            while (newX >= 0 && newX < m && newY >= 0 && newY < n && maze[newX][newY] == 0) {
                newX += dir[0];
                newY += dir[1];
                step++;
            }

            newX -= dir[0];
            newY -= dir[1];

            if (dist[newX][newY] == -1 || dist[x][y] + step < dist[newX][newY]) {
                dist[newX][newY] = dist[x][y] + step;
                q.offer(new int[]{newX, newY, dist[newX][newY]});
            }
        }
    }

    return dist[destination[0]][destination[1]];
}
```


```python
def find_relative_ranks(score):
    rank_sort = sorted(range(len(score)), key=lambda i: score[i], reverse=True)
    result = [0] * len(score)
    for i, rank in enumerate(rank_sort):
        result[rank] = i + 1
    return result
```

\[ "Gold Medal ", "Silver Medal ", "Bronze Medal ", "4 ", "5 "\]

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

std::vector<int> findRelativeRanks(std::vector<int>& score) {
    std::vector<int> rank_sort(score.size());
    for(int i = 0; i < score.size(); ++i) rank_sort[i] = i;
    std::sort(rank_sort.begin(), rank_sort.end(), [&](int i1, int i2) { return score[i1] > score[i2]; });
    std::vector<int>  result(score.size());
    for(int i = 0; i < rank_sort.size(); ++i) result[rank_sort[i]] = i + 1;
    return result;
}
```


```cpp
bool checkPerfectNumber(int num) {
    if (num <= 1) return false;
    int sum = 1;
    for (int i = 2; i * i <= num; ++i) {
        if (num % i == 0) {
            sum += i;
            if (i * i != num) sum += num / i;
        }
    }
    return sum == num;
}
```

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

```python
def checkPerfectNumber(num: int) -> bool:
    if num <= 1:
        return False
    sum = 1
    i = 2
    while i * i <= num:
        if num % i == 0:
            sum += i
            if i * i != num:
                sum += num // i
        i += 1
    return sum == num
```


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

void helper(TreeNode* root, std::map<int, int>& counts, int& max_count) {
    if (!root) return;
    int sum = root->val + helper(root->left, counts, max_count) + helper(root->right, counts, max_count);
    counts[sum]++;
    max_count = std::max(max_count, counts[sum]);
}

std::vector<int> findFrequentTreeSum(TreeNode* root) {
    std::map<int, int> counts;
    int max_count = 0;
    helper(root, counts, max_count);
    std::vector<int> result;
    for (const auto& pair : counts) {
        if (pair.second == max_count) result.push_back(pair.first);
    }
    return result;
}
```

```python
from collections import defaultdict

def helper(node, counts):
    if not node: return 0
    val = node.val + helper(node.left, counts) + helper(node.right, counts)
    counts[val] += 1
    return val

def findFrequentTreeSum(root):
    counts = defaultdict(int)
    helper(root, counts)
    max_count = max(counts.values(), default=0)
    return [s for s, c in counts.items() if c == max_count]
```


```java
public int findBottomLeftValue(TreeNode root) {
    int[] maxDepth = new int[1];
    int[] result = new int[1];
    helper(root, 1, maxDepth, result);
    return result[0];
}

private void helper(TreeNode node, int depth, int[] maxDepth, int[] result) {
    if (node == null) return;
    if (depth > maxDepth[0]) {
        maxDepth[0] = depth;
        result[0] = node.val;
    }
    helper(node.left, depth+1, maxDepth, result);
    helper(node.right, depth+1, maxDepth, result);
}
```

```python
def findBottomLeftValue(self, root: TreeNode) -> int:
    result = [0, 0] # [depth, value]
    self.helper(root, 1, result)
    return result[1]

def helper(self, node, depth, result):
    if not node:
        return
    if depth > result[0]:
        result[0] = depth
        result[1] = node.val

    self.helper(node.left, depth+1, result)
    self.helper(node.right, depth+1, result)
```


```java
public int findRotateSteps(String ring, String key) {
    int n = ring.length(), m = key.length();
    int[][] dp = new int[m + 1][n];

    for (int i = m - 1; i >= 0; --i) {
        for (int j = 0; j < n; ++j) {
            dp[i][j] = Integer.MAX_VALUE;
            for (int k = 0; k < n; ++k) {
                if (ring.charAt(k) == key.charAt(i)) {
                    int diff = Math.abs(j - k);
                    int step = Math.min(diff, n - diff);
                    dp[i][j] = Math.min(dp[i][j], step + dp[i + 1][k]);
                }
            }
        }
    }

    return dp[0][0] + m;
}
```

```python
def find_rotate_steps(ring: str, key: str) -> int:
    n, m = len(ring), len(key)
    dp = [[0] * n for _ in range(m + 1)]

    for i in range(m - 1, -1, -1):
        for j in range(n):
            dp[i][j] = float('inf')
            for k in range(n):
                if ring[k] == key[i]:
                    diff = abs(j - k)
                    step = min(diff, n - diff)
                    dp[i][j] = min(dp[i][j], step + dp[i + 1][k])

    return dp[0][0] + m
```


```python
from collections import deque

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def largestValues(root: TreeNode):
    if not root:
        return []
    result = []
    queue = deque([root])

    while queue:
        size = len(queue)
        max_val = float('-inf')
        for _ in range(size):
            node = queue.popleft()
            max_val = max(max_val, node.val)

            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        result.append(max_val)

    return result
```

```java
import java.util.*;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
}

public List<Integer> largestValues(TreeNode root) {
    if (root == null) return new ArrayList<>();
    List<Integer> result = new ArrayList<>();
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);

    while (!queue.isEmpty()) {
        int size = queue.size();
        int max_val = Integer.MIN_VALUE;
        for (int i = 0; i < size; i++) {
            TreeNode node = queue.poll();
            max_val = Math.max(max_val, node.val);

            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }
        result.add(max_val);
    }
    return result;
}
```


```java
public int findMinMoves(int[] machines) {
    int n = machines.length;
    int totalDresses = 0;
    for (int m : machines) totalDresses += m;
    if (totalDresses % n != 0) return -1;
    int average = totalDresses / n;
    int moves = 0, imbalance = 0;

    for (int i = 0; i < n; i++) {
        imbalance += machines[i] - average;
        moves = Math.max(moves, Math.max(Math.abs(imbalance), machines[i] - average));
    }

    return moves;
}
```

```python
def find_min_moves(machines):
    n = len(machines)
    total_dresses = sum(machines)
    if total_dresses % n != 0:
        return -1
    average = total_dresses // n
    moves = 0
    imbalance = 0

    for i in range(n):
        imbalance += machines[i] - average
        moves = max(moves, abs(imbalance), machines[i] - average)

    return moves
```


```cpp
bool detectCapitalUse(string word) {
    int numCapital = 0;
    for (char c : word) {
        if (isupper(c)) numCapital++;
    }
    return numCapital == 0 || numCapital == word.size() || (numCapital == 1 && isupper(word[0]));
}
```

FlaG
leetcode
Algorithms -
USA -
miSsissipi -
Google
USA
WORLD
flAg
Algorithms
Google -
hello
hello -
miSsissipi
USA
leetcode -
FlaG -

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

```python
def detectCapitalUse(word: str) -> bool:
    numCapital = sum(1 for c in word if c.isupper())
    return numCapital == 0 or numCapital == len(word) or (numCapital == 1 and word[0].isupper())
```


```java
public int findLUSlength(String a, String b) {
    if (a.equals(b)) {
        return -1;
    }
    return Math.max(a.length(), b.length());
}
```

```python
def findLUSlength(a: str, b: str) -> int:
    if a == b:
        return -1
    return max(len(a), len(b))
```


```python
def find_lus_length(strs):
    max_length = -1
    for i in range(len(strs)):
        is_uncommon = True
        for j in range(len(strs)):
            if i != j and strs[i] in strs[j]:
                is_uncommon = False
                break
        if is_uncommon:
            max_length = max(max_length, len(strs[i]))
    return max_length
```

abc def ghi jkl mno pqr stu vwx yz bcdefg

abc def ghi jkl mno pqr stu vwx yz abcdefg

abc def ghi jkl mno pqr stu vwx yz cdeef

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

int findLUSlength(std::vector<std::string>& strs) {
    int maxLength = -1;
    for(int i = 0; i < strs.size(); ++i) {
        bool isUncommon = true;
        for(int j = 0; j < strs.size(); ++j) {
            if(i != j && std::search(strs[j].begin(), strs[j].end(), strs[i].begin(), strs[i].end()) != strs[j].end()) {
                isUncommon = false;
                break;
            }
        }
        if(isUncommon) {
            maxLength = std::max(maxLength, static_cast<int>(strs[i].length()));
        }
    }
    return maxLength;
}
```


```java
import java.util.HashMap;

public boolean checkSubarraySum(int[] nums, int k) {
    int n = nums.length, sum = 0;
    HashMap<Integer, Integer> map = new HashMap<>();
    map.put(0, -1);
    for (int i = 0; i < n; i++) {
        sum += nums[i];
        if (k != 0) sum %= k;
        if (map.containsKey(sum)) {
            if (i - map.get(sum) > 1) return true;
        } else {
            map.put(sum, i);
        }
    }
    return false;
}
```

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

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

bool checkSubarraySum(std::vector<int>& nums, int k) {
    int n = nums.size(), sum = 0;
    std::unordered_map<int, int> mp;
    mp[0] = -1;
    for (int i = 0; i < n; ++i) {
        sum += nums[i];
        if (k != 0) sum %= k;
        if (mp.count(sum)) {
            if (i - mp[sum] > 1) return true;
        } else {
            mp[sum] = i;
        }
    }
    return false;
}
```


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

bool isSubsequence(const std::string &s, const std::string &word) {
    int i = 0, j = 0;
    while (i < s.size() && j < word.size()) {
        if (s[i] == word[j]) {
            j++;
        }
        i++;
    }
    return j == word.size();
}

std::string findLongestWord(std::string s, std::vector<std::string> &dictionary) {
    std::string longest = "";
    std::sort(dictionary.begin(), dictionary.end());
    for (const std::string &word : dictionary) {
        if (isSubsequence(s, word)) {
            if (word.size() > longest.size()) {
                longest = word;
            }
        }
    }
    return longest;
}
```

s =  "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\]

abpcplea
[ "apple ", "banana ", "apricot ", "kiwi "]

 Codility
["Code", "Cody", "ility", "tivity"]

abpcplea
[ "apple ", "banana ", "apricot ", "grapefruit "]

abpcplea
[ "apple ", "banana ", "apricot ", "nectarine "]

abpcplea
[ "apple ", "banana ", "apricot ", "prune "]

abpcplea
[ "apple ", "banana ", "apricot ", "lemon "]

abpcplea
["ale", "apple", "monkey", "plea"]

abpcplea
[ "apple ", "plea ", "banana ", "apricot "]

abpcplea
[ "apple ", "banana ", "apricot ", "quince "]

abpcplea
[ "apple ", "banana ", "apricot ", "grape "]

abpcplea
[ "apple ", "banana ", "apricot ", "pomegranate "]

abpcplea
[ "apple ", "banana ", "apricot ", "lime "]

abpcplea
[ "apple ", "banana ", "apricot ", "peach "]

abpcplea
[ "apple ", "banana ", "apricot ", "raspberry "]

mississippi
["issippi", "issip", "miss", "pi"]

abpcplea
[ "apple ", "banana ", "apricot ", "pineapple "]

abpcplea
[ "apple ", "banana ", "apricot ", "pear "]

abpcplea
[ "ale ", "apple ", "monkey ", "plea "]

abpcplea
[ "apple ", "banana ", "apricot ", "orange "]

abpcplea
[ "apple ", "banana ", "apricot ", "plum "]

abpcplea
[ "apple ", "banana ", "apricot ", "strawberry "]

abpcplea
[ "apple ", "banana ", "apricot ", "mango "]

zookeeper
["zoo", "keeper", "poo", "keeperz"]

abpcplea
[ "apple ", "banana ", "apricot ", "watermelon "]

entertainer
["enter", "rain", "tainer", "entertain"]

apple issippi aabc ility ample 12345 keeper entertain

```java
import java.util.Arrays;

public String findLongestWord(String s, String[] dictionary) {
    String longest = "";
    Arrays.sort(dictionary);
    for (String word : dictionary) {
        if (isSubsequence(s, word)) {
            if (word.length() > longest.length()) {
                longest = word;
            }
        }
    }
    return longest;
}

private boolean isSubsequence(String s, String word) {
    int i = 0, j = 0;
    while (i < s.length() && j < word.length()) {
        if (s.charAt(i) == word.charAt(j)) {
            j++;
        }
        i++;
    }
    return j == word.length();
}
```


```java
public int findMaxLength(int[] nums) {
    HashMap<Integer, Integer> counts = new HashMap<>();
    counts.put(0, -1);
    int max_len = 0, count = 0;
    for (int i = 0; i < nums.length; i++) {
        count += (nums[i] == 1) ? 1 : -1;
        if (counts.containsKey(count))
            max_len = Math.max(max_len, i - counts.get(count));
        else
            counts.put(count, i);
    }
    return max_len;
}
```

```cpp
int findMaxLength(vector<int>& nums) {
    unordered_map<int, int> counts;
    counts[0] = -1;
    int max_len = 0, count = 0;
    for (int i = 0; i < nums.size(); i++) {
        count += (nums[i] == 1) ? 1 : -1;
        if (counts.count(count))
            max_len = max(max_len, i - counts[count]);
        else
            counts[count] = i;
    }
    return max_len;
}
```


```python
def countArrangement(n: int) -> int:
    def helper(idx: int, visited: List[bool], n: int) -> int:
        if idx > n:
            return 1

        count = 0
        for i in range(1, n+1):
            if not visited[i] and (idx % i == 0 or i % idx == 0):
                visited[i] = True
                count += helper(idx+1, visited, n)
                visited[i] = False

        return count

    visited = [False] * (n+1)
    return helper(1, visited, n)
```

```java
int countArrangement(int n) {
    int[] res = new int[]{0};
    boolean[] visited = new boolean[n+1];
    helper(n, 1, visited, res);
    return res[0];
}

void helper(int n, int idx, boolean[] visited, int[] res) {
    if (idx > n) {
        res[0]++;
    }

    for(int i=1; i<=n; i++){
        if (!visited[i] && (idx % i == 0 || i % idx == 0)) {
            visited[i] = true;
            helper(n, idx+1, visited, res);
            visited[i] = false;
        }
    }
}
```


```cpp
#include <algorithm>
#include <climits>

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution {
public:
    int getMinimumDifference(TreeNode* root) {
        int result = INT_MAX, prev = -1;
        minimumDifference(root, result, prev);
        return result;
    }

    void minimumDifference(TreeNode* node, int& result, int& prev) {
        if (!node) return;
        minimumDifference(node->left, result, prev);
        if (prev != -1) {
            result = std::min(result, node->val - prev);
        }
        prev = node->val;
        minimumDifference(node->right, result, prev);
    }
};
```

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

class Solution:
    def getMinimumDifference(self, root: TreeNode) -> int:
        result = float('inf')
        prev = None

        def inorderTraversal(node):
            nonlocal result, prev
            if node is None:
                return
            inorderTraversal(node.left)
            if prev is not None:
                result = min(result, node.val - prev.val)
            prev = node
            inorderTraversal(node.right)

        inorderTraversal(root)
        return result
```


```java
public int findLonelyPixel(char[][] picture) {
    int m = picture.length, n = picture[0].length;
    int[] row = new int[m], col = new int[n];

    for(int i = 0; i < m; ++i) {
        for(int j = 0; j < n; ++j) {
            if(picture[i][j] == 'B') {
                row[i]++;
                col[j]++;
            }
        }
    }

    int lonely = 0;
    for(int i = 0; i < m; ++i) {
        for(int j = 0; j < n; ++j) {
            if(picture[i][j] == 'B' && row[i] == 1 && col[j] == 1) {
                lonely++;
            }
        }
    }

    return lonely;
}
```

```python
def findLonelyPixel(picture):
    m, n = len(picture), len(picture[0])
    row, col = [0] * m, [0] * n

    for i in range(m):
        for j in range(n):
            if picture[i][j] == 'B':
                row[i] += 1
                col[j] += 1

    lonely = 0
    for i in range(m):
        for j in range(n):
            if picture[i][j] == 'B' and row[i] == 1 and col[j] == 1:
                lonely += 1

    return lonely
```


```python
def find_pairs(nums, k):
    if k < 0:
        return 0
    starters = set()
    occurrences = {}
    for num in nums:
        if num + k in occurrences:
            starters.add(num)
        if num - k in occurrences:
            starters.add(num - k)
        occurrences[num] = occurrences.get(num, 0) + 1
    return len(starters)
```

```java
import java.util.HashMap;
import java.util.HashSet;

public int findPairs(int[] nums, int k) {
    if (k < 0) return 0;
    HashSet<Integer> starters = new HashSet<>();
    HashMap<Integer, Integer> occurrences = new HashMap<>();
    for (int num : nums) {
        if (occurrences.containsKey(num + k)) starters.add(num);
        if (occurrences.containsKey(num - k)) starters.add(num - k);
        occurrences.put(num, occurrences.getOrDefault(num, 0) + 1);
    }
    return starters.size();
}
```


```cpp
int findBlackPixel(vector<vector<char>>& picture, int target) {
    int m = picture.size();
    int n = picture[0].size();
    vector<int> rows(m, 0), cols(n, 0);
    unordered_map<string, int> rowCounts;
    for (int i = 0; i < m; ++i) {
        string row;
        for (int j = 0; j < n; ++j) {
            if (picture[i][j] == 'B') {
                rows[i]++;
                cols[j]++;
            }
            row.push_back(picture[i][j]);
        }
        if (rows[i] == target)
            rowCounts[row]++;
    }
    int ans = 0;
    for (auto &[row, count] : rowCounts) {
        if (count == target) {
            for (int j = 0; j < n; ++j) {
                if (row[j] == 'B' && cols[j] == target)
                    ans += count;
            }
        }
    }
    return ans;
}
```

```python
def findBlackPixel(picture, target):
    m, n = len(picture), len(picture[0])
    rows = [0] * m
    cols = [0] * n
    rowCounts = {}
    for i in range(m):
        row = ""
        for j in range(n):
            if picture[i][j] == 'B':
                rows[i] += 1
                cols[j] += 1
            row += picture[i][j]
        if rows[i] == target:
            rowCounts[row] = rowCounts.get(row, 0) + 1
    ans = 0
    for row, count in rowCounts.items():
        if count == target:
            for j in range(n):
                if row[j] == 'B' and cols[j] == target:
                    ans += count
    return ans
```


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

class Solution:
    def __init__(self):
        self.sum = 0

    def convertBST(self, root: TreeNode) -> TreeNode:
        if root:
            self.convertBST(root.right)
            self.sum += root.val
            root.val = self.sum
            self.convertBST(root.left)

        return root
```

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

class Solution {
    int sum = 0;

    public TreeNode convertBST(TreeNode root) {
        if (root != null) {
            convertBST(root.right);
            sum += root.val;
            root.val = sum;
            convertBST(root.left);
        }

        return root;
    }
}
```


```python
def findMinDifference(timePoints):
    timePoints.sort()
    min_difference = float('inf')

    for i in range(len(timePoints)):
        h1, m1 = map(int, timePoints[i].split(':'))
        h2, m2 = map(int, timePoints[(i+1)%len(timePoints)].split(':'))
        cur_difference = abs((h1 * 60 + m1) - (h2 * 60 + m2))
        min_difference = min(min_difference, 1440 - cur_difference if cur_difference > 720 else cur_difference)

    return min_difference
```

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

public int findMinDifference(List<String> timePoints) {
    Collections.sort(timePoints);
    int minDifference = Integer.MAX_VALUE;

    for (int i = 0; i < timePoints.size(); ++i) {
        int curDifference = Math.abs((Integer.parseInt(timePoints.get(i).substring(0, 2)) * 60 + Integer.parseInt(timePoints.get(i).substring(3, 5))) - (Integer.parseInt(timePoints.get((i + 1) % timePoints.size()).substring(0, 2)) * 60 + Integer.parseInt(timePoints.get((i + 1) % timePoints.size()).substring(3, 5))));
        minDifference = Math.min(minDifference, curDifference > 720 ? 1440 - curDifference : curDifference);
    }

    return minDifference;
}
```


```cpp
int singleNonDuplicate(vector<int>& nums) {
    int low = 0, high = nums.size() - 1;
    while (low < high) {
        int mid = low + (high - low) / 2;
        if (mid % 2 == 1)
            mid--;
        if (nums[mid] == nums[mid + 1])
            low = mid + 2;
        else
            high = mid;
    }
    return nums[low];
}
```

```python
def singleNonDuplicate(nums):
    low, high = 0, len(nums) - 1
    while low < high:
        mid = low + (high - low) // 2
        if mid % 2 == 1:
            mid -= 1
        if nums[mid] == nums[mid + 1]:
            low = mid + 2
        else:
            high = mid
    return nums[low]
```


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

string reverseStr(string s, int k) {
    for (int i = 0; i < s.size(); i += 2*k) {
        if (i + k <= s.size()) {
            reverse(s.begin() + i, s.begin() + i + k);
        } else {
            reverse(s.begin() + i, s.end());
        }
    }
    return s;
}
```

gfedcba gfedcba gfedcba bacdfeg gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba edcbafg gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba bacdfeg gfedcba gfedcba gfedcba gfedcba gfedcba fedcbag gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba edcbafg gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba cbadefihgj gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba 432156789 gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba dcbaefg dcbaefg fedcbag abcdefg gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba bacdfeg gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba edcbafg gfedcba gfedcba dcbaefg gfedcba gfedcba gfedcba gfedcba gfedcba fedcbag edcbafg a gfedcba 543216789054321678905432167890 gfedcba cbadefg gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba ab gfedcba gfedcba gfedcba gfedcba bacdfeg cbadefg fedcbag gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba cbadefg gfedcba gfedcba gfedcba dcbaefg cbadefg gfedcba bacdfeg gfedcba gfedcba gfedcba gfedcba gfedcba bacdfeg gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba gfedcba 321456 gfedcba gfedcba

```python
def reverseStr(s, k):
    chars = list(s)
    for i in range(0, len(chars), 2 * k):
        chars[i:i + k] = reversed(chars[i:i + k])
    return "".join(chars)
```


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

def diameter_of_binary_tree(root):
    def _diameter_of_binary_tree(node):
        if not node:
            return 0, 0
        left_height, left_diameter = _diameter_of_binary_tree(node.left)
        right_height, right_diameter = _diameter_of_binary_tree(node.right)
        height = 1 + max(left_height, right_height)
        diameter = max(left_height + right_height, max(left_diameter, right_diameter))
        return height, diameter

    return _diameter_of_binary_tree(root)[1]
```

```java
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public int[] diameterHelper(TreeNode root) {
    if (root == null) return new int[]{0, 0};
    int[] left = diameterHelper(root.left);
    int[] right = diameterHelper(root.right);
    int maxHeight = 1 + Math.max(left[0], right[0]);
    int maxDiameter = Math.max(left[0] + right[0], Math.max(left[1], right[1]));
    return new int[]{maxHeight, maxDiameter};
}

public int diameterOfBinaryTree(TreeNode root) {
    return diameterHelper(root)[1];
}
```


```python
def findContestMatch(n):
    matches = [str(i) for i in range(1, n + 1)]

    while n > 1:
        for i in range(n // 2):
            matches[i] = "(" + matches[i] + "," + matches[n - 1 - i] + ")"
        n //= 2

    return matches[0]
```

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

string findContestMatch(int n) {
    vector<string> matches(n);
    for (int i = 1; i <= n; i++) {
        matches[i - 1] = to_string(i);
    }

    while (n > 1) {
        for (int i = 0; i < n / 2; i++) {
            matches[i] = "(" + matches[i] + "," + matches[n - 1 - i] + ")";
        }
        n /= 2;
    }

    return matches[0];
}
```


```cpp
class Solution {
public:
    void leftBoundary(TreeNode* node, vector<int>& boundary) {
        if (!node || (!node->left && !node->right)) return;
        boundary.push_back(node->val);
        if (node->left) leftBoundary(node->left, boundary);
        else leftBoundary(node->right, boundary);
    }

    void rightBoundary(TreeNode* node, vector<int>& boundary) {
        if (!node || (!node->left && !node->right)) return;
        if (node->right) rightBoundary(node->right, boundary);
        else rightBoundary(node->left, boundary);
        boundary.push_back(node->val);
    }

    void leaves(TreeNode* node, vector<int>& boundary) {
        if (!node) return;
        if (!node->left && !node->right) {
            boundary.push_back(node->val);
        }
        leaves(node->left, boundary);
        leaves(node->right, boundary);
    }

    vector<int> boundaryOfBinaryTree(TreeNode* root) {
        vector<int> res;
        if (!root) return res;
        res.push_back(root->val);
        leftBoundary(root->left, res);
        leaves(root, res);
        rightBoundary(root->right, res);
        return res;
    }
};
```

```java
class Solution {
    public void leftBoundary(TreeNode node, List<Integer> boundary) {
        if (node == null || (node.left == null && node.right == null)) return;
        boundary.add(node.val);
        if (node.left != null) leftBoundary(node.left, boundary);
        else leftBoundary(node.right, boundary);
    }

    public void rightBoundary(TreeNode node, List<Integer> boundary) {
        if (node == null || (node.left == null && node.right == null)) return;
        if (node.right != null) rightBoundary(node.right, boundary);
        else rightBoundary(node.left, boundary);
        boundary.add(node.val);
    }

    public void leaves(TreeNode node, List<Integer> boundary) {
        if (node == null) return;
        if (node.left == null && node.right == null) {
            boundary.add(node.val);
        }
        leaves(node.left, boundary);
        leaves(node.right, boundary);
    }

    public List<Integer> boundaryOfBinaryTree(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        res.add(root.val);
        leftBoundary(root.left, res);
        leaves(root, res);
        rightBoundary(root.right, res);
        return res;
    }
}
```


```python
def removeBoxes(boxes):
    def dfs(l, r, k):
        if l > r: return 0
        if dp[l][r][k] != 0: return dp[l][r][k]

        while r > l and boxes[r] == boxes[r - 1]:
            r -= 1
            k += 1

        dp[l][r][k] = (k + 1) * (k + 1) + dfs(l, r - 1, 0)

        for i in range(l, r):
            if boxes[i] == boxes[r]:
                dp[l][r][k] = max(dp[l][r][k], dfs(l, i, k + 1) + dfs(i + 1, r - 1, 0))

        return dp[l][r][k]

    dp = [[[0] * 100 for _ in xrange(100)] for _ in xrange(100)]
    return dfs(0, len(boxes) - 1, 0)
```

```java
public int removeBoxes(int[] boxes) {
    int[][][] dp = new int[100][100][100];
    return dfs(boxes, dp, 0, boxes.length - 1, 0);
}

private int dfs(int[] boxes, int[][][] dp, int l, int r, int k) {
    if (l > r) return 0;
    if (dp[l][r][k] != 0) return dp[l][r][k];

    while (r > l && boxes[r] == boxes[r - 1]) {r--; k++;}

    dp[l][r][k] = (k + 1) * (k + 1) + dfs(boxes, dp, l, r - 1, 0);

    for (int i = l; i < r; i++) {
        if (boxes[i] == boxes[r]) {
            dp[l][r][k] = Math.max(dp[l][r][k], dfs(boxes, dp, l, i, k + 1) + dfs(boxes, dp, i + 1, r - 1, 0));
        }
    }

    return dp[l][r][k];
}
```


```cpp
#include <vector>

using std::vector;

void dfs(vector<vector<int>>& isConnected, vector<bool>& visited, int i) {
    visited[i] = true;
    for (int j = 0; j < isConnected.size(); j++) {
        if (isConnected[i][j] == 1 && !visited[j]) {
            dfs(isConnected, visited, j);
        }
    }
}

int findCircleNum(vector<vector<int>>& isConnected) {
    int provinces = 0;
    vector<bool> visited(isConnected.size(), false);
    for (int i = 0; i < isConnected.size(); i++) {
        if (!visited[i]) {
            dfs(isConnected, visited, i);
            provinces++;
        }
    }
    return provinces;
}
```

```java
public int findCircleNum(int[][] isConnected) {
    int provinces = 0;
    boolean[] visited = new boolean[isConnected.length];
    for (int i = 0; i < isConnected.length; i++) {
        if (!visited[i]) {
            dfs(isConnected, visited, i);
            provinces++;
        }
    }
    return provinces;
}

private void dfs(int[][] isConnected, boolean[] visited, int i) {
    visited[i] = true;
    for (int j = 0; j < isConnected.length; j++) {
        if (isConnected[i][j] == 1 && !visited[j]) {
            dfs(isConnected, visited, j);
        }
    }
}
```


```python
def find_triplet_equal_sum(nums):
    n = len(nums)
    prefix_sum = [0] * (n + 1)

    for i in range(n):
        prefix_sum[i + 1] = prefix_sum[i] + nums[i]

    for i in range(1, n - 2):
        for j in range(i + 2, n - 1):
            for k in range(j + 2, n):
                s1 = prefix_sum[i]
                s2 = prefix_sum[j] - prefix_sum[i + 1]
                s3 = prefix_sum[k] - prefix_sum[j + 1]
                s4 = prefix_sum[n] - prefix_sum[k + 1]
                if s1 == s2 == s3 == s4:
                    return True
    return False
```

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

```java
boolean find_triplet_equal_sum(int[] nums) {
    int n = nums.length;
    int[] prefix_sum = new int[n + 1];

    for (int i = 0; i < n; ++i) {
        prefix_sum[i + 1] = prefix_sum[i] + nums[i];
    }

    for (int i = 1; i + 2 < n; ++i) {
        for (int j = i + 2; j + 1 < n; ++j) {
            for (int k = j + 2; k < n; ++k) {
                int s1 = prefix_sum[i];
                int s2 = prefix_sum[j] - prefix_sum[i + 1];
                int s3 = prefix_sum[k] - prefix_sum[j + 1];
                int s4 = prefix_sum[n] - prefix_sum[k + 1];
                if (s1 == s2 && s2 == s3 && s3 == s4) {
                    return true;
                }
            }
        }
    }
    return false;
}
```


```java
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public int longestConsecutivePathUtil(TreeNode root, int[] maxLength) {
    if (root == null) return 0;
    int left = longestConsecutivePathUtil(root.left, maxLength) + 1;
    int right = longestConsecutivePathUtil(root.right, maxLength) + 1;
    if (root.left != null && root.left.val != root.val + 1) left = 1;
    if (root.right != null && root.right.val != root.val + 1) right = 1;
    int length = Math.max(left, right);
    maxLength[0] = Math.max(maxLength[0], left + right - 1);
    return length;
}

public int longestConsecutive(TreeNode root) {
    int[] maxLength = new int[1];
    longestConsecutivePathUtil(root, maxLength);
    return maxLength[0];
}
```

```cpp
#include<algorithm>

class TreeNode {
public:
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

int longestConsecutivePathUtil(TreeNode* root, int& maxLength) {
    if (root == nullptr) return 0;
    int left = longestConsecutivePathUtil(root->left, maxLength) + 1;
    int right = longestConsecutivePathUtil(root->right, maxLength) + 1;
    if (root->left != nullptr && root->left->val != root->val + 1) left = 1;
    if (root->right != nullptr && root->right->val != root->val + 1) right = 1;
    int length = std::max(left, right);
    maxLength = std::max(maxLength, left + right - 1);
    return length;
}

int longestConsecutive(TreeNode* root) {
    int maxLength = 0;
    longestConsecutivePathUtil(root, maxLength);
    return maxLength;
}
```


```cpp
#include <string>

bool checkRecord(std::string s) {
    int late = 0, absent = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == 'A') {
            absent++;
            late = 0;
        } else if (s[i] == 'L') {
            late++;
        } else {
            late = 0;
        }

        if (absent >= 2 || late >= 3) return false;
    }
    return true;
}
```

AAPLPLLPL AAAAAA L PLA LAAP PPP PPALLL AAPPLPLLP PPALLL AAPLPLPLL AAPP APPAPLP AAPL AAPPPP AAPLPLPLLP AP PPALLP AAPLPLL AAPPLLPLL AAPLPP AAPPPLLP PLL PPPLLALL AAPLPLLPL AAPPLLP AAPLPLPLLP AAPLPLP PPALLP AALP AAPLPLLP LLL LPP AAPLPLLP PLLALL AAPPLPLPLL PPA ALP AAPLLP PPLLALL AAPLLPLL A LP PPAPLL LALLLL LLP AAP LAL PPALLP APLPLA AAPLP AAPLPLL

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

```python
def checkRecord(s: str) -> bool:
    late, absent = 0, 0
    for c in s:
        if c == 'A':
            absent += 1
            late = 0
        elif c == 'L':
            late += 1
        else:
            late = 0

        if absent >= 2 or late >= 3:
            return False
    return True
```


```cpp
int checkRecord(int n) {
    int M = 1000000007;
    vector<long long> dp(6, 1);  // {latent state 0, latent state 1, ..., latent state 5}
    while (n--) {
        vector<long long> next_dp(6, 0);
        next_dp[0] = (dp[0] + dp[1] + dp[2]) % M;
        next_dp[1] = dp[0];
        next_dp[2] = dp[1];
        next_dp[3] = (dp[3] + dp[4] + dp[5]) % M;
        next_dp[4] = dp[3];
        next_dp[5] = dp[4];
        dp = next_dp;
    }
    return (dp[0] + dp[1] + dp[2] + dp[3] + dp[4] + dp[5]) % M;
}
```

```python
def checkRecord(n: int) -> int:
    M = 1000000007
    dp = [1] * 6  # [latent state 0, latent state 1, ..., latent state 5]
    while n:
        next_dp = [0] * 6
        next_dp[0] = (dp[0] + dp[1] + dp[2]) % M
        next_dp[1] = dp[0]
        next_dp[2] = dp[1]
        next_dp[3] = (dp[3] + dp[4] + dp[5]) % M
        next_dp[4] = dp[3]
        next_dp[5] = dp[4]
        dp = next_dp
        n -= 1
    return sum(dp) % M
```


```python
def optimal_division(nums):
    n = len(nums)
    if n == 1:
        return str(nums[0])
    if n == 2:
        return str(nums[0]) + '/' + str(nums[1])
    res = str(nums[0]) + '/('
    for i in range(1, n - 1):
        res += str(nums[i]) + '/'
    res += str(nums[n - 1]) + ')'
    return res
```

```java
public String optimalDivision(int[] nums) {
    int n = nums.length;
    if (n == 1) return Integer.toString(nums[0]);
    if (n == 2) return Integer.toString(nums[0]) + "/" + Integer.toString(nums[1]);
    StringBuilder res = new StringBuilder(Integer.toString(nums[0]) + "/(");
    for (int i = 1; i < n - 1; ++i) {
        res.append(Integer.toString(nums[i])).append("/");
    }
    res.append(Integer.toString(nums[n - 1])).append(")");
    return res.toString();
}
```


```python
from collections import defaultdict

def least_bricks(wall):
    edge_count = defaultdict(int)
    max_count = 0

    for row in wall:
        edge_position = 0
        for i in range(len(row) - 1):
            edge_position += row[i]
            edge_count[edge_position] += 1
            max_count = max(max_count, edge_count[edge_position])

    return len(wall) - max_count
```

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

int leastBricks(std::vector<std::vector<int>>& wall) {
    std::unordered_map<int, int> edge_count;
    int max_count = 0;

    for (const auto& row : wall) {
        int edge_position = 0;
        for (size_t i = 0; i < row.size() - 1; ++i) {
            edge_position += row[i];
            ++edge_count[edge_position];
            max_count = std::max(max_count, edge_count[edge_position]);
        }
    }

    return wall.size() - max_count;
}
```


```python
def splitLoopedString(strs):
    ans = ''
    cur = ''.join(max(s, s[::-1]) for s in strs)

    for i, s in enumerate(strs):
        for xstr in (s, s[::-1]):
            for j in range(len(xstr)):
                t = xstr[j:] + cur[len(xstr):] + cur[:len(xstr)] + xstr[:j]
                ans = max(ans, t)
        cur = cur[len(s):] + cur[:len(s)]

    return ans
```

["abc ", "defghijklmnopqr"]
["abc", "abc"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["", "xyz"]
["abc ", "defghijklmnopqrstuv"]
["abc"]
["abc ", "defghijklmnopqrstuvwx"]
["abc", "xyz", "zyx", "123"]
["abc ", "defghijklmnopqrs"]
["abc ", "defghijklmnopqrstuvwx"]
["a", "b", "c"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghij"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc", ""]
["abc ", "defghijklmnopq"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc", "xyz"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijk"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrst"]
["abc ", "defg"]
["abc ", "defghijklm"]
["abc ", "defghijklmnopqrstuvwx"]
["abc", "123", "", "xyz"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnop"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "xyz "]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvw"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmn"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["zab", "ycd"]
["abc ", "defghijklmnopqrstu"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "def"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijkl"]
["123", "abc", "xyz"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmno"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghi"]
["xyz", "xyz"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
[ "abc ", "xyz "]
["abc ", "defgh"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]
["abc ", "defghijklmnopqrstuvwx"]

mlkjihgfedabc zyx xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc vutsrqponmlkjihgfedabc zyxcba321 xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc tsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc srqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc ihgfedabc xwvutsrqponmlkjihgfedabc hgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc cba wvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc lkjihgfedabc ccbaab xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc qponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc zyxcba xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc nmlkjihgfedabc zyxabc onmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc utsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc fedabc zycdba xwvutsrqponmlkjihgfedabc zzyx321cbaxy xwvutsrqponmlkjihgfedabc cba rqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc zyx321cba gfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc jihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc kjihgfedabc cab xwvutsrqponmlkjihgfedabc zyxabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc ponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc xwvutsrqponmlkjihgfedabc zzyxxy xwvutsrqponmlkjihgfedabc

```java
import java.util.*;

public String splitLoopedString(String[] strs) {
    String ans = "", cur = "";
    for (String s : strs) {
        String rev = new StringBuilder(s).reverse().toString();
        cur += (s.compareTo(rev) > 0) ? s : rev;
    }

    for (int i = 0, k = 0; i < strs.length; i++) {
        String rev = new StringBuilder(strs[i]).reverse().toString();
        for (String xstr : Arrays.asList(strs[i], rev)) {
            for (int j = 0; j < xstr.length(); j++) {
                String t = xstr.substring(j) + cur.substring(k + xstr.length()) + cur.substring(0, k) + xstr.substring(0, j);
                ans = ans.compareTo(t) > 0 ? ans : t;
            }
        }
        k += strs[i].length();
    }
    return ans;
}
```


```java
import java.util.Arrays;

public class Main {
    public int nextGreaterElement(int n) {
        char[] number = String.valueOf(n).toCharArray();
        int i, j;
        for (i = number.length - 1; i > 0; i--) {
            if (number[i - 1] < number[i]) {
                break;
            }
        }

        if (i == 0) {
            return -1;
        }

        int x = number[i - 1], smallest = i;
        for (j = i + 1; j < number.length; j++) {
            if (number[j] > x && number[j] < number[smallest]) {
                smallest = j;
            }
        }

        char temp = number[i - 1];
        number[i - 1] = number[smallest];
        number[smallest] = temp;

        Arrays.sort(number, i, number.length);

        long result = Long.parseLong(new String(number));

        return (result <= Integer.MAX_VALUE) ? (int) result : -1;
    }
}
```

```cpp
#include <bits/stdc++.h>
using namespace std;

int32_t nextGreaterElement(int n) {
    string num = to_string(n);
    if (next_permutation(num.begin(), num.end())) {
        long long result = stoll(num);
        if (result <= INT32_MAX) {
            return result;
        }
    }
    return -1;
}
```


```cpp
int subarraySum(vector<int>& nums, int k) {
    unordered_map<int, int> prefixSumFrequency;
    prefixSumFrequency[0] = 1;
    int prefixSum = 0, result = 0;

    for (int num : nums) {
        prefixSum += num;
        result += prefixSumFrequency[prefixSum - k];
        prefixSumFrequency[prefixSum]++;
    }

    return result;
}
```

```java
public int subarraySum(int[] nums, int k) {
    Map<Integer, Integer> prefixSumFrequency = new HashMap<>();
    prefixSumFrequency.put(0, 1);
    int prefixSum = 0, result = 0;

    for (int num : nums) {
        prefixSum += num;
        result += prefixSumFrequency.getOrDefault(prefixSum - k, 0);
        prefixSumFrequency.put(prefixSum, prefixSumFrequency.getOrDefault(prefixSum, 0) + 1);
    }

    return result;
}
```


```python
def array_pair_sum(nums):
    nums.sort()
    return sum(nums[::2])
```

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

int arrayPairSum(std::vector<int>& nums) {
    std::sort(nums.begin(), nums.end());
    int sum = 0;
    for (int i = 0; i < nums.size(); i += 2) {
        sum += nums[i];
    }
    return sum;
}
```


```cpp
int longestLine(vector<vector<int>>& mat) {
    int rows = mat.size();
    int cols = mat[0].size();
    int max_length = 0;
    vector<vector<vector<int>>> dp(rows, vector<vector<int>>(cols, vector<int>(4, 0)));

    for (int r = 0; r < rows; ++r) {
        for (int c = 0; c < cols; ++c) {
            if (mat[r][c] == 1) {
                dp[r][c][0] = r > 0 ? dp[r - 1][c][0] + 1 : 1;
                dp[r][c][1] = c > 0 ? dp[r][c - 1][1] + 1 : 1;
                dp[r][c][2] = (r > 0 && c > 0) ? dp[r - 1][c - 1][2] + 1 : 1;
                dp[r][c][3] = (r > 0 && c < cols - 1) ? dp[r - 1][c + 1][3] + 1 : 1;
                max_length = max(max_length, max(dp[r][c][0], max(dp[r][c][1], max(dp[r][c][2], dp[r][c][3]))));
            }
        }
    }
    return max_length;
}
```

```python
def longestLine(mat):
    rows, cols = len(mat), len(mat[0])
    max_length = 0
    dp = [[[0, 0, 0, 0] for _ in range(cols)] for _ in range(rows)]

    for r in range(rows):
        for c in range(cols):
            if mat[r][c] == 1:
                dp[r][c][0] = dp[r - 1][c][0] + 1 if r > 0 else 1
                dp[r][c][1] = dp[r][c - 1][1] + 1 if c > 0 else 1
                dp[r][c][2] = dp[r - 1][c - 1][2] + 1 if r > 0 and c > 0 else 1
                dp[r][c][3] = dp[r - 1][c + 1][3] + 1 if r > 0 and c < cols - 1 else 1
                max_length = max(max_length, max(dp[r][c]))

    return max_length
```


```java
public class ClosestPalindrome {
    public static boolean isPalindrome(String str) {
        int left = 0;
        int right = str.length() - 1;
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    public static int closestPalindrome(String n) {
        int num = Integer.parseInt(n);
        int left = num - 1;
        int right = num + 1;

        while (true) {
            if (isPalindrome(Integer.toString(left))) {
                return left;
            }
            if (isPalindrome(Integer.toString(right))) {
                return right;
            }
            left--;
            right++;
        }
    }
}
```

```python
def is_palindrome(s: str) -> bool:
    return s == s[::-1]

def closest_palindrome(n: str) -> int:
    num = int(n)
    left = num - 1
    right = num + 1

    while True:
        if is_palindrome(str(left)):
            return left
        if is_palindrome(str(right)):
            return right
        left -= 1
        right += 1
```


```java
public int arrayNesting(int[] nums) {
    int n = nums.length;
    int max_len = 0;
    for (int i = 0; i < n; ++i) {
        if (nums[i] != -1) {
            int start = nums[i];
            int count = 0;
            while (nums[start] != -1) {
                int temp = start;
                start = nums[start];
                count++;
                nums[temp]=-1;
            }
            max_len = Math.max(max_len, count);
        }
    }
    return max_len;
}
```

```cpp
int arrayNesting(vector<int>& nums) {
    int n = nums.size();
    int max_len = 0;
    for (int i = 0; i < n; ++i) {
        if (nums[i] != -1) {
            int start = nums[i];
            int count = 0;
            while (nums[start] != -1) {
                int temp = start;
                start = nums[start];
                count++;
                nums[temp]=-1;
            }
            max_len = max(max_len, count);
        }
    }
    return max_len;
}
```


```java
public int maxVacationDays(int[][] flights, int[][] days) {
    int n = flights.length;
    int k = days[0].length;
    int[][] memo = new int[n][k];
    for (int i = 0; i < n; i++) {
        Arrays.fill(memo[i], -1);
    }
    return dfs(flights, days, 0, 0, memo);
}

private int dfs(int[][] flights, int[][] days, int week, int city, int[][] memo) {
    int numCities = flights.length;
    int numWeeks = days[0].length;

    if (week == numWeeks) {
        return 0;
    }

    if (memo[city][week] != -1) {
        return memo[city][week];
    }

    int maxVacation = days[city][week] + dfs(flights, days, week + 1, city, memo);

    for (int i = 0; i < numCities; i++) {
        if (flights[city][i] == 1) {
            maxVacation = Math.max(maxVacation, days[i][week] + dfs(flights, days, week + 1, i, memo));
        }
    }

    memo[city][week] = maxVacation;
    return maxVacation;
}
```

```python
def maxVacationDays(flights, days):
    n = len(flights)
    k = len(days[0])
    memo = [[-1] * k for _ in range(n)]

    def dfs(currentWeek, currentCity):
        if currentWeek == k:
            return 0
        if memo[currentCity][currentWeek] != -1:
            return memo[currentCity][currentWeek]

        maxVacation = days[currentCity][currentWeek] + dfs(currentWeek + 1, currentCity)

        for i in range(n):
            if flights[currentCity][i] == 1:
                maxVacation = max(maxVacation, days[i][currentWeek] + dfs(currentWeek + 1, i))

        memo[currentCity][currentWeek] = maxVacation
        return maxVacation

    return dfs(0, 0)
```


```java
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
}

public boolean isSubtree(TreeNode root, TreeNode subRoot) {
    if (root == null) return false;
    if (isIdentical(root, subRoot)) return true;
    return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}

public boolean isIdentical(TreeNode n1, TreeNode n2) {
    if (n1 == null || n2 == null) return n1 == n2;
    if (n1.val != n2.val) return false;
    return isIdentical(n1.left, n2.left) && isIdentical(n1.right, n2.right);
}
```

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

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

def isSubtree(root, subRoot):
    if root is None:
        return False
    if is_identical(root, subRoot):
        return True
    return isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot)

def is_identical(n1, n2):
    if n1 is None or n2 is None:
        return n1 == n2
    if n1.val != n2.val:
        return False
    return is_identical(n1.left, n2.left) and is_identical(n1.right, n2.right)
```


```java
public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) {
    int totalDist = 0;
    int minDiff = Integer.MAX_VALUE;

    for (int[] nut : nuts) {
        int treeDist = Math.abs(tree[0] - nut[0]) + Math.abs(tree[1] - nut[1]);
        int squirrelDist = Math.abs(squirrel[0] - nut[0]) + Math.abs(squirrel[1] - nut[1]);

        totalDist += 2 * treeDist;
        minDiff = Math.min(minDiff, squirrelDist - treeDist);
    }

    return totalDist + minDiff;
}
```

```python
def minDistance(height, width, tree, squirrel, nuts):
    totalDist = 0
    minDiff = float("inf")

    for nut in nuts:
        treeDist = abs(tree[0] - nut[0]) + abs(tree[1] - nut[1])
        squirrelDist = abs(squirrel[0] - nut[0]) + abs(squirrel[1] - nut[1])

        totalDist += 2 * treeDist
        minDiff = min(minDiff, squirrelDist - treeDist)

    return totalDist + minDiff
```


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

public int maxNumberOfCandies(int[] candyType) {
    Set<Integer> uniqueCandies = new HashSet<>();
    for (int type : candyType) {
        uniqueCandies.add(type);
    }
    return Math.min(uniqueCandies.size(), candyType.length / 2);
}
```

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

int maxNumberOfCandies(vector<int>& candyType) {
    unordered_set<int> uniqueCandies(candyType.begin(), candyType.end());
    return min(uniqueCandies.size(), candyType.size() / 2);
}
```


```python
def findPaths(m, n, maxMove, startRow, startColumn):
    MOD = 10**9 + 7
    dp = [[[0]* n for _ in range(m)] for _ in range(maxMove + 1)]
    moves = ((-1, 0), (1, 0), (0, -1), (0, 1))

    for k in range(1, maxMove + 1):
        for i in range(m):
            for j in range(n):
                for move in moves:
                    ni, nj = i + move[0], j + move[1]
                    if ni < 0 or ni >= m or nj < 0 or nj >= n:
                        dp[k][i][j] = (dp[k][i][j] + 1) % MOD
                    else:
                        dp[k][i][j] = (dp[k][i][j] + dp[k - 1][ni][nj]) % MOD

    return dp[maxMove][startRow][startColumn]
```

m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0

```java
public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
    int MOD = 1000000007;
    int[][][] dp = new int[maxMove + 1][m][n];
    int[][] moves = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    for (int k = 1; k <= maxMove; k++) {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                for (int[] move : moves) {
                    int ni = i + move[0], nj = j + move[1];
                    if (ni < 0 || ni >= m || nj < 0 || nj >= n) {
                        dp[k][i][j] = (dp[k][i][j] + 1) % MOD;
                    } else {
                        dp[k][i][j] = (dp[k][i][j] + dp[k - 1][ni][nj]) % MOD;
                    }
                }
            }
        }
    }
    return dp[maxMove][startRow][startColumn];
}
```


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

int findUnsortedSubarray(vector<int>& nums) {
    vector<int> sorted_nums(nums);
    sort(sorted_nums.begin(), sorted_nums.end());
    int start = 0, end = nums.size() - 1;
    while (start < nums.size() && nums[start] == sorted_nums[start]) start++;
    while (end > start && nums[end] == sorted_nums[end]) end--;
    return end - start + 1;
}
```

```java
import java.util.Arrays;

public int findUnsortedSubarray(int[] nums) {
    int[] sortedNums = nums.clone();
    Arrays.sort(sortedNums);
    int start = 0, end = nums.length - 1;
    while (start < nums.length && nums[start] == sortedNums[start]) start++;
    while (end > start && nums[end] == sortedNums[end]) end--;
    return end - start + 1;
}
```


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

vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {
    unordered_map<int, vector<int>> children;
    for (int i = 0; i < pid.size(); i++) {
        children[ppid[i]].push_back(pid[i]);
    }

    vector<int> killed;
    function<void(int)> dfs = [&](int id) {
        killed.push_back(id);
        for (int child : children[id]) {
            dfs(child);
        }
    };
    dfs(kill);

    return killed;
}
```

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

public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
    Map<Integer, List<Integer>> children = new HashMap<>();
    for (int i = 0; i < pid.size(); i++) {
        children.computeIfAbsent(ppid.get(i), k -> new ArrayList<>()).add(pid.get(i));
    }

    List<Integer> killed = new ArrayList<>();
    dfs(kill, children, killed);
    return killed;
}

private void dfs(int id, Map<Integer, List<Integer>> children, List<Integer> killed) {
    killed.add(id);
    for (int child : children.getOrDefault(id, new ArrayList<>())) {
        dfs(child, children, killed);
    }
}
```