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

using namespace std;

bool compare(const vector<int>& p, const vector<int>& q) {
    return p[0] < q[0] || (p[0] == q[0] && p[1] < q[1]);
}

int cross_product(const vector<int>& p, const vector<int>& q, const vector<int>& r) {
    return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]);
}

vector<vector<int>> fence(vector<vector<int>>& trees) {
    sort(trees.begin(), trees.end(), compare);
    vector<vector<int>> hull;
    for (const auto& p : trees) {
        while (hull.size() >= 2 && cross_product(hull[hull.size() - 2], hull[hull.size() - 1], p) > 0) {
            hull.pop_back();
        }
        hull.push_back(p);
    }
    for (int i = trees.size() - 1; i >= 0; --i) {
        const auto& p = trees[i];
        while (hull.size() >= 2 && cross_product(hull[hull.size() - 2], hull[hull.size() - 1], p) > 0) {
            hull.pop_back();
        }
        hull.push_back(p);
    }
    return hull;
}
```

```python
def cross_product(p, q, r):
    return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])

def fence(trees):
    trees.sort(key=lambda p: (p[0], p[1]))
    hull = []
    for p in trees:
        while len(hull) >= 2 and cross_product(hull[-2], hull[-1], p) > 0:
            hull.pop()
        hull.append(p)

    for p in reversed(trees):
        while len(hull) >= 2 and cross_product(hull[-2], hull[-1], p) > 0:
            hull.pop()
        hull.append(p)

    return hull
```


```cpp
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
    set<int> dist;
    vector<vector<int>> points{p1, p2, p3, p4};

    for (int i = 0; i < 4; i++) {
        for (int j = i + 1; j < 4; j++) {
            dist.insert(pow(points[i][0] - points[j][0], 2) + pow(points[i][1] - points[j][1], 2));
        }
    }

    return dist.size() == 2 && *dist.begin() != 0;
}
```

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

```java
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
    Set<Integer> dist = new HashSet<>();
    int[][] points = {p1, p2, p3, p4};

    for (int i = 0; i < 4; i++) {
        for (int j = i + 1; j < 4; j++) {
            dist.add((points[i][0] - points[j][0]) * (points[i][0] - points[j][0]) + (points[i][1] - points[j][1]) * (points[i][1] - points[j][1]));
        }
    }

    return dist.size() == 2 && !dist.contains(0);
}
```


```java
import java.util.HashMap;

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

    int longest_sequence = 0;
    for (int key : count.keySet()) {
        if (count.containsKey(key + 1))
            longest_sequence = Math.max(longest_sequence, count.get(key) + count.get(key + 1));
    }

    return longest_sequence;
}
```

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

int findLHS(vector<int>& nums) {
    unordered_map<int, int> count;
    for (int num : nums)
        count[num]++;

    int longest_sequence = 0;
    for (auto &elem : count) {
        if (count.find(elem.first + 1) != count.end())
            longest_sequence = max(longest_sequence, elem.second + count[elem.first + 1]);
    }

    return longest_sequence;
}
```


```python
def maxCount(m: int, n: int, ops: List[List[int]]) -> int:
    for op in ops:
        m = min(m, op[0])
        n = min(n, op[1])
    return m * n
```

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

int maxCount(int m, int n, vector<vector<int>>& ops) {
    for (vector<int>& op : ops) {
        m = min(m, op[0]);
        n = min(n, op[1]);
    }
    return m * n;
}
```


```python
from typing import List

def findRestaurant(list1: List[str], list2: List[str]) -> List[str]:
    restaurantMap = {restaurant: i for i, restaurant in enumerate(list1)}

    minSum = float("inf")
    result = []
    for j, restaurant in enumerate(list2):
        if restaurant in restaurantMap:
            totalSum = j + restaurantMap[restaurant]
            if totalSum < minSum:
                result = [restaurant]
                minSum = totalSum
            elif totalSum == minSum:
                result.append(restaurant)

    return result
```

list1 = \[ "Shogun ", "Tapioca Express ", "Burger King ", "KFC "\], list2 = \[ "Piatti ", "The Grill at Torrey Pines ", "Hungry Hunter Steakhouse ", "Shogun "\]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Shogun ", "Tapioca Express"]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Piatti ", "The Grill at Torrey Pines ", "Steakhouse ", "McDonalds "]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Shogun ", "The Grill at Torrey Pines ", "Burger King ", "KFC "]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Tapioca Express ", "Burger King"]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["KFC ", "Shogun ", "Burger King"]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Shogun ", "Burger King ", "KFC"]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["KFC ", "Shogun ", "Burger King ", "Tapioca Express"]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Tapioca Express ", "Burger King ", "KFC"]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Tapioca Express"]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Piatti ", "The Grill at Torrey Pines ", "Hungry Hunter Steakhouse ", "Shogun "]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Shogun ", "Tapioca Express ", "Burger King ", "KFC"]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Shogun ", "Tapioca Express ", "KFC"]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Burger King ", "KFC"]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Burger King"]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Shogun"]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Tapioca Express ", "KFC"]

["Apple ", "Banana ", "Cherry ", "Date ", "Fig "]
["Banana ", "Cherry ", "Date ", "Elderberry ", "Fig "]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Shogun ", "Tapioca Express ", "Burger King"]

["UniqueString1 ", "UniqueString2 ", "UniqueString3 "]
["UniqueString3 ", "UniqueString4 ", "UniqueString5 "]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["KFC"]

["Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
["Shogun ", "Burger King"]

["Apple ", "Banana ", "Cherry ", "Date "]
["Banana ", "Cherry ", "Date ", "Elderberry "]

[ "Shogun ", "Tapioca Express ", "Burger King ", "KFC "]
[ "Piatti ", "The Grill at Torrey Pines ", "Hungry Hunter Steakhouse ", "Shogun "]

[Burger King ]
[Shogun ]
[Tapioca Express ]
[]
[Shogun ]
[Burger King ]
[Shogun ]
[Shogun ]
[Shogun ]
[]
[Shogun ]
[Tapioca Express ]
[Tapioca Express ]
[]
[]
[Shogun ]
[]
[Shogun ]
[]
[Tapioca Express ]
[Shogun ]
[Banana ]
[]
[Shogun ]
[Shogun ]
[UniqueString3 ]
[Shogun ]
[Tapioca Express ]
[Tapioca Express ]
[Shogun ]
[Shogun ]
[]
[]
[Banana ]

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

public List<String> findRestaurant(String[] list1, String[] list2) {
    HashMap<String, Integer> restaurantMap = new HashMap<>();
    for (int i = 0; i < list1.length; i++) {
        restaurantMap.put(list1[i], i);
    }

    int minSum = Integer.MAX_VALUE;
    List<String> result = new ArrayList<>();
    for (int j = 0; j < list2.length; j++) {
        Integer index = restaurantMap.get(list2[j]);
        if (index != null) {
            int sum = j + index;
            if (sum < minSum) {
                result.clear();
                result.add(list2[j]);
                minSum = sum;
            } else if (sum == minSum) {
                result.add(list2[j]);
            }
        }
    }
    return result;
}
```


```python
def findIntegers(n: int) -> int:
    dp = [[0, 0] for _ in range(32)]
    dp[0][0], dp[0][1] = 1, 1

    for i in range(1, 32):
        dp[i][0] = dp[i - 1][0] + dp[i - 1][1]
        dp[i][1] = dp[i - 1][0]

    ans = 0
    prev_bit = 0
    for i in range(30, -1, -1):
        if n & (1 << i):
            ans += dp[i][0]
            if prev_bit:
                break
            prev_bit = 1
        else:
            prev_bit = 0

    return ans + 1
```


```java
public boolean canPlaceFlowers(int[] flowerbed, int n) {
    int count = 0;
    for(int i = 0; i < flowerbed.length; i++) {
        if(flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
            flowerbed[i] = 1;
            count++;
        }
        if(count >= n) return true;
    }
    return count >= n;
}
```

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

```cpp
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
    int count = 0;
    for(int i = 0; i < flowerbed.size(); i++) {
        if(flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) {
            flowerbed[i] = 1;
            count++;
        }
        if(count >= n) return true;
    }
    return count >= n;
}
```


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

def tree2str(t):
    if not t:
        return ""
    if not t.left and not t.right:
        return str(t.val)
    if not t.right:
        return "{}({})".format(t.val, tree2str(t.left))
    return "{}({})({})".format(t.val, tree2str(t.left), tree2str(t.right))
```

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

class Solution {
    public String tree2str(TreeNode t) {
        if (t == null) {
            return "";
        }
        if (t.left == null && t.right == null) {
            return t.val + "";
        }
        if (t.right == null) {
            return t.val + "(" + tree2str(t.left) + ")";
        }
        return t.val + "(" + tree2str(t.left) + ")(" + tree2str(t.right) + ")";
    }
}
```


```python
from collections import defaultdict

def find_duplicate(paths):
    content_map = defaultdict(list)
    for path in paths:
        parts = path.split()
        directory = parts[0]
        for file in parts[1:]:
            start = file.index('(')
            end = file.index(')')
            content = file[start + 1:end]
            file_path = directory + '/' + file[:start]
            content_map[content].append(file_path)

    result = [file_paths for file_paths in content_map.values() if len(file_paths) > 1]
    return result
```

paths = \["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"\]

root/a 1.txt(abcd) 2.txt(abcd)
root/b 3.txt(efgh) 4.txt(efgh)

root/a 1.txt(abcd) 2.txt(efgh)
root/b 3.txt(abcd) 4.txt(efgh)
root/c 5.txt(ghij)

root/a 1.txt(abcd) 2.txt(efgh)
root/c 3.txt(abcd)
root/c/d 4.txt(efgh)
root 4.txt(efgh)

root/a/b 1.txt(abcd)
root/a/c 2.txt(efgh)
root/b/c 3.txt(abcd)
root/b/d 4.txt(efgh)

root/a 1.txt(abcd) 2.txt(efgh) 3.txt(efgh) 4.txt(efgh) 5.txt(efgh) 6.txt(efgh) 7.txt(efgh) 8.txt(efgh)

root/c 3.txt(abcd) 4.txt(efgh) 5.txt(efgh) 6.txt(efgh) 7.txt(efgh) 8.txt(efgh) 9.txt(efgh)

root 1.txt(abcd)
root/a 2.txt(abcd)
root/b 3.txt(abcd)

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

std::vector<std::vector<std::string>> findDuplicate(std::vector<std::string>& paths) {
    std::unordered_map<std::string, std::vector<std::string>> content_map;
    for (const std::string &path : paths) {
        std::istringstream iss(path);
        std::string directory;
        iss >> directory;
        std::string file;
        while (iss >> file) {
            size_t start = file.find('(');
            size_t end = file.find(')');
            std::string content = file.substr(start + 1, end - start - 1);
            std::string file_path = directory + "/" + file.substr(0, start);
            content_map[content].push_back(file_path);
        }
    }
    std::vector<std::vector<std::string>> result;
    for (const auto &entry : content_map) {
        if (entry.second.size() > 1) {
            result.push_back(entry.second);
        }
    }
    return result;
}
```


```cpp
int triangleNumber(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    int count = 0;
    for (int i = 0; i < nums.size(); ++i) {
        for (int j = i + 1; j < nums.size(); ++j) {
            for (int k = j + 1; k < nums.size(); ++k) {
                if (nums[i] + nums[j] > nums[k]) {
                    ++count;
                }
                else {
                    break;
                }
            }
        }
    }
    return count;
}
```

```java
public int triangleNumber(int[] nums) {
    Arrays.sort(nums);
    int count = 0;
    for (int i = 0; i < nums.length; ++i) {
        for (int j = i + 1; j < nums.length; ++j) {
            for (int k = j + 1; k < nums.length; ++k) {
                if (nums[i] + nums[j] > nums[k]) {
                    count++;
                }
                else {
                    break;
                }
            }
        }
    }
    return count;
}
```


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

std::string addBoldTag(std::string s, std::vector<std::string>& words) {
    int n = s.size();
    std::vector<bool> marked(n, false);
    for (const auto& word : words) {
        int pos = s.find(word, 0);
        while (pos != std::string::npos) {
            std::fill(marked.begin() + pos, marked.begin() + pos + word.size(), true);
            pos = s.find(word, pos + 1);
        }
    }
    std::string result;
    for (int i = 0; i < n; ++i) {
        if (marked[i] && (i == 0 || !marked[i - 1])) {
            result += "<b>";
        }
        result += s[i];
        if (marked[i] && (i == n - 1 || !marked[i + 1])) {
            result += "</b>";
        }
    }
    return result;
}
```

hello world goodbye world
["hello ", "world "]

hello world goodbye world goodbye world
["hello ", "world "]

hello world goodbye world goodbye world goodbye
["hello ", "world "]

hello world goodbye
["hello ", "world "]

hello world goodbye world goodbye
["hello ", "world "]

<b>hello world </b>goodbye <b>world </b>goodbye <b>world </b>goodbye

```python
def addBoldTag(s: str, words: list) -> str:
    n = len(s)
    marked = [False] * n
    for word in words:
        pos = s.find(word)
        while pos != -1:
            for i in range(pos, pos + len(word)):
                marked[i] = True
            pos = s.find(word, pos + 1)
    result = []
    i = 0
    while i < n:
        if marked[i]:
            result.append("<b>")
            while i < n and marked[i]:
                result.append(s[i])
                i += 1
            result.append("</b>")
        else:
            result.append(s[i])
            i += 1
    return "".join(result)
```


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

public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
    if (root1 == null) return root2;
    if (root2 == null) return root1;

    root1.val += root2.val;
    root1.left = mergeTrees(root1.left, root2.left);
    root1.right = mergeTrees(root1.right, root2.right);
    return root1;
}
```

```cpp
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
};

TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
    if (root1 == nullptr) return root2;
    if (root2 == nullptr) return root1;

    root1->val += root2->val;
    root1->left = mergeTrees(root1->left, root2->left);
    root1->right = mergeTrees(root1->right, root2->right);
    return root1;
}
```


```java
import java.util.HashMap;
import java.util.PriorityQueue;

public int leastInterval(char[] tasks, int n) {
    HashMap<Character, Integer> taskFreq = new HashMap<>();
    for (char task : tasks) {
        taskFreq.put(task, taskFreq.getOrDefault(task, 0) + 1);
    }

    PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
    maxHeap.addAll(taskFreq.values());

    int cycles = 0;

    while (!maxHeap.isEmpty()) {
        List<Integer> temp = new ArrayList<>();
        for (int i = 0; i < n + 1; i++) {
            if (!maxHeap.isEmpty()) {
                temp.add(maxHeap.remove());
            }
        }

        for (int freq : temp) {
            if (--freq > 0) {
                maxHeap.add(freq);
            }
        }

        cycles += maxHeap.isEmpty() ? temp.size() : n + 1;
    }

    return cycles;
}
```

```python
from collections import Counter

def least_interval(tasks, n):
    task_freq = Counter(tasks)

    max_f = max(task_freq.values())
    max_count = sum(1 for count in task_freq.values() if count == max_f)

    return max(len(tasks), (max_f - 1) * (n + 1) + max_count)
```


```java
public void addOneRowHelper(TreeNode node, int val, int depth, int currentDepth) {
    if (node == null) return;
    if (currentDepth == depth - 1) {
        TreeNode left = node.left;
        TreeNode right = node.right;
        node.left = new TreeNode(val);
        node.left.left = left;
        node.right = new TreeNode(val);
        node.right.right = right;
    } else {
        addOneRowHelper(node.left, val, depth, currentDepth + 1);
        addOneRowHelper(node.right, val, depth, currentDepth + 1);
    }
}

public TreeNode addOneRow(TreeNode root, int val, int depth) {
    if (depth == 1) {
        TreeNode newRoot = new TreeNode(val);
        newRoot.left = root;
        return newRoot;
    }
    addOneRowHelper(root, val, depth, 1);
    return root;
}
```

[1, 2, None, 3, None, 4, 4, 4, None, None, None, 5]

[1, 2, 3, 4, 5, 6, 7, 8, None, None, None, None, None, None, None, 2, 2]

```python
def add_one_row_helper(node, val, depth, current_depth):
    if not node:
        return
    if current_depth == depth - 1:
        left = node.left
        right = node.right
        node.left = TreeNode(val)
        node.left.left = left
        node.right = TreeNode(val)
        node.right.right = right
    else:
        add_one_row_helper(node.left, val, depth, current_depth + 1)
        add_one_row_helper(node.right, val, depth, current_depth + 1)

def add_one_row(root, val, depth):
    if depth == 1:
        new_root = TreeNode(val)
        new_root.left = root
        return new_root
    add_one_row_helper(root, val, depth, 1)
    return root
```


```python
def smallestFactorization(num: int) -> int:
    if num == 1:
        return 1
    result = 0
    factor = 1
    for i in range(9, 1, -1):
        while num % i == 0:
            num //= i
            result += i * factor
            factor *= 10
            if result > 2**31 - 1:
                return 0
    return result if num == 1 else 0
```

```cpp
int smallestFactorization(int num) {
    if (num == 1) return 1;
    long result = 0, factor = 1;
    for (int i = 9; i > 1; --i) {
        while (num % i == 0) {
            num /= i;
            result += i * factor;
            factor *= 10;
            if (result > INT_MAX) return 0;
        }
    }
    return num == 1 ? result : 0;
}
```


```python
def maximumProduct(nums):
    nums.sort()
    n = len(nums)
    return max(nums[0] * nums[1] * nums[-1], nums[-1] * nums[-2] * nums[-3])
```

```java
public int maximumProduct(int[] nums) {
    Arrays.sort(nums);
    int n = nums.length;
    return Math.max(nums[0] * nums[1] * nums[n-1], nums[n-1] * nums[n-2] * nums[n-3]);
}
```


```cpp
int kInversePairs(int n, int k) {
    int mod = 1e9 + 7;
    vector<vector<int>> dp(n + 1, vector<int>(k + 1, 0));
    for (int i = 1; i <= n; ++i) {
        dp[i][0] = 1;
        for (int j = 1; j <= k; ++j) {
            dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % mod;
            if (j - i >= 0) {
                dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + mod) % mod;
            }
        }
    }
    return dp[n][k];
}
```


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

public int scheduleCourse(int[][] courses) {
    Arrays.sort(courses, (a, b) -> a[1] - b[1]);

    PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
    int time = 0;

    for (int[] course : courses) {
        time += course[0];
        pq.offer(course[0]);

        if (time > course[1]) {
            time -= pq.poll();
        }
    }

    return pq.size();
}
```

```python
import heapq

def scheduleCourse(courses):
    courses.sort(key=lambda x: x[1])
    curr_time, duration_sum = 0, []

    for duration, deadline in courses:
        curr_time += duration
        heapq.heappush(duration_sum, -duration)

        if curr_time > deadline:
            curr_time += heapq.heappop(duration_sum)

    return len(duration_sum)
```


```java
class Solution {
    public boolean judgeSquareSum(int c) {
        for (int a = 0; a <= Math.sqrt(c); ++a) {
            int b = (int) Math.sqrt(c - a * a);
            if (a * a + b * b == c) {
                return true;
            }
        }
        return false;
    }
}
```

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

```python
def judge_square_sum(c):
    for a in range(int(c ** 0.5) + 1):
        b = int((c - a * a) ** 0.5)
        if a * a + b * b == c:
            return True
    return False
```


```python
def findDerangement(n: int) -> int:
    MOD = 10**9 + 7
    dp = [0] * (n + 1)
    dp[2] = 1
    for i in range(3, n + 1):
        dp[i] = (i - 1) * (dp[i - 1] + dp[i - 2]) % MOD
    return dp[n]
```

```java
public int findDerangement(int n) {
    final int MOD = 1000000007;
    long[] dp = new long[n + 1];
    dp[2] = 1;
    for (int i = 3; i <= n; ++i) {
        dp[i] = (i - 1) * (dp[i - 1] + dp[i - 2]) % MOD;
    }
    return (int)dp[n];
}
```


```python
def exclusiveTime(n, logs):
    res = [0] * n
    stack = []
    prev_time = 0

    for log in logs:
        parts = log.split(':')
        id = int(parts[0])
        type = parts[1]
        time = int(parts[2])

        if type == "start":
            if stack:
                res[stack[-1]] += time - prev_time
            stack.append(id)
            prev_time = time
        else:
            res[stack.pop()] += time - prev_time + 1
            prev_time = time + 1

    return res
```

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

std::vector<int> exclusiveTime(int n, std::vector<std::string>& logs) {
    std::vector<int> res(n, 0);
    std::stack<int> s;
    int prev_time = 0;

    for (const auto& log : logs) {
        auto colon1 = log.find(':');
        auto colon2 = log.rfind(':');

        int id = std::stoi(log.substr(0, colon1));
        std::string type = log.substr(colon1 + 1, colon2 - colon1 - 1);
        int time = std::stoi(log.substr(colon2 + 1));

        if (type == "start") {
            if (!s.empty()) {
                res[s.top()] += time - prev_time;
            }
            s.push(id);
            prev_time = time;
        } else {
            res[s.top()] += time - prev_time + 1;
            s.pop();
            prev_time = time + 1;
        }
    }

    return res;
}
```


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

def averageOfLevels(root: TreeNode):
    result = []
    queue = [root]

    while queue:
        sum_ = 0
        count = 0
        temp = []
        while queue:
            node = queue.pop(0)
            sum_ += node.val
            count += 1
            if node.left: temp.append(node.left)
            if node.right: temp.append(node.right)
        queue = temp
        result.append(sum_ / count)

    return result
```

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

using namespace std;

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

vector<double> averageOfLevels(TreeNode* root) {
    vector<double> result;
    queue<TreeNode*> q;
    q.push(root);

    while (!q.empty()) {
        long long sum = 0;
        int count = 0;
        queue<TreeNode*> temp;
        while (!q.empty()) {
            TreeNode* n = q.front();
            q.pop();
            sum += n->val;
            count++;
            if (n->left) temp.push(n->left);
            if (n->right) temp.push(n->right);
        }
        q = temp;
        result.push_back(static_cast<double>(sum) / count);
    }

    return result;
}
```


```python
from typing import List

def shoppingOffers(price: List[int], special: List[List[int]], needs: List[int]) -> int:
    def helper(index):
        if index == len(special):
            return sum(needs[i] * price[i] for i in range(len(needs)))

        no_offer = helper(index + 1)
        can_apply_offer = True
        for i in range(len(needs)):
            needs[i] -= special[index][i]
            if needs[i] < 0:
                can_apply_offer = False

        with_offer = float('inf')
        if can_apply_offer:
            offer_cost = special[index][-1] + helper(index)
            with_offer = min(no_offer, offer_cost)

        for i in range(len(needs)):
            needs[i] += special[index][i]

        return with_offer if can_apply_offer else no_offer

    return helper(0)
```

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

int shoppingOffersHelper(vector<int>& price, vector<vector<int>>& special, vector<int>& needs, int index) {
    if (index == special.size()) {
        int sum = 0;
        for (int i = 0; i < needs.size(); ++i) {
            sum += price[i] * needs[i];
        }
        return sum;
    }

    int no_offer = shoppingOffersHelper(price, special, needs, index + 1);
    bool can_apply_offer = true;
    for (int i = 0; i < needs.size(); ++i) {
        needs[i] -= special[index][i];
        if (needs[i] < 0) can_apply_offer = false;
    }

    int with_offer = INT_MAX;
    if (can_apply_offer) {
        int offer_cost = special[index][needs.size()] + shoppingOffersHelper(price, special, needs, index);
        with_offer = min(no_offer, offer_cost);
    }

    for (int i = 0; i < needs.size(); ++i) {
        needs[i] += special[index][i];
    }

    return can_apply_offer ? with_offer : no_offer;
}

int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
    return shoppingOffersHelper(price, special, needs, 0);
}
```


```java
public double findMaxAverage(int[] nums, int k) {
    int n = nums.length;
    double sum = 0;
    for (int i = 0; i < k; i++) {
        sum += nums[i];
    }
    double max_avg = sum / k;
    for (int i = k; i < n; i++) {
        sum = sum - nums[i - k] + nums[i];
        max_avg = Math.max(max_avg, sum / k);
    }
    return max_avg;
}
```

```python
def findMaxAverage(nums, k):
    n = len(nums)
    sum_ = sum(nums[:k])
    max_avg = sum_ / k
    for i in range(k, n):
        sum_ = sum_ - nums[i - k] + nums[i]
        max_avg = max(max_avg, sum_ / k)
    return max_avg
```


```java
public double findMaxAverage(int[] nums, int k) {
    long sum = 0;
    for(int i = 0; i < k; i++) {
        sum += nums[i];
    }

    double max_avg = (double) sum / k;

    for(int i = k; i < nums.length; i++) {
        sum += nums[i] - nums[i - k];
        max_avg = Math.max(max_avg, (double) sum / k);
    }

    return max_avg;
}
```

```python
def findMaxAverage(nums, k):
    total = sum(nums[:k])
    max_avg = total / k
    for i in range(k, len(nums)):
        total += nums[i] - nums[i - k]
        max_avg = max(max_avg, total / k)
    return max_avg
```


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

vector<int> findErrorNums(vector<int>& nums) {
    vector<int> result;
    for (int i = 0; i < nums.size(); i++) {
        int index = abs(nums[i]) - 1;
        if (nums[index] > 0) {
            nums[index] = -nums[index];
        } else {
            result.push_back(index + 1);
        }
    }
    for (int i = 0; i < nums.size(); i++) {
        if (nums[i] > 0) {
            result.push_back(i + 1);
            break;
        }
    }
    return result;
}
```

```python
def findErrorNums(nums):
    result = []
    for num in nums:
        index = abs(num) - 1
        if nums[index] > 0:
            nums[index] = -nums[index]
        else:
            result.append(index + 1)
    for i, num in enumerate(nums):
        if num > 0:
            result.append(i + 1)
            break
    return result
```


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

int findLongestChain(std::vector<std::vector<int>>& pairs) {
    std::sort(pairs.begin(), pairs.end(), [](const std::vector<int>& a, const std::vector<int>& b) {
        return a[1] < b[1];
    });

    int max_chain_length = 0, last_right = INT_MIN;
    for (const auto& pair : pairs) {
        if (pair[0] > last_right) {
            last_right = pair[1];
            max_chain_length++;
        }
    }

    return max_chain_length;
}
```

```python
def findLongestChain(pairs):
    pairs.sort(key=lambda x: x[1])

    max_chain_length = 0
    last_right = float('-inf')
    for pair in pairs:
        if pair[0] > last_right:
            last_right = pair[1]
            max_chain_length += 1

    return max_chain_length
```


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

public String replaceWords(List<String> dict, String sentence) {
    Set<String> roots = new HashSet<>(dict);
    String[] words = sentence.split(" ");
    StringBuilder result = new StringBuilder();

    for (String word : words) {
        String prefix = "";
        for (int i = 1; i <= word.length(); ++i) {
            prefix = word.substring(0, i);
            if (roots.contains(prefix)) {
                break;
            }
        }
        result.append(prefix).append(" ");
    }

    return result.toString().trim();
}
```

dictionary = \[ "cat ", "bat ", "rat "\], sentence =  "the cattle was rattled by the battery "

["test", "testing", "tested", "tester"]
,

["run", "runner", "running", "ran", "runny"]
,

["play", "player", "played", "playful"]
,

[ "cat ", "bat ", "rat "]
the cattle was rattled by the battery

,
,
,
,
,
the cattle was rattled by the battery
,
,
,

```python
def replaceWords(dict, sentence):
    roots = set(dict)
    words = sentence.split()
    result = []

    for word in words:
        prefix = ''
        for i in range(1, len(word) + 1):
            prefix = word[:i]
            if prefix in roots:
                break
        result.append(prefix)

    return ' '.join(result)
```


```python
from collections import deque

def predict_party_victory(senate: str) -> str:
    radiant = deque()
    dire = deque()
    n = len(senate)

    for i, s in enumerate(senate):
        if s == 'R':
            radiant.append(i)
        else:
            dire.append(i)

    while radiant and dire:
        r = radiant.popleft()
        d = dire.popleft()

        if r < d:
            radiant.append(r + n)
        else:
            dire.append(d + n)

    return "Dire" if not radiant else "Radiant"
```

RRDDRR DDDDD DDRRDDDDDDRRD DDRRDDDDDDDDRR RDDDDDDDDDDDDRRDD RDDDDDDDDDDRR DR DDRRDDRRD RDD RRDDRRD RRD DDRRDD DDRRDDDDRRDD RRRRR RDDRRRDDD DDRRDDDDDDRR RD RDDRR RRDDRRDD RRDD RDDRRDD RDDDDDDDDDDRRD DDRDDR RDDDDRRD RDDRRRDD RDDDDRR DDRRDDDDRR RD RDDDDDDRR DDRRDDRRDD RDDDDDDDDDDDDRRD DDRRDDDDDDDDRRD DDRRRDD DRRDR DDRRDDRR RDDDDDDDDDDRRDD RDDD RDDRRD RRDRRD DDRRRDDD RDDDDDDRRDD DDRRDDDDDDRRDD DDRRD RDDRD DDRRDDDDDDDDRRDD RDDDDDDRRD RDDDDDDDDDDDDRR RD DDRR DDRRDDDDRRD RDDDDRRDD

Dire Dire Dire Dire Dire Dire Dire Radiant Dire Radiant Dire Dire Dire Dire Dire Radiant Dire Dire Dire Radiant Dire Dire Dire Radiant Dire Radiant Dire Dire Dire Dire Radiant Dire Dire Dire Radiant Dire Radiant Radiant Dire Dire Radiant Radiant Radiant Dire Radiant Dire Dire Dire Dire Dire Dire

```java
import java.util.Queue;
import java.util.LinkedList;

public String predictPartyVictory(String senate) {
    Queue<Integer> radiant = new LinkedList<>();
    Queue<Integer> dire = new LinkedList<>();
    int n = senate.length();

    for (int i = 0; i < n; i++) {
        if (senate.charAt(i) == 'R')
            radiant.add(i);
        else
            dire.add(i);
    }

    while (!radiant.isEmpty() && !dire.isEmpty()) {
        int r = radiant.poll();
        int d = dire.poll();

        if (r < d)
            radiant.add(r + n);
        else
            dire.add(d + n);
    }

    return radiant.isEmpty() ? "Dire" : "Radiant";
}
```


```python
def min_steps(n):
    result = 0
    i = 2
    while i <= n:
        while n % i == 0:
            result += i
            n //= i
        i += 1
    return result
```

```cpp
int minSteps(int n) {
    int result = 0;
    for (int i = 2; i <= n; ++i) {
        while (n % i == 0) {
            result += i;
            n /= i;
        }
    }
    return result;
}
```


```cpp
int maxA(int n) {
    vector<int> dp(n + 1);
    for(int i = 1; i <= n; ++i) {
        dp[i] = i;
        for(int j = 1; j <= i - 3; ++j)
            dp[i] = max(dp[i], dp[j] * (i - j - 1));
    }
    return dp[n];
}
```

```python
def maxA(n: int) -> int:
    dp = [0] * (n + 1)
    for i in range(1, n + 1):
        dp[i] = i
        for j in range(1, i - 2):
            dp[i] = max(dp[i], dp[j] * (i - j - 1))
    return dp[n]
```


```cpp
bool findTarget(TreeNode* root, int k) {
    unordered_set<int> nodes;
    return findNode(root, k, nodes);
}

bool findNode(TreeNode* root, int k, unordered_set<int>& nodes) {
    if (!root) return false;
    if (nodes.count(k - root->val)) return true;
    nodes.insert(root->val);
    return findNode(root->left, k, nodes) || findNode(root->right, k, nodes);
}
```

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

```python
def findTarget(root, k):
    nodes = set()
    return findNode(root, k, nodes)

def findNode(root, k, nodes):
    if not root:
        return False
    if k - root.val in nodes:
        return True
    nodes.add(root.val)
    return findNode(root.left, k, nodes) or findNode(root.right, k, nodes)
```


```java
public boolean judgeCircle(String moves) {
    int x = 0, y = 0;
    for(char move : moves.toCharArray()) {
        if(move == 'U') y++;
        else if(move == 'D') y--;
        else if(move == 'R') x++;
        else if(move == 'L') x--;
    }
    return x == 0 && y == 0;
}
```

LLUUDD UD DDDDDDDDD RRUDD RRRRRRRRR UUUUUUUUU LLLLLLLLL LDRRLU UD

True False False False True False False False True

```python
def judgeCircle(moves: str) -> bool:
    x, y = 0, 0
    for move in moves:
        if move == 'U': y += 1
        elif move == 'D': y -= 1
        elif move == 'R': x += 1
        elif move == 'L': x -= 1
    return x == 0 and y == 0
```


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

public List<Integer> findClosestElements(int[] arr, int k, int x) {
    int left = 0;
    int right = arr.length - k;

    while (left < right) {
        int mid = left + (right - left) / 2;
        if (x - arr[mid] > arr[mid + k] - x) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }

    List<Integer> result = new ArrayList<>();
    for (int i = left; i < left + k; i++) {
        result.add(arr[i]);
    }

    return result;
}
```

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

std::vector<int> findClosestElements(std::vector<int>& arr, int k, int x) {
    int left = 0;
    int right = arr.size() - k;

    while (left < right) {
        int mid = left + (right - left) / 2;
        if (x - arr[mid] > arr[mid + k] - x) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }

    return std::vector<int>(arr.begin() + left, arr.begin() + left + k);
}
```


```java
public boolean canSplit(int[] nums) {
    int[] freq = new int[20001], needed = new int[20001];
    for (int n : nums)
        freq[n]++;
    for (int n : nums) {
        if (freq[n] == 0) continue;
        if (needed[n - 1] == 0) {
            if (freq[n + 1] > 0 && freq[n + 2] > 0) {
                freq[n]--; freq[n + 1]--; freq[n + 2]--;
                needed[n + 2]++;
            } else return false;
        } else {
            freq[n]--; needed[n - 1]--;
            needed[n]++;
        }
    }
    return true;
}
```

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

```python
def can_split(nums):
    freq = [0] * 20001
    needed = [0] * 20001
    for n in nums:
        freq[n] += 1
    for n in nums:
        if not freq[n]: continue
        if not needed[n - 1]:
            if freq[n + 1] and freq[n + 2]:
                freq[n] -= 1; freq[n + 1] -= 1; freq[n + 2] -= 1;
                needed[n + 2] += 1
            else: return False
        else:
            freq[n] -= 1; needed[n - 1] -= 1;
            needed[n] += 1
    return True
```


```python
def newInteger(n):
    result = 0
    base = 1
    while n:
        result += n % 9 * base
        n //= 9
        base *= 10
    return result
```

```cpp
int newInteger(int n) {
    int result = 0, base = 1;
    while (n) {
        result += n % 9 * base;
        n /= 9;
        base *= 10;
    }
    return result;
}
```


```java
public int[][] imageSmoother(int[][] img) {
    int m = img.length, n = img[0].length;
    int[][] result = new int[m][n];

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            int count = 0, sum = 0;
            for (int x = i - 1; x <= i + 1; x++) {
                for (int y = j - 1; y <= j + 1; y++) {
                    if (x >= 0 && x < m && y >= 0 && y < n) {
                        sum += img[x][y];
                        count++;
                    }
                }
            }
            result[i][j] = sum / count;
        }
    }

    return result;
}
```

```python
def imageSmoother(img):
    m, n = len(img), len(img[0])
    result = [[0] * n for _ in range(m)]

    for i in range(m):
        for j in range(n):
            count, total = 0, 0
            for x in range(i - 1, i + 2):
                for y in range(j - 1, j + 2):
                    if 0 <= x < m and 0 <= y < n:
                        total += img[x][y]
                        count += 1
            result[i][j] = total // count

    return result
```


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

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

class Solution {
    public boolean checkEqualTree(TreeNode root) {
        Set<Integer> seen = new HashSet<>();
        int total = sum(root, seen);
        if (total % 2 == 0) {
            seen.remove(total);
            return seen.contains(total / 2);
        }
        return false;
    }

    private int sum(TreeNode node, Set<Integer> seen) {
        if (node == null) return 0;
        int s = node.val + sum(node.left, seen) + sum(node.right, seen);
        seen.add(s);
        return s;
    }
}
```

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

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

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

class Solution {
public:
    bool checkEqualTree(TreeNode* root) {
        unordered_set<int> seen;
        int total = sum(root, seen);
        if(total % 2 == 0) {
            seen.erase(total);
            return seen.count(total / 2);
        }
        return false;
    }
    int sum(TreeNode* node, unordered_set<int>& seen) {
        if (!node) return 0;
        int s = node->val + sum(node->left, seen) + sum(node->right, seen);
        seen.insert(s);
        return s;
    }
};
```


```python
def strange_printer(s: str) -> int:
    n = len(s)
    if n == 0: return 0
    dp = [[0] * n for _ in range(n)]
    for i in range(n):
        dp[i][i] = 1
    for len in range(1, n):
        for i in range(n - len):
            j = i + len
            dp[i][j] = dp[i+1][j] + 1
            for k in range(i + 1, j + 1):
                if s[i] == s[k]:
                    dp[i][j] = min(dp[i][j], dp[i+1][k-1] + dp[k][j])
    return dp[0][n-1]
```

aabccccc aaabbb aabccccccccc a aabccca aabbbc abbcccba abbaaa abbca abbccccb aaaa abbc abbccccccb aaaccc aabcccc aabbc abbcaa abcdeabcdeabcde abbcccca aabccb aabccccc abbcccc aaabbb aabcccccc abbcccb aabcca abcde abbcccaa abbccc aabccc aaaabbbbcccc abbcb aabccccccc abbcccccccc aabcc aaabbbccc abbccccca aaabbb abbcc aabccccca aabccccb

```java
int strangePrinter(String s) {
    int n = s.length();
    if(n == 0) return 0;
    int[][] dp = new int[n][n];
    for(int i = 0; i < n; i++) dp[i][i] = 1;
    for(int len = 1; len < n; len++) {
        for(int i = 0; i < n - len; i++) {
            int j = i + len;
            dp[i][j] = dp[i+1][j] + 1;
            for(int k = i + 1; k <= j; k++) {
                if(s.charAt(i) == s.charAt(k)) {
                    dp[i][j] = Math.min(dp[i][j], dp[i+1][k-1] + dp[k][j]);
                }
            }
        }
    }
    return dp[0][n-1];
}
```


```java
public boolean checkPossibility(int[] nums) {
    int cnt = 0;
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] < nums[i - 1]) {
            cnt++;
            if (i == 1 || nums[i] >= nums[i - 2]) {
                nums[i-1] = nums[i];
            } else {
                nums[i] = nums[i - 1];
            }
            if (cnt > 1) return false;
        }
    }
    return true;
}
```

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

```python
def checkPossibility(nums):
    cnt = 0
    for i in range(1, len(nums)):
        if nums[i] < nums[i - 1]:
            cnt += 1
            if i == 1 or nums[i] >= nums[i - 2]:
                nums[i-1] = nums[i]
            else:
                nums[i] = nums[i - 1]
            if cnt > 1:
                return False
    return True
```


```java
import java.util.ArrayList;

class Solution {
    public List<Integer> constructArray(int n, int k) {
        ArrayList<Integer> answer = new ArrayList<>(n);
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                answer.add(i / 2 + 1);
            } else {
                answer.add(n - (i - 1) / 2);
                k--;
            }
        }
        if (k > 0) {
            for (int i = n - 2; i >= 0 && k > 0; i--) {
                answer.set(i, answer.get(i + 1) - answer.get(i));
                k--;
            }
        }
        return answer;
    }
}
```


```python
def findKthNumber(m, n, k):
    low, high = 1, m * n
    while low < high:
        mid = low + (high - low) // 2
        count = 0
        for i in range(1, m+1):
            count += min(mid // i, n)
        if count < k:
            low = mid + 1
        else:
            high = mid
    return low
```

```java
public int findKthNumber(int m, int n, int k) {
    int low = 1, high = m * n;
    while (low < high) {
        int mid = low + (high - low) / 2;
        int count = 0;
        for (int i = 1; i <= m; i++) {
            count += Math.min(mid / i, n);
        }
        if (count < k) {
            low = mid + 1;
        } else {
            high = mid;
        }
    }
    return low;
}
```


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

public TreeNode trimBST(TreeNode root, int low, int high) {
    if (root == null) return null;

    if (root.val < low) {
        return trimBST(root.right, low, high);
    } else if (root.val > high) {
        return trimBST(root.left, low, high);
    } else {
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
    }

    return root;
}
```

[1, None, 2, None, 3, None, 4, None, 5, None, 6, None, 7, None, 8]
2
7

[1, None, 2, None, 3, None, 4, None, 5, None, 6, None, 7]
2
6

[1, None, 2, None, 3, None, 4, None, 5, None, 6]
2
5

[1, None, 2, None, 3, None, 4, None, 5, None, 6, None, 7]
1
7

[1, None, 2, None, 3, None, 4, None, 5, None, 6]
1
6

[2, None, 3, None, 4, None, 5, None, 6, None, 7]

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

def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
    if not root:
        return None

    if root.val < low:
        return self.trimBST(root.right, low, high)
    elif root.val > high:
        return self.trimBST(root.left, low, high)
    else:
        root.left = self.trimBST(root.left, low, high)
        root.right = self.trimBST(root.right, low, high)

    return root
```


```cpp
int maximumSwap(int num) {
    string num_str = to_string(num);
    vector<int> last(10, 0);

    for (int i = 0; i < num_str.size(); i++) {
        last[num_str[i] - '0'] = i;
    }

    for (int i = 0; i < num_str.size(); i++) {
        for (int d = 9; d > num_str[i] - '0'; d--) {
            if (last[d] > i) {
                swap(num_str[i], num_str[last[d]]);
                return stoi(num_str);
            }
        }
    }

    return num;
}
```

```python
def maximumSwap(num):
    num_str = list(str(num))
    last = {int(v): i for i, v in enumerate(num_str)}

    for i, v in enumerate(num_str):
        for d in range(9, int(v), -1):
            if last.get(d, -1) > i:
                num_str[i], num_str[last[d]] = num_str[last[d]], num_str[i]
                return int("".join(num_str))

    return num
```


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

public int findSecondMinimumValue(TreeNode root) {
    return findSecondMinimumValue(root, -1);
}

private int findSecondMinimumValue(TreeNode root, int current) {
    if (root == null) return current;
    if (current == -1 || root.val < current) current = root.val;
    if (root.left != null && root.right != null) {
        if (root.val == root.left.val) {
            current = findSecondMinimumValue(root.left, current);
            if (root.val != root.right.val)
                current = (current == -1) ? root.right.val : Math.min(current, root.right.val);
        } else {
            current = findSecondMinimumValue(root.right, current);
            if (root.val != root.left.val)
                current = (current == -1) ? root.left.val : Math.min(current, root.left.val);
        }
    }
    return current;
}
```

[1, None, 2, None, 3, None, 4, None, 5, None, 6, None, 7, None, 8, None, 9, None, 10, None, 11, None, 12]

[1, None, 2, None, 3, None, 4, None, 5, None, 6, None, 7, None, 8, None, 9, None, 10, None, 11]

[1, 2, 3, None, None, 4, None, None, 5, 6, 7, None, None, 8, None, None, 9, 10, None, None, 11]

```cpp
#include <algorithm>

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
};

int findSecondMinimumValue(TreeNode* root, int current = -1) {
    if (!root) return current;
    if (current == -1 || root->val < current) current = root->val;
    if (root->left && root->right) {
        if (root->val == root->left->val) {
            current = findSecondMinimumValue(root->left, current);
            if (root->val != root->right->val)
                current = (current == -1) ? root->right->val : std::min(current, root->right->val);
        } else {
            current = findSecondMinimumValue(root->right, current);
            if (root->val != root->left->val)
                current = (current == -1) ? root->left->val : std::min(current, root->left->val);
        }
    }
    return current;
}
```


```python
def num_light_configuration(n, presses):
    dp = [[0] * (presses + 1) for _ in range(n+1)]
    dp[0][0] = 1

    for i in range(n + 1):
        for j in range(1, presses + 1):
            dp[i][j] = dp[i][j - 1] * (i + 1) + (dp[i - 1][j - 1] if i > 0 else 0)

    return dp[n][presses]
```

```cpp
#include <vector>

int numLightConfiguration(int n, int presses) {
    std::vector<std::vector<int>> dp(n + 1, std::vector<int>(presses + 1, 0));
    dp[0][0] = 1;

    for (int i = 0; i <= n; ++i) {
        for (int j = 1; j <= presses; ++j) {
            dp[i][j] = dp[i][j - 1] * (i + 1) + (i > 0 ? dp[i - 1][j - 1] : 0);
        }
    }

    return dp[n][presses];
}
```


```java
public int findNumberOfLIS(int[] nums) {
    int n = nums.length, maxLength = 0, ans = 0;
    int[] length = new int[n];
    int[] count = new int[n];

    for (int i = 0; i < n; ++i) {
        length[i] = count[i] = 1;
        for (int j = 0; j < i; ++j) {
            if (nums[i] > nums[j]) {
                if (length[i] == length[j] + 1) {
                    count[i] += count[j];
                } else if (length[i] < length[j] + 1) {
                    length[i] = length[j] + 1;
                    count[i] = count[j];
                }
            }
        }
        if (maxLength == length[i]) {
            ans += count[i];
        } else if (maxLength < length[i]) {
            maxLength = length[i];
            ans = count[i];
        }
    }

    return ans;
}
```

```cpp
#include <vector>

int findNumberOfLIS(std::vector<int>& nums) {
    int n = nums.size(), maxLength = 0, ans = 0;
    std::vector<int> length(n, 0), count(n, 0);

    for (int i = 0; i < n; ++i) {
        length[i] = count[i] = 1;
        for (int j = 0; j < i; ++j) {
            if (nums[i] > nums[j]) {
                if (length[i] == length[j] + 1) {
                    count[i] += count[j];
                } else if (length[i] < length[j] + 1) {
                    length[i] = length[j] + 1;
                    count[i] = count[j];
                }
            }
        }
        if (maxLength == length[i]) {
            ans += count[i];
        } else if (maxLength < length[i]) {
            maxLength = length[i];
            ans = count[i];
        }
    }

    return ans;
}
```


```python
def findLengthOfLCIS(nums):
    if not nums:
        return 0
    result, current = 1, 1
    for i in range(1, len(nums)):
        current = current + 1 if nums[i] > nums[i - 1] else 1
        result = max(result, current)
    return result
```

```cpp
int findLengthOfLCIS(vector<int>& nums) {
    if (nums.empty()) return 0;
    int result = 1, current = 1;
    for (int i = 1; i < nums.size(); ++i) {
        current = nums[i] > nums[i - 1] ? current + 1 : 1;
        result = max(result, current);
    }
    return result;
}
```


```python
from itertools import permutations

def helper(cards, target=24):
    if len(cards) == 1:
        return abs(cards[0] - target) < 1e-6

    for i in range(len(cards)):
        for j in range(i + 1, len(cards)):
            a, b = cards[i], cards[j]
            rest = [cards[k] for k in range(len(cards)) if k != i and k != j]
            for e in a + b, a - b, a * b, a / b:
                if helper(rest + [e]):
                    return True
    return False

def canGet24(cards):
    return helper(cards)
```

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

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

bool helper(std::vector<double>& cards) {
    if (cards.size() == 1) {
        return std::abs(cards[0] - 24) < 1e-6;
    }

    for (int i = 0; i < cards.size(); ++i) {
        for (int j = i + 1; j < cards.size(); ++j) {
            double a = cards[i], b = cards[j];
            std::vector<double> next = {a + b, a - b, a * b, a / b};

            cards.erase(cards.begin() + j);
            cards.erase(cards.begin() + i);

            for (auto& e : next) {
                cards.push_back(e);
                if (helper(cards)) {
                    return true;
                }
                cards.pop_back();
            }

            cards.insert(cards.begin() + i, a);
            cards.insert(cards.begin() + j, b);
        }
    }
    return false;
}

bool canGet24(std::vector<int>& cards) {
    std::vector<double> doubleCards(cards.begin(), cards.end());
    return helper(doubleCards);
}
```


```python
def kEmptySlots(bulbs, k):
    days = [0] * len(bulbs)
    for i, bulb in enumerate(bulbs):
        days[bulb - 1] = i

    ans = float('inf')
    left = 0
    right = k + 1
    while right < len(days):
        i = left + 1
        for i in range(left + 1, right):
            if days[i] < days[left] or days[i] < days[right]:
                left = i
                break
        else:
            ans = min(ans, max(days[left], days[right]))
            left += 1
            right += 1

    return -1 if ans == float('inf') else ans + 1
```

```java
public int kEmptySlots(int[] bulbs, int k) {
    int[] days = new int[bulbs.length];
    for(int i = 0; i < bulbs.length; i++) {
        days[bulbs[i] - 1] = i;
    }

    int ans = Integer.MAX_VALUE;
    int left = 0;
    int right = k + 1;
    while (right < days.length) {
        int i = left + 1;
        for (; i < right; i++) {
            if (days[i] < days[left] || days[i] < days[right]) {
                left = i;
                break;
            }
        }
        if (i == right) {
            ans = Math.min(ans, Math.max(days[left], days[right]));
            left++;
            right++;
        }
    }

    return ans == Integer.MAX_VALUE ? -1 : ans + 1;
}
```


```python
def findRedundantDirectedConnection(edges):
    parent = [0] * (len(edges) + 1)
    candidateA = candidateB = None

    for u, v in edges:
        if parent[v] > 0:
            candidateA = [parent[v], v]
            candidateB = [u, v]
        else:
            parent[v] = u

    for i in range(1, len(edges) + 1):
        cycle = i
        steps = len(edges)
        while parent[cycle] != 0 and steps > 0:
            cycle = parent[cycle]
            steps -= 1
        if steps == 0:
            if not candidateA:
                return [parent[i], i]
            else:
                return candidateA

    return candidateB
```

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

vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {
    vector<int> parent(edges.size() + 1, 0);
    vector<int> candidateA, candidateB;

    for (const auto& edge : edges) {
        int u = edge[0], v = edge[1];
        if (parent[v] > 0) {
            candidateA = {parent[v], v};
            candidateB = edge;
        } else {
            parent[v] = u;
        }
    }

    for (int i = 1; i <= edges.size(); ++i) {
        int cycle = i, steps = edges.size();
        while (parent[cycle] != 0 && steps-- > 0) {
            cycle = parent[cycle];
        }
        if (steps == -1) {
            if (candidateA.empty()) return {parent[i], i};
            else return candidateA;
        }
    }

    return candidateB;
}
```


```cpp
int findUnivaluePath(TreeNode* node, int& maxLen) {
    if (!node) return 0;
    int left = findUnivaluePath(node->left, maxLen);
    int right = findUnivaluePath(node->right, maxLen);
    left = (node->left && node->left->val == node->val) ? left + 1 : 0;
    right = (node->right && node->right->val == node->val) ? right + 1 : 0;
    maxLen = max(maxLen, left + right);
    return max(left, right);
}

int longestUnivaluePath(TreeNode* root) {
    int maxLen = 0;
    findUnivaluePath(root, maxLen);
    return maxLen;
}
```

```python
def longestUnivaluePath(root):
    def findUnivaluePath(node):
        if not node:
            return 0
        left = findUnivaluePath(node.left)
        right = findUnivaluePath(node.right)
        left = left + 1 if node.left and node.left.val == node.val else 0
        right = right + 1 if node.right and node.right.val == node.val else 0
        maxLen[0] = max(maxLen[0], left + right)
        return max(left, right)

    maxLen = [0]
    findUnivaluePath(root)
    return maxLen[0]
```


```python
def knightProbability(self, n: int, k: int, row: int, column: int) -> float:
    memo = [[[-1.0 for _ in range(k + 1)] for _ in range(n)] for _ in range(n)]
    return self.helper(n, k, row, column, memo)

def helper(self, n, k, row, column, memo):
    if row < 0 or row >= n or column < 0 or column >= n:
        return 0.0
    if k == 0:
        return 1.0
    if memo[row][column][k] >= 0:
        return memo[row][column][k]

    result = 0.0
    moves = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]
    for move in moves:
        result += self.helper(n, k - 1, row + move[0], column + move[1], memo) / 8

    memo[row][column][k] = result
    return result
```

```java
public double knightProbability(int n, int k, int row, int column) {
    double[][][] memo = new double[n][n][k + 1];
    for (double[][] m : memo)
        for (double[] l : m)
            Arrays.fill(l, -1.0);
    return helper(n, k, row, column, memo);
}

double helper(int n, int k, int row, int column, double[][][] memo) {
    if (row < 0 || row >= n || column < 0 || column >= n) return 0.0;
    if (k == 0) return 1.0;
    if (memo[row][column][k] >= 0) return memo[row][column][k];

    double result = 0.0;
    int[][] moves = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}};
    for (int i = 0; i < 8; ++i)
        result += helper(n, k - 1, row + moves[i][0], column + moves[i][1], memo) / 8;

    memo[row][column][k] = result;
    return result;
}
```


```java
import java.util.Arrays;

public int[] max_sum_of_three_subarrays(int[] nums, int k) {
    int n = nums.length;
    int[] sums = new int[n - k + 1];
    int[] left = new int[n], right = new int[n], ans = new int[3];
    int acc_sum = 0;

    for (int i = 0; i < n; ++i) {
        acc_sum += nums[i];
        if (i >= k) {
            acc_sum -= nums[i - k];
        }
        if (i >= k - 1) {
            sums[i - k + 1] = acc_sum;
        }
    }

    left[0] = 0;
    right[n - k] = n - k;

    for (int i = 1; i < n - k + 1; ++i) {
        left[i] = sums[i] > sums[left[i - 1]] ? i : left[i - 1];
    }

    for (int i = n - k - 1; i >= 0; --i) {
        right[i] = sums[i] >= sums[right[i + 1]] ? i : right[i + 1];
    }

    int max_sum = 0;

    for (int i = k; i < n - 2 * k + 1; ++i) {
        int left_idx = left[i - k], right_idx = right[i + k], total_sum = sums[left_idx] + sums[i] + sums[right_idx];
        if (total_sum > max_sum) {
            max_sum = total_sum;
            ans = new int[] {left_idx, i, right_idx};
        }
    }

    return ans;
}
```

```python
def max_sum_of_three_subarrays(nums, k):
    n = len(nums)
    sums = [0] * (n - k + 1)
    left, right = [0] * n, [0] * n

    acc_sum = 0
    for i in range(n):
        acc_sum += nums[i]
        if i >= k:
            acc_sum -= nums[i - k]
        if i >= k - 1:
            sums[i - k + 1] = acc_sum

    left[0] = 0
    right[n - k] = n - k
    for i in range(1, n - k + 1):
        left[i] = i if sums[i] > sums[left[i - 1]] else left[i - 1]

    for i in range(n - k - 1, -1, -1):
        right[i] = i if sums[i] >= sums[right[i + 1]] else right[i + 1]

    max_sum, ans = 0, [0] * 3
    for i in range(k, n - 2 * k + 1):
        left_idx, right_idx = left[i - k], right[i + k]
        total_sum = sums[left_idx] + sums[i] + sums[right_idx]
        if total_sum > max_sum:
            max_sum = total_sum
            ans = [left_idx, i, right_idx]

    return ans
```


```java
import java.util.*;

public class Solution {
    public List<String> kFrequentWords(String[] words, int k) {
        Map<String, Integer> wordCount = new HashMap<>();
        for (String word : words) {
            wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
        }

        PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(
                (a, b) -> a.getValue() == b.getValue()
                        ? a.getKey().compareTo(b.getKey())
                        : b.getValue() - a.getValue()
        );
        pq.addAll(wordCount.entrySet());

        List<String> result = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            result.add(pq.poll().getKey());
        }
        return result;
    }
}
```

words = \[ "i ", "love ", "leetcode ", "i ", "love ", "coding "\], k = 2

["i ", "love ", "leetcode ", "i ", "love ", "coding ", "i ", "love ", "leetcode ", "i ", "love"]
2

["apple ", "banana ", "cherry ", "apple ", "banana ", "cherry ", "banana ", "apple ", "banana"]
2

["the ", "day ", "is ", "sunny ", "the ", "the ", "the ", "sunny ", "is ", "is ", "the ", "is ", "sunny"]
2

["the ", "day ", "is ", "sunny ", "the ", "the ", "the ", "sunny ", "is ", "is ", "the ", "is ", "sunny ", "is ", "the ", "sunny ", "is"]
2

["i", "love", "leetcode", "i", "love", "coding"]
2

["apple ", "banana ", "cherry ", "apple ", "banana ", "cherry ", "banana ", "apple"]
2

["i ", "love ", "leetcode ", "i ", "love ", "coding ", "i ", "love ", "leetcode ", "i"]
2

["aabbcc", "aabbcc", "aabbcc", "aabbcc", "aabb", "aabb", "aabb", "aabb", "cc", "cc", "cc", "cc", "cc", "cc", "cc"]
2

["apple ", "banana ", "cherry ", "apple ", "banana ", "cherry ", "banana ", "apple ", "banana ", "cherry ", "banana"]
2

["i ", "love ", "leetcode ", "i ", "love ", "coding ", "i ", "love ", "leetcode ", "i ", "love ", "coding", "i"]
2

["apple", "banana", "apple", "apple", "dog", "cat", "banana", "apple", "dog", "banana", "cat", "apple"]
2

["apple ", "banana ", "cherry ", "apple ", "banana ", "cherry"]
2

[ "i ", "love ", "leetcode ", "i ", "love ", "coding "]
2

["i ", "love ", "leetcode ", "i ", "love ", "coding "]
2

["i ", "love ", "leetcode ", "i ", "love ", "coding ", "i ", "love ", "leetcode ", "i ", "love ", "coding ", "i ", "love ", "coding"]
2

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

vector<string> kFrequentWords(vector<string>& words, int k) {
    unordered_map<string, int> wordCount;
    for (const auto& word : words) {
        wordCount[word]++;
    }

    auto comp = [](const pair<string, int>& a, const pair<string, int>& b) {
        if (a.second == b.second) {
            return a.first > b.first;
        }
        return a.second < b.second;
    };
    priority_queue<pair<string, int>, vector<pair<string, int>>, decltype(comp)> pq(comp);

    for (const auto& wc : wordCount) {
        pq.push(wc);
    }

    vector<string> result;
    for (int i = 0; i < k; ++i) {
        result.push_back(pq.top().first);
        pq.pop();
    }

    return result;
}
```


```python
def has_alternating_bits(n):
    prev_bit = n % 2
    n //= 2
    while n > 0:
        curr_bit = n % 2
        if curr_bit == prev_bit:
            return False
        prev_bit = curr_bit
        n //= 2
    return True
```

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

```java
public boolean hasAlternatingBits(int n) {
    int prevBit = n % 2;
    n /= 2;
    while (n > 0) {
        int currBit = n % 2;
        if (currBit == prevBit) return false;
        prevBit = currBit;
        n /= 2;
    }
    return true;
}
```


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

public int numDistinctIslands(int[][] grid) {
    HashSet<ArrayList<ArrayList<Integer>>> uniqueIslands = new HashSet<>();
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[0].length; j++) {
            if (grid[i][j] == 1) {
                ArrayList<ArrayList<Integer>> islandShape = new ArrayList<>();
                dfs(grid, i, j, i, j, islandShape);
                Collections.sort(islandShape, (shape1, shape2) -> {
                    int cmp = shape1.get(0).compareTo(shape2.get(0));
                    if (cmp != 0) return cmp;
                    return shape1.get(1).compareTo(shape2.get(1));
                });
                uniqueIslands.add(islandShape);
            }
        }
    }
    return uniqueIslands.size();
}

private void dfs(int[][] grid, int i, int j, int i0, int j0, ArrayList<ArrayList<Integer>> shape) {
    if (i >= 0 && i < grid.length && j >= 0 && j < grid[0].length && grid[i][j] == 1) {
        grid[i][j] = 2;
        ArrayList<Integer> current = new ArrayList<>();
        current.add(i - i0);
        current.add(j - j0);
        shape.add(current);
        dfs(grid, i - 1, j, i0, j0, shape);
        dfs(grid, i + 1, j, i0, j0, shape);
        dfs(grid, i, j - 1, i0, j0, shape);
        dfs(grid, i, j + 1, i0, j0, shape);
    }
}
```

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

void dfs(vector<vector<int>>& grid, int i, int j, int i0, int j0, vector<pair<int, int>>& shape) {
    if (i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] == 1) {
        grid[i][j] = 2;
        shape.push_back({i - i0, j - j0});
        dfs(grid, i - 1, j, i0, j0, shape);
        dfs(grid, i + 1, j, i0, j0, shape);
        dfs(grid, i, j - 1, i0, j0, shape);
        dfs(grid, i, j + 1, i0, j0, shape);
    }
}

int numDistinctIslands(vector<vector<int>>& grid) {
    set<vector<pair<int, int>>> unique_islands;
    for (int i = 0; i < grid.size(); ++i) {
        for (int j = 0; j < grid[0].size(); ++j) {
            if (grid[i][j] == 1) {
                vector<pair<int,int>> island_shape;
                dfs(grid, i, j, i, j, island_shape);
                sort(island_shape.begin(), island_shape.end());
                unique_islands.insert(island_shape);
            }
        }
    }
    return unique_islands.size();
}
```


```cpp
int maxAreaOfIsland(vector<vector<int>>& grid) {
    int max_area = 0;

    function<int(int, int)> dfs = [&](int i, int j) {
        if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j] == 0) {
            return 0;
        }
        grid[i][j] = 0;
        return 1 + dfs(i - 1, j) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i, j + 1);
    };

    for (int i = 0; i < grid.size(); i++) {
        for (int j = 0; j < grid[0].size(); j++) {
            if (grid[i][j]) {
                max_area = max(max_area, dfs(i, j));
            }
        }
    }
    return max_area;
}
```

```java
public int maxAreaOfIsland(int[][] grid) {
    int maxArea = 0;

    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[0].length; j++) {
            if (grid[i][j] == 1) {
                maxArea = Math.max(maxArea, dfs(grid, i, j));
            }
        }
    }
    return maxArea;
}

private int dfs(int[][] grid, int i, int j) {
    if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0) {
        return 0;
    }
    grid[i][j] = 0;
    return 1 + dfs(grid, i - 1, j) + dfs(grid, i + 1, j) + dfs(grid, i, j - 1) + dfs(grid, i, j + 1);
}
```


```python
def findShortestSubArray(nums):
    freq_map, start_map = {}, {}
    max_freq, min_length = 0, len(nums)

    for i, num in enumerate(nums):
        if num not in start_map:
            start_map[num] = i
        freq_map[num] = freq_map.get(num, 0) + 1

        freq = freq_map[num]
        if freq > max_freq:
            max_freq = freq
            min_length = i - start_map[num] + 1
        elif freq == max_freq:
            min_length = min(min_length, i - start_map[num] + 1)

    return min_length
```

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

int findShortestSubArray(std::vector<int>& nums) {
    std::unordered_map<int, int> freq_map, start_map;
    int max_freq = 0, min_length = nums.size();

    for (int i = 0; i < nums.size(); ++i) {
        if (start_map.count(nums[i]) == 0) {
            start_map[nums[i]] = i;
        }
        freq_map[nums[i]]++;

        int freq = freq_map[nums[i]];
        if (freq > max_freq) {
            max_freq = freq;
            min_length = i - start_map[nums[i]] + 1;
        } else if (freq == max_freq) {
            min_length = std::min(min_length, i - start_map[nums[i]] + 1);
        }
    }

    return min_length;
}
```


```python
def canPartitionKSubsets(nums, k):
    total_sum = sum(nums)
    if total_sum % k != 0:
        return False
    target = total_sum // k
    visited = [False] * len(nums)
    return dfs(nums, visited, 0, target, 0, k)

def dfs(nums, visited, start, target, curr_sum, k):
    if k == 1:
        return True
    if curr_sum == target:
        return dfs(nums, visited, 0, target, 0, k - 1)
    for i in range(start, len(nums)):
        if not visited[i] and curr_sum + nums[i] <= target:
            visited[i] = True
            if dfs(nums, visited, i + 1, target, curr_sum + nums[i], k):
                return True
            visited[i] = False
    return False
```

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

```java
public boolean canPartitionKSubsets(int[] nums, int k) {
  int sum = 0;
  for (int num : nums) sum += num;
  if (sum % k != 0) return false;
  int target = sum / k;
  boolean[] visited = new boolean[nums.length];
  return dfs(nums, visited, 0, target, 0, k);
}

private boolean dfs(int[] nums, boolean[] visited, int start, int target, int curr_sum, int k) {
  if (k == 1) return true;
  if (curr_sum == target) return dfs(nums, visited, 0, target, 0, k - 1);
  for (int i = start; i < nums.length; i++) {
    if (!visited[i] && curr_sum + nums[i] <= target) {
      visited[i] = true;
      if (dfs(nums, visited, i + 1, target, curr_sum + nums[i], k)) return true;
      visited[i] = false;
    }
  }
  return false;
}
```


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

def searchBST(root: TreeNode, val: int) -> TreeNode:
    if not root or root.val == val:
        return root
    return searchBST(root.right, val) if root.val < val else searchBST(root.left, val)
```

```cpp
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
};

TreeNode* searchBST(TreeNode* root, int val) {
    if (!root || root->val == val)
        return root;
    return (root->val < val) ? searchBST(root->right, val) : searchBST(root->left, val);
}
```


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

def insertIntoBST(root, val):
    if root is None:
        return TreeNode(val)

    if val < root.val:
        root.left = insertIntoBST(root.left, val)
    else:
        root.right = insertIntoBST(root.right, val)

    return root
```

```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 TreeNode insertIntoBST(TreeNode root, int val) {
    if (root == null) {
        return new TreeNode(val);
    }

    if (val < root.val) {
        root.left = insertIntoBST(root.left, val);
    } else {
        root.right = insertIntoBST(root.right, val);
    }

    return root;
}
```


```python
def search(nums: List[int], target: int) -> int:
    left, right = 0, len(nums) - 1
    while left <= right:
        mid = left + (right - left) // 2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1
```

```java
public int search(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) return mid;
        if (nums[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}
```


```python
class Solution:
    def numDistinctIslands(self, grid: List[List[int]]) -> int:
        def dfs(r, c, r0, c0):
            if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c]:
                grid[r][c] = 0
                island.append((r - r0, c - c0))
                dfs(r + 1, c, r0, c0)
                dfs(r - 1, c, r0, c0)
                dfs(r, c + 1, r0, c0)
                dfs(r, c - 1, r0, c0)

        def normalize(island):
            ret = []
            for p in island:
                x, y = p
                ret += [(x, y), (x, -y), (-x, y), (-x, -y), (y, x), (y, -x), (-y, x), (-y, -x)]
            ret.sort()
            return tuple(ret)

        distinctIslands = set()
        for r in range(len(grid)):
            for c in range(len(grid[0])):
                if grid[r][c]:
                    island = []
                    dfs(r, c, r, c)
                    distinctIslands.add(normalize(island))
        return len(distinctIslands)
```

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

class Solution {
    private void dfs(int r, int c, int r0, int c0, int[][] grid, ArrayList<int[]> island){
        if (r >= 0 && c >= 0 && r < grid.length && c < grid[0].length && grid[r][c] == 1) {
            grid[r][c] = 0;
            island.add(new int[]{r - r0, c - c0});
            dfs(r + 1, c, r0, c0, grid, island);
            dfs(r - 1, c, r0, c0, grid, island);
            dfs(r, c + 1, r0, c0, grid, island);
            dfs(r, c - 1, r0, c0, grid, island);
        }
    }

    private String normalize(ArrayList<int[]> island) {
        ArrayList<String> ret = new ArrayList<>();
        for (int[] p : island) {
            int x = p[0];
            int y = p[1];
            ret.add(x + "," + y);
            ret.add(x + "," + -y);
            ret.add(-x + "," + y);
            ret.add(-x + "," + -y);
            ret.add(y + "," + x);
            ret.add(y + "," + -x);
            ret.add(-y + "," + x);
            ret.add(-y + "," + -x);
        }
        ret.sort(String::compareTo);
        return String.join(" ", ret);
    }

    public int numDistinctIslands(int[][] grid) {
        Set<String> distinctIslands = new HashSet<>();
        for (int r = 0; r < grid.length; ++r) {
            for (int c = 0; c < grid[r].length; ++c) {
                if (grid[r][c] == 1) {
                    ArrayList<int[]> island = new ArrayList<>();
                    dfs(r, c, r, c, grid, island);
                    distinctIslands.add(normalize(island));
                }
            }
        }
        return distinctIslands.size();
    }
}
```


```python
def minimumDeleteSum(s1: str, s2: str) -> int:
    dp = [[0] * (len(s2) + 1) for _ in range(len(s1) + 1)]
    for i in range(1, len(s1) + 1):
        dp[i][0] = dp[i - 1][0] + ord(s1[i - 1])
    for j in range(1, len(s2) + 1):
        dp[0][j] = dp[0][j - 1] + ord(s2[j - 1])
    for i in range(1, len(s1) + 1):
        for j in range(1, len(s2) + 1):
            if s1[i - 1] == s2[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = min(dp[i - 1][j] + ord(s1[i - 1]), dp[i][j - 1] + ord(s2[j - 1]))
    return dp[len(s1)][len(s2)]
```

```java
public int minimumDeleteSum(String s1, String s2) {
    int[][] dp = new int[s1.length() + 1][s2.length() + 1];
    for (int i = 1; i <= s1.length(); i++) {
        dp[i][0] = dp[i - 1][0] + s1.charAt(i - 1);
    }
    for (int j = 1; j <= s2.length(); j++) {
        dp[0][j] = dp[0][j - 1] + s2.charAt(j - 1);
    }
    for (int i = 1; i <= s1.length(); i++) {
        for (int j = 1; j <= s2.length(); j++) {
            if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                dp[i][j] = dp[i - 1][j - 1];
            } else {
                dp[i][j] = Math.min(dp[i - 1][j] + s1.charAt(i - 1), dp[i][j - 1] + s2.charAt(j - 1));
            }
        }
    }
    return dp[s1.length()][s2.length()];
}
```


```python
def maxProfit(prices, fee):
    cash, hold = 0, -prices[0]
    for price in prices:
        temp = cash
        cash = max(cash, hold + price - fee)
        hold = max(hold, temp - price)
    return cash
```

```cpp
int maxProfit(vector<int>& prices, int fee) {
    int cash = 0, hold = -prices[0];
    for (int price : prices) {
        int temp = cash;
        cash = max(cash, hold + price - fee);
        hold = max(hold, temp - price);
    }
    return cash;
}
```


```java
boolean isOneBitCharacter(int[] bits) {
    int i;
    for (i = 0; i < bits.length - 1; i++) {
        i += bits[i];
    }
    return i == bits.length - 1;
}
```

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

```cpp
bool isOneBitCharacter(std::vector<int>& bits) {
    int i;
    for (i = 0; i < bits.size() - 1; i++) {
        i += bits[i];
    }
    return i == bits.size() - 1;
}
```


```cpp
int findLength(vector<int>& nums1, vector<int>& nums2) {
    int m = nums1.size();
    int n = nums2.size();
    vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
    int maxLength = 0;

    for (int i = m - 1; i >= 0; i--) {
        for (int j = n - 1; j >= 0; j--) {
            if (nums1[i] == nums2[j]) {
                dp[i][j] = dp[i + 1][j + 1] + 1;
                maxLength = max(maxLength, dp[i][j]);
            }
        }
    }

    return maxLength;
}
```

```python
def findLength(nums1, nums2):
    m, n = len(nums1), len(nums2)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    maxLength = 0

    for i in range(m - 1, -1, -1):
        for j in range(n - 1, -1, -1):
            if nums1[i] == nums2[j]:
                dp[i][j] = dp[i + 1][j + 1] + 1
                maxLength = max(maxLength, dp[i][j])

    return maxLength
```


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

int smallestDistancePair(std::vector<int>& nums, int k) {
    std::sort(nums.begin(), nums.end());
    int low = 0, high = nums.back() - nums.front();

    while (low < high) {
        int mid = (low + high) / 2;
        int count = 0, left = 0;

        for (int right = 0; right < nums.size(); ++right) {
            while (nums[right] - nums[left] > mid) {
                ++left;
            }
            count += (right - left);
        }

        if (count < k) {
            low = mid + 1;
        } else {
            high = mid;
        }
    }

    return low;
}
```

```python
def smallestDistancePair(nums, k):
    nums.sort()
    low, high = 0, nums[-1] - nums[0]

    while low < high:
        mid = (low + high) // 2
        count, left = 0, 0

        for right in range(len(nums)):
            while nums[right] - nums[left] > mid:
                left += 1
            count += (right - left)

        if count < k:
            low = mid + 1
        else:
            high = mid

    return low
```


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

std::string longestWord(std::vector<std::string>& words) {
    std::sort(words.begin(), words.end());
    std::set<std::string> built_words;
    std::string result = "";

    for (const auto& word : words) {
        if (word.size() == 1 || built_words.find(word.substr(0, word.size() - 1)) != built_words.end()) {
            result = (word.size() > result.size()) ? word : result;
            built_words.insert(word);
        }
    }

    return result;
}
```

words = \[ "w ", "wo ", "wor ", "worl ", "world "\]

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

class Solution {
    public String longestWord(String[] words) {
        Arrays.sort(words);
        Set<String> builtWords = new HashSet<>();
        String result = "";

        for (String word : words) {
            if (word.length() == 1 || builtWords.contains(word.substring(0, word.length() - 1))) {
                result = (word.length() > result.length()) ? word : result;
                builtWords.add(word);
            }
        }

        return result;
    }
}
```


```java
import java.util.*;

public List<List<String>> accountsMerge(List<List<String>> accounts) {
    Map<String, Integer> emailToId = new HashMap<>();
    for (int i = 0; i < accounts.size(); ++i) {
        for (int j = 1; j < accounts.get(i).size(); ++j) {
            emailToId.put(accounts.get(i).get(j), i);
        }
    }

    List<List<String>> result = new ArrayList<>();
    boolean[] visited = new boolean[accounts.size()];
    for (int i = 0; i < accounts.size(); ++i) {
        if (!visited[i]) {
            Set<String> mergedEmails = new HashSet<>();
            dfs(i, accounts, visited, mergedEmails, emailToId);
            List<String> mergedAccount = new ArrayList<>(mergedEmails);
            Collections.sort(mergedAccount);
            mergedAccount.add(0, accounts.get(i).get(0));
            result.add(mergedAccount);
        }
    }
    return result;
}

private void dfs(int id, List<List<String>> accounts, boolean[] visited, Set<String> mergedEmails, Map<String, Integer> emailToId) {
    if (visited[id]) return;
    visited[id] = true;
    for (int j = 1; j < accounts.get(id).size(); ++j) {
        String email = accounts.get(id).get(j);
        mergedEmails.add(email);
        int nextId = emailToId.get(email);
        dfs(nextId, accounts, visited, mergedEmails, emailToId);
    }
}
```

accounts = \[\[ "John ", "johnsmith@mail.com ", "john\_newyork@mail.com "\],\[ "John ", "johnsmith@mail.com ", "john00@mail.com "\],\[ "Mary ", "mary@mail.com "\],\[ "John ", "johnnybravo@mail.com "\]\]

\[\[ "John ", "john00@mail.com ", "john\_newyork@mail.com ", "johnsmith@mail.com "\],\[ "Mary ", "mary@mail.com "\],\[ "John ", "johnnybravo@mail.com "\]\]

[[ "John ", "johnsmith@mail.com ", "john\_newyork@mail.com "],[ "John ", "johnsmith@mail.com ", "john00@mail.com "],[ "Mary ", "mary@mail.com "],[ "John ", "johnnybravo@mail.com "]]

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

using namespace std;

void dfs(int id, const vector<vector<string>>& accounts, vector<bool>& visited, set<string>& merged_emails, map<string, int>& email_to_id) {
    if (visited[id]) return;
    visited[id] = true;
    for (int j = 1; j < accounts[id].size(); ++j) {
        const string& email = accounts[id][j];
        merged_emails.insert(email);
        int next_id = email_to_id[email];
        dfs(next_id, accounts, visited, merged_emails, email_to_id);
    }
}

vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
    map<string, int> email_to_id;
    for (int i = 0; i < accounts.size(); ++i)
        for (int j = 1; j < accounts[i].size(); ++j)
            email_to_id[accounts[i][j]] = i;

    vector<vector<string>> result;
    vector<bool> visited(accounts.size(), false);
    for (int i = 0; i < accounts.size(); ++i) {
        if (!visited[i]) {
            set<string> merged_emails;
            dfs(i, accounts, visited, merged_emails, email_to_id);
            vector<string> merged_account(merged_emails.begin(), merged_emails.end());
            merged_account.insert(merged_account.begin(), accounts[i][0]);
            result.push_back(merged_account);
        }
    }
    return result;
}
```


```java
public int[][] candyCrush(int[][] board) {
    int rows = board.length, cols = board[0].length;
    boolean toDo = false;

    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols - 2; c++) {
            int val = Math.abs(board[r][c]);
            if (val != 0 && val == Math.abs(board[r][c + 1]) && val == Math.abs(board[r][c + 2])) {
                board[r][c] = board[r][c + 1] = board[r][c + 2] = -val;
                toDo = true;
            }
        }
    }

    for (int r = 0; r < rows - 2; r++) {
        for (int c = 0; c < cols; c++) {
            int val = Math.abs(board[r][c]);
            if (val != 0 && val == Math.abs(board[r + 1][c]) && val == Math.abs(board[r + 2][c])) {
                board[r][c] = board[r + 1][c] = board[r + 2][c] = -val;
                toDo = true;
            }
        }
    }

    for (int c = 0; c < cols; c++) {
        int wr = rows - 1;
        for (int r = rows - 1; r >= 0; r--)
            if (board[r][c] > 0)
                board[wr--][c] = board[r][c];
        while (wr >= 0)
            board[wr--][c] = 0;
    }

    return toDo ? candyCrush(board) : board;
}
```

```python
def candyCrush(board):
    rows = len(board)
    cols = len(board[0])
    toDo = False

    for r in range(rows):
        for c in range(cols - 2):
            val = abs(board[r][c])
            if val and val == abs(board[r][c + 1]) and val == abs(board[r][c + 2]):
                board[r][c] = board[r][c + 1] = board[r][c + 2] = -val
                toDo = True

    for r in range(rows - 2):
        for c in range(cols):
            val = abs(board[r][c])
            if val and val == abs(board[r + 1][c]) and val == abs(board[r + 2][c]):
                board[r][c] = board[r + 1][c] = board[r + 2][c] = -val
                toDo = True

    for c in range(cols):
        wr = rows - 1
        for r in range(rows - 1, -1, -1):
            if board[r][c] > 0:
                board[wr][c] = board[r][c]
                wr -= 1

        for r in range(wr, -1, -1):
            board[r][c] = 0

    return candyCrush(board) if toDo else board
```


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

map<string, int> parse(const string &formula, int &i) {
    map<string, int> counts;
    while (i < formula.size()) {
        if (formula[i] == '(') {
            map<string, int> temp = parse(formula, ++i);
            int count = 0;
            while (isdigit(formula[i])) {
                count = count * 10 + (formula[i++] - '0');
            }
            if (count == 0) count = 1;
            for (const auto &e : temp) {
                counts[e.first] += e.second * count;
            }
        } else if (formula[i] == ')') {
            ++i;
            return counts;
        } else {
            string name;
            name += formula[i++];
            while (islower(formula[i])) {
                name += formula[i++];
            }
            int count = 0;
            while (isdigit(formula[i])) {
                count = count * 10 + (formula[i++] - '0');
            }
            if (count == 0) count = 1;
            counts[name] += count;
        }
    }
    return counts;
}

string countOfAtoms(string formula) {
    int i = 0;
    map<string, int> counts = parse(formula, i);
    string ans;
    for (const auto &e : counts) {
        ans += e.first;
        if (e.second > 1) ans += to_string(e.second);
    }
    return ans;
}
```

```python
from collections import Counter

def parse(formula, i):
    counts = Counter()
    while i[0] < len(formula):
        if formula[i[0]] == '(':
            i[0] += 1
            temp = parse(formula, i)
            count = 0
            while i[0] < len(formula) and formula[i[0]].isdigit():
                count = count * 10 + int(formula[i[0]])
                i[0] += 1
            if count == 0: count = 1
            for name, c in temp.items():
                counts[name] += c * count
        elif formula[i[0]] == ')':
            i[0] += 1
            return counts
        else:
            name = formula[i[0]]
            i[0] += 1
            while i[0] < len(formula) and formula[i[0]].islower():
                name += formula[i[0]]
                i[0] += 1
            count = 0
            while i[0] < len(formula) and formula[i[0]].isdigit():
                count = count * 10 + int(formula[i[0]])
                i[0] += 1
            if count == 0: count = 1
            counts[name] += count
    return counts

def countOfAtoms(formula):
    i = [0]
    counts = parse(formula, i)
    ans = []
    for name, count in counts.items():
        ans.append(name)
        if count > 1: ans.append(str(count))
    return ''.join(ans)
```


```cpp
#include <vector>

bool isSelfDividing(int num) {
    int n = num;
    while (n) {
        int digit = n % 10;
        if (digit == 0 || num % digit != 0)
            return false;
        n /= 10;
    }
    return true;
}

std::vector<int> selfDividingNumbers(int left, int right) {
    std::vector<int> result;
    for (int i = left; i <= right; ++i) {
        if (isSelfDividing(i))
            result.push_back(i);
    }
    return result;
}
```

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

public class Solution {
    public static boolean isSelfDividing(int num) {
        int n = num;
        while (n != 0) {
            int digit = n % 10;
            if (digit == 0 || num % digit != 0)
                return false;
            n /= 10;
        }
        return true;
    }

    public static List<Integer> selfDividingNumbers(int left, int right) {
        List<Integer> result = new ArrayList<>();
        for (int i = left; i <= right; ++i) {
            if (isSelfDividing(i))
                result.add(i);
        }
        return result;
    }
}
```


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

void fill(vector<vector<int>>& image, int sr, int sc, int newColor, int startColor) {
    if (sr < 0 || sc < 0 || sr >= image.size() || sc >= image[0].size() || image[sr][sc] != startColor || image[sr][sc] == newColor) return;
    image[sr][sc] = newColor;
    fill(image, sr - 1, sc, newColor, startColor);
    fill(image, sr + 1, sc, newColor, startColor);
    fill(image, sr, sc - 1, newColor, startColor);
    fill(image, sr, sc + 1, newColor, startColor);
}

vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
    int startColor = image[sr][sc];
    fill(image, sr, sc, newColor, startColor);
    return image;
}
```

```python
def floodFill(image, sr, sc, newColor):
    startColor = image[sr][sc]
    def fill(sr, sc):
        if not (0 <= sr < len(image)) or not (0 <= sc < len(image[0])) or image[sr][sc] != startColor or image[sr][sc] == newColor:
            return
        image[sr][sc] = newColor
        fill(sr - 1, sc)
        fill(sr + 1, sc)
        fill(sr, sc - 1)
        fill(sr, sc + 1)

    fill(sr, sc)
    return image
```


```java
import java.util.*;

public boolean areSentencesSimilar(String[] sentence1, String[] sentence2, List<List<String>> similarPairs) {
    if (sentence1.length != sentence2.length) return false;
    Map<String, Set<String>> similarityMap = new HashMap<>();
    for (List<String> pair : similarPairs) {
        similarityMap.putIfAbsent(pair.get(0), new HashSet<>());
        similarityMap.putIfAbsent(pair.get(1), new HashSet<>());
        similarityMap.get(pair.get(0)).add(pair.get(1));
        similarityMap.get(pair.get(1)).add(pair.get(0));
    }
    for (int i = 0; i < sentence1.length; ++i) {
        if (!sentence1[i].equals(sentence2[i]) && !similarityMap.getOrDefault(sentence1[i], Collections.emptySet()).contains(sentence2[i]))
            return false;
    }
    return true;
}
```

sentence1 = \[ "great ", "acting ", "skills "\], sentence2 = \[ "fine ", "drama ", "talent "\], similarPairs = \[\[ "great ", "fine "\],\[ "drama ", "acting "\],\[ "skills ", "talent "\]\]

[ "quick ", "brown ", "fox "]
[ "fast ", "quick ", "animal "]
[[ "quick ", "fast "],[ "fox ", "animal "]]

[ "hello ", "world "]
[ "hi ", "universe "]
[[ "hello ", "hi "]]

[ "great ", "acting ", "skills "]
[ "fine ", "drama ", "talent "]
[["great ", "fine "],["acting ", "drama "],["skills ", "talent "]]

[ "I ", "am ", "happy ", "with ", "leetcode "]
[ "I ", "am ", "happy ", "with ", "leetcode "]
[["I ", "I "],["am ", "am "],["happy ", "happy "],["with ", "with "],["leetcode ", "leetcode "]]

[ "sea ", "sail "]
[ "ocean ", "voyage "]
[[ "sea ", "ocean "],[ "sail ", "voyage "],[ "sailing ", "navigation "]]

[ "terrific ", "play ", "ability "]
[ "excellent ", "performance ", "talent "]
[[ "terrific ", "excellent "],[ "play ", "performance "],[ "ability ", "talent "]]

[ "sky ", "cloud ", "rain "]
[ "firmament ", "nimbus ", "pluie "]
[[ "sky ", "firmament "],[ "cloud ", "nimbus "],[ "rain ", "pluie "]]

[ "sun ", "moon ", "stars "]
[ "light ", "darkness ", "galaxies "]
[]

[ "great "]
[ "doubleplus ", "good "]
[["great ", "doubleplus "]]

[ "apple ", "banana ", "cherry "]
[ "orange ", "banana ", "grape "]
[[ "apple ", "orange "],[ "cherry ", "grape "]]

[ "great ", "acting ", "skills "]
[ "fine ", "drama ", "talent "]
[[ "great ", "fine "],[ "drama ", "acting "],[ "skills ", "talent "]]

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

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

bool areSentencesSimilar(vector<string>& sentence1, vector<string>& sentence2, vector<vector<string>>& similarPairs) {
    if (sentence1.size() != sentence2.size()) return false;
    unordered_map<string, unordered_set<string>> similarityMap;
    for (const auto& pair : similarPairs) {
        similarityMap[pair[0]].insert(pair[1]);
        similarityMap[pair[1]].insert(pair[0]);
    }
    for (int i = 0; i < sentence1.size(); ++i) {
        if (sentence1[i] != sentence2[i] && !similarityMap[sentence1[i]].count(sentence2[i]))
            return false;
    }
    return true;
}
```


```python
def asteroidCollision(asteroids):
    s = []
    for num in asteroids:
        if num > 0 or not s or s[-1] < 0:
            s.append(num)
        elif s[-1] <= -num:
            if s[-1] < -num:
                s.pop()
                s.append(num)
            else:
                s.pop()
    return s
```

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

vector<int> asteroidCollision(vector<int>& asteroids) {
    vector<int> s;
    for (int i = 0; i < asteroids.size(); i++) {
        if (asteroids[i] > 0 || s.empty() || s.back() < 0) {
            s.push_back(asteroids[i]);
        } else if (s.back() <= -asteroids[i]) {
            if (s.back() < -asteroids[i]) i--;
            s.pop_back();
        }
    }
    return s;
}
```


```cpp
int monotoneIncreasingDigits(int n) {
    string n_str = to_string(n);
    int n_len = n_str.size();

    int i = n_len - 1;
    while (i > 0) {
        if (n_str[i] < n_str[i - 1]) {
            n_str[i - 1] -= 1;
            for (int j = i; j < n_len; ++j) {
                n_str[j] = '9';
            }
        }
        --i;
    }

    return stoi(n_str);
}
```

```java
public int monotoneIncreasingDigits(int n) {
    char[] n_str = String.valueOf(n).toCharArray();
    int n_len = n_str.length;

    int i = n_len - 1;
    while (i > 0) {
        if (n_str[i] < n_str[i - 1]) {
            n_str[i - 1] -= 1;
            for (int j = i; j < n_len; ++j) {
                n_str[j] = '9';
            }
        }
        --i;
    }

    return Integer.parseInt(new String(n_str));
}
```


```java
import java.util.Stack;

public int[] dailyTemperatures(int[] temperatures) {
    int[] result = new int[temperatures.length];
    Stack<Integer> stack = new Stack<>();

    for (int i = 0; i < temperatures.length; i++) {
        while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
            int idx = stack.pop();
            result[idx] = i - idx;
        }
        stack.push(i);
    }

    return result;
}
```

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

std::vector<int> dailyTemperatures(std::vector<int>& temperatures) {
    std::vector<int> result(temperatures.size(), 0);
    std::stack<int> stack;

    for (size_t i = 0; i < temperatures.size(); ++i) {
        while (!stack.empty() && temperatures[i] > temperatures[stack.top()]) {
            int idx = stack.top();
            stack.pop();
            result[idx] = i - idx;
        }
        stack.push(i);
    }

    return result;
}
```


```python
def max_points(nums):
    dp = [0] * 100001
    max_points = 0
    for num in nums:
        dp[num] += 1
    for i in range(2, len(dp)):
        dp[i] = max(dp[i - 1], dp[i - 2] + i * dp[i])
        max_points = max(max_points, dp[i])
    return max_points
```

```cpp
int maxPoints(vector<int>& nums) {
    vector<int> dp(100001, 0);
    int max_points = 0;
    for (int num : nums) {
        dp[num]++;
    }
    for (int i = 2; i < dp.size(); i++) {
        dp[i] = max(dp[i - 1], dp[i - 2] + i * dp[i]);
        max_points = max(max_points, dp[i]);
    }
    return max_points;
}
```