```python
def findKthLargest(nums: List[int], k: int) -> int:
    nums.sort(reverse=True)
    return nums[k-1]
```

```java
import java.util.PriorityQueue;

public int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> minHeap = new PriorityQueue<>();
    for (int num : nums) {
        minHeap.add(num);
        if (minHeap.size() > k) {
            minHeap.poll();
        }
    }
    return minHeap.poll();
}
```


```python
def combinationSum3(k, n):
    def helper(k, n, current, current_comb, result):
        if k == 0 and n == 0:
            result.append(list(current_comb))
        elif k > 0 and n > 0:
            for i in range(current + 1, 10):
                current_comb.append(i)
                helper(k - 1, n - i, i, current_comb, result)
                current_comb.pop()

    result = []
    helper(k, n, 0, [], result)
    return result
```

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

public List<List<Integer>> combinationSum3(int k, int n) {
    List<List<Integer>> result = new ArrayList<>();
    helper(k, n, 0, new ArrayList<>(), result);
    return result;
}

private void helper(int k, int n, int current, List<Integer> currentComb, List<List<Integer>> result) {
    if (k == 0 && n == 0) {
        result.add(new ArrayList<>(currentComb));
    } else if (k > 0 && n > 0) {
        for (int i = current + 1; i <= 9; i++) {
            currentComb.add(i);
            helper(k - 1, n - i, i, currentComb, result);
            currentComb.remove(currentComb.size() - 1);
        }
    }
}
```


```java
public boolean containsDuplicate(int[] nums) {
    Set<Integer> set = new HashSet<Integer>();
    for (int num : nums) {
        if (!set.add(num)) {
            return true;
        }
    }
    return false;
}
```

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

```cpp
bool containsDuplicate(vector<int>& nums) {
    unordered_set<int> s;
    for (int num : nums) {
        if (s.find(num) != s.end()) {
            return true;
        }
        s.insert(num);
    }
    return false;
}
```


```cpp
bool containsNearbyDuplicate(vector<int>& nums, int k) {
    unordered_map<int, int> valueIndexMap;
    for (int i = 0; i < nums.size(); i++) {
        if (valueIndexMap.find(nums[i]) != valueIndexMap.end() && i - valueIndexMap[nums[i]] <= k) {
            return true;
        }
        valueIndexMap[nums[i]] = i;
    }
    return false;
}
```

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

```java
public boolean containsNearbyDuplicate(int[] nums, int k) {
    HashMap<Integer, Integer> valueIndexMap = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        if (valueIndexMap.containsKey(nums[i]) && i - valueIndexMap.get(nums[i]) <= k) {
            return true;
        }
        valueIndexMap.put(nums[i], i);
    }
    return false;
}
```


```java
import java.util.TreeSet;

public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    TreeSet<Long> window = new TreeSet<>();
    for(int i = 0; i < nums.length; i++) {
        if(i > k) {
            window.remove((long)nums[i - k - 1]);
        }
        Long ceil = window.ceiling((long)nums[i] - t);
        if(ceil != null && ceil - nums[i] <= t) {
            return true;
        }
        window.add((long)nums[i]);
    }
    return false;
}
```

nums = \[1,2,3,1\], indexDiff = 3, valueDiff = 0

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

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

bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
    set<long> window;
    for (int i = 0; i < nums.size(); i++) {
        if (i > k) {
            window.erase(nums[i - k - 1]);
        }
        auto pos = window.lower_bound((long)nums[i] - t);
        if (pos != window.end() && *pos - nums[i] <= t) {
            return true;
        }
        window.insert(nums[i]);
    }
    return false;
}
```


```cpp
int maximalSquare(vector<vector<char>>& matrix) {
    int m = matrix.size();
    int n = matrix[0].size();
    vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
    int maxSize = 0;

    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (matrix[i - 1][j - 1] == '1') {
                dp[i][j] = min({dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]}) + 1;
                maxSize = max(maxSize, dp[i][j]);
            }
        }
    }

    return maxSize * maxSize;
}
```

```python
def maximalSquare(matrix):
    m, n = len(matrix), len(matrix[0])
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    maxSize = 0

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if matrix[i - 1][j - 1] == '1':
                dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1
                maxSize = max(maxSize, dp[i][j])

    return maxSize * maxSize
```


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

public int countNodes(TreeNode root) {
    if (root == null) return 0;
    int ld = 0, rd = 0;
    TreeNode l = root, r = root;

    while (l != null) {
        l = l.left;
        ld++;
    }

    while (r != null) {
        r = r.right;
        rd++;
    }

    if (ld == rd) return (1 << ld) - 1;
    return 1 + countNodes(root.left) + countNodes(root.right);
}
```

```cpp
class TreeNode {
public:
    TreeNode *left, *right;
};

int countNodes(TreeNode* root) {
    if (!root) return 0;
    int ld = 0, rd = 0;
    TreeNode *l = root, *r = root;

    while (l) {
        l = l->left;
        ld++;
    }

    while (r) {
        r = r->right;
        rd++;
    }

    if (ld == rd) return (1 << ld) - 1;
    return 1 + countNodes(root->left) + countNodes(root->right);
}
```


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

TreeNode* invertTree(TreeNode* root) {
    if (root == nullptr) {
        return nullptr;
    }
    TreeNode* temp = root->left;
    root->left = invertTree(root->right);
    root->right = invertTree(temp);
    return root;
}
```

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

def invert_tree(root):
    if root is None:
        return None
    root.left, root.right = invert_tree(root.right), invert_tree(root.left)
    return root
```


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

public List<String> findRanges(int[] nums) {
    List<String> result = new ArrayList<>();
    int n = nums.length;
    if (n == 0) return result;

    int start = nums[0];
    for (int i = 1; i < n; i++) {
        if (nums[i] > nums[i-1] + 1) {
            if (start == nums[i-1])
                result.add(Integer.toString(start));
            else
                result.add(start + "->" + nums[i-1]);
            start = nums[i];
        }
    }

    if (start == nums[n-1])
        result.add(Integer.toString(start));
    else
        result.add(start + "->" + nums[n-1]);

    return result;
}
```

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

std::vector<std::string> find_ranges(std::vector<int>& nums) {
    std::vector<std::string> result;
    int n = nums.size();
    if (n == 0) return result;

    int start = nums[0];
    for (int i = 1; i < n; ++i) {
        if (nums[i] > nums[i-1] + 1) {
            if (start == nums[i-1])
                result.push_back(std::to_string(start));
            else
                result.push_back(std::to_string(start) + "->" + std::to_string(nums[i-1]));
            start = nums[i];
        }
    }

    if (start == nums[n-1])
        result.push_back(std::to_string(start));
    else
        result.push_back(std::to_string(start) + "->" + std::to_string(nums[n-1]));

    return result;
}
```


```python
def majorityElement(nums):
    n = len(nums)
    count = {}
    result = []

    for num in nums:
        if num not in count:
            count[num] = 1
        else:
            count[num] += 1
        if count[num] > n / 3 and num not in result:
            result.append(num)

    return result
```

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

public List<Integer> majorityElement(int[] nums) {
    int n = nums.length;
    HashMap<Integer, Integer> count = new HashMap<>();
    ArrayList<Integer> result = new ArrayList<>();

    for (int num : nums) {
        count.put(num, count.getOrDefault(num, 0) + 1);
        if (count.get(num) > n / 3 && !result.contains(num)) {
            result.add(num);
        }
    }
    return result;
}
```


```cpp
class TreeNode {
public:
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

int kthSmallest(TreeNode* root, int k) {
    stack<TreeNode*> stk;
    TreeNode* curr = root;

    while (true) {
        while (curr) {
            stk.push(curr);
            curr = curr->left;
        }

        curr = stk.top();
        stk.pop();

        if (--k == 0) return curr->val;

        curr = curr->right;
    }
}

```

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

def kthSmallest(root, k):
    stk = []
    curr = root

    while True:
        while curr:
            stk.append(curr)
            curr = curr.left

        curr = stk.pop()

        k -= 1
        if k == 0:
            return curr.val

        curr = curr.right
```


```cpp
bool isPowerOfTwo(int n) {
    if (n <= 0) {
        return false;
    }
    return (n & (n - 1)) == 0;
}
```

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

```python
def is_power_of_two(n):
    if n <= 0:
        return False
    return (n & (n - 1)) == 0
```


```cpp
int countDigitOne(int n) {
    int count = 0;
    for(long long i = 1; i <= n; i *= 10){
        int divider = i * 10;
        count += (n / divider) * i + min(max(n % divider - i + 1, 0LL), i);
    }
    return count;
}
```

```python
def countDigitOne(n):
    count = 0
    i = 1
    while i <= n:
        divider = i * 10
        count += (n // divider) * i + min(max(n % divider - i + 1, 0), i)
        i *= 10
    return count
```


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

def isPalindrome(head):
    if not head or not head.next:
        return True

    fast, slow, prev = head, head, None
    while fast and fast.next:
        fast = fast.next.next
        temp = slow.next
        slow.next = prev
        prev = slow
        slow = temp

    if fast:
        slow = slow.next

    while prev and prev.val == slow.val:
        prev = prev.next
        slow = slow.next

    return prev == None
```

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

```java
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

public boolean isPalindrome(ListNode head) {
    if (head == null || head.next == null) return true;

    ListNode fast = head, slow = head, prev = null;
    while (fast != null && fast.next != null) {
        fast = fast.next.next;
        ListNode temp = slow.next;
        slow.next = prev;
        prev = slow;
        slow = temp;
    }

    if (fast != null) slow = slow.next;

    while (prev != null && prev.val == slow.val) {
        prev = prev.next;
        slow = slow.next;
    }

    return prev == null;
}
```


```java
import java.util.LinkedList;
import java.util.Deque;

public int[] maxSlidingWindow(int[] nums, int k) {
    if (nums == null || nums.length == 0) return new int[0];
    int[] result = new int[nums.length - k + 1];
    int idx = 0;
    Deque<Integer> deque = new LinkedList<Integer>();

    for (int i = 0; i < nums.length; i++) {
        if (!deque.isEmpty() && deque.peekFirst() == i - k) deque.poll();

        while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
            deque.removeLast();
        }

        deque.offer(i);
        if (i >= k - 1) {
            result[idx++] = nums[deque.peek()];
        }
    }
    return result;
}
```

```cpp
#include <vector>
#include <deque>

std::vector<int> maxSlidingWindow(std::vector<int>& nums, int k) {
    std::vector<int> result;
    std::deque<int> dq;

    for (int i = 0; i < nums.size(); i++) {
        while (!dq.empty() && dq.front() < i - k + 1) {
            dq.pop_front();
        }

        while (!dq.empty() && nums[dq.back()] < nums[i]) {
            dq.pop_back();
        }

        dq.push_back(i);

        if (i >= k - 1) {
            result.push_back(nums[dq.front()]);
        }
    }

    return result;
}
```


```java
public boolean searchMatrix(int[][] matrix, int target) {
    int row = matrix.length - 1, col = 0;
    while (row >= 0 && col < matrix[0].length) {
        if (matrix[row][col] > target) {
            row--;
        } else if (matrix[row][col] < target) {
            col++;
        } else {
            return true;
        }
    }
    return false;
}
```

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

```cpp
bool searchMatrix(vector<vector<int>>& matrix, int target) {
    int row = matrix.size() - 1, col = 0;
    while (row >= 0 && col < matrix[0].size()) {
        if (matrix[row][col] > target) {
            row--;
        } else if (matrix[row][col] < target) {
            col++;
        } else {
            return true;
        }
    }
    return false;
}
```


```python
def diffWaysToCompute(input: str):
    result = []
    for i in range(len(input)):
        c = input[i]
        if c == '+' or c == '-' or c == '*':
            left = diffWaysToCompute(input[:i])
            right = diffWaysToCompute(input[i + 1:])
            for l in left:
                for r in right:
                    if c == '+': result.append(l + r)
                    elif c == '-': result.append(l - r)
                    elif c == '*': result.append(l * r)
    if not result:
        result.append(int(input))
    return result
```

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

public List<Integer> diffWaysToCompute(String input) {
    List<Integer> result = new ArrayList<>();
    for (int i = 0; i < input.length(); i++) {
        char c = input.charAt(i);
        if (c == '+' || c == '-' || c == '*') {
            List<Integer> left = diffWaysToCompute(input.substring(0, i));
            List<Integer> right = diffWaysToCompute(input.substring(i + 1));
            for (int l : left) {
                for (int r : right) {
                    if (c == '+') result.add(l + r);
                    else if (c == '-') result.add(l - r);
                    else if (c == '*') result.add(l * r);
                }
            }
        }
    }
    if (result.isEmpty()) result.add(Integer.parseInt(input));
    return result;
}
```


```java
public boolean isAnagram(String s, String t) {
    if(s.length() != t.length())
        return false;

    int[] counts = new int[26];
    for(char c : s.toCharArray())
        counts[c - 'a']++;

    for(char c : t.toCharArray()) {
        if(counts[c - 'a'] == 0)
            return false;
        counts[c - 'a']--;
    }

    return true;
}
```

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

```python
def is_anagram(s, t):
    if len(s) != len(t):
        return False

    counts = {}
    for c in s:
        if c in counts:
            counts[c] += 1
        else:
            counts[c] = 1

    for c in t:
        if c not in counts or counts[c] == 0:
            return False
        counts[c] -= 1

    return True
```


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

int shortestDistance(std::vector<std::string>& wordsDict, std::string word1, std::string word2) {
    int index1 = -1, index2 = -1, minDistance = std::numeric_limits<int>::max();
    for (int i = 0; i < wordsDict.size(); ++i) {
        if (wordsDict[i] == word1) { index1 = i; }
        if (wordsDict[i] == word2) { index2 = i; }
        if (index1 != -1 && index2 != -1) {
            minDistance = std::min(minDistance, std::abs(index1 - index2));
        }
    }
    return minDistance;
}
```

wordsDict = \["practice", "makes", "perfect", "coding", "makes"\], word1 = "makes", word2 = "coding"

["practice", "make", "perfect", "coding", "make"]
coding
perfect

["apple", "banana", "makes", "banana", "coding", "makes"]
makes
coding

["practice", "make", "perfect", "coding", "make"]
practice
make

["practice", "make", "perfect", "coding", "make"]
practice
coding

["practice", "make", "perfect", "coding", "make"]
make
coding

["practice", "makes", "perfect", "coding", "makes", "perfect", "coding"]
makes
coding

["practice", "makes", "perfect", "coding", "makes"]
coding
practice

["practice", "make", "perfect", "coding", "coding"]
make
coding

["practice", "makes", "perfect", "coding", "makes"]
perfect
coding

["practice", "make", "perfect", "coding", "make"]
make
make

["makes", "makes", "coding", "coding"]
makes
coding

["practice", "make", "perfect", "coding", "make"]
coding
make

["practice", "makes", "perfect", "coding", "makes"]
makes
coding

["practice", "make", "perfect", "coding", "coding"]
coding
make

["practice", "makes", "perfect", "coding", "makes"]
practice
coding

["practice", "make", "perfect", "coding", "make"]
perfect
coding

["practice", "make", "perfect", "coding", "make"]
coding
practice

["practice", "make", "perfect", "coding", "make"]
make
perfect

["practice", "make", "perfect", "coding", "coding"]
coding
coding

["practice", "makes", "perfect", "coding", "makes"]
practice
perfect

["word1", "word2", "word1", "word2", "word1", "word2", "word1", "word2", "word1"]
word1
word2

["practice", "make", "perfect", "coding", "make"]
perfect
practice

["word1", "word2", "word1", "word2", "word1", "word2"]
word1
word2

["practice", "makes", "perfect", "coding", "coding"]
practice
coding

```java
public int shortestDistance(String[] wordsDict, String word1, String word2) {
    int index1 = -1, index2 = -1, minDistance = Integer.MAX_VALUE;
    for (int i = 0; i < wordsDict.length; ++i) {
        if (wordsDict[i].equals(word1)) { index1 = i; }
        if (wordsDict[i].equals(word2)) { index2 = i; }
        if (index1 != -1 && index2 != -1) {
            minDistance = Math.min(minDistance, Math.abs(index1 - index2));
        }
    }
    return minDistance;
}
```


```cpp
bool isStrobogrammatic(string num) {
    unordered_map<char, char> lookup {{'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}};
    int left = 0, right = num.size() - 1;
    while(left <= right) {
        if(lookup[num[left]] != num[right]) return false;
        left++;
        right--;
    }
    return true;
}
```

True True True True True True True True True True True True True True True True True

```python
def isStrobogrammatic(num: str) -> bool:
    lookup = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
    left, right = 0, len(num) - 1
    while left <= right:
        if num[left] not in lookup or lookup[num[left]] != num[right]:
            return False
        left += 1
        right -= 1
    return True
```


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

public List<String> findStrobogrammatic(int n) {
    return helper(n, n);
}

private List<String> helper(int n, int m) {
    if (n == 0) return new ArrayList<>(Arrays.asList(""));
    if (n == 1) return new ArrayList<>(Arrays.asList("0", "1", "8"));

    List<String> list = helper(n - 2, m);
    List<String> res = new ArrayList<>();

    for (int i = 0; i < list.size(); i++) {
        String s = list.get(i);

        if (n != m) res.add("0" + s + "0");

        res.add("1" + s + "1");
        res.add("6" + s + "9");
        res.add("8" + s + "8");
        res.add("9" + s + "6");
    }

    return res;
}
```


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

public List<List<String>> groupStrings(String[] strings) {
    Map<String, List<String>> map = new HashMap<>();

    for (String s : strings) {
        StringBuilder key = new StringBuilder();
        for (char c : s.toCharArray()) {
            key.append((c - s.charAt(0) + 26) % 26).append(",");
        }
        String keyStr = key.toString();
        map.putIfAbsent(keyStr, new ArrayList<>());
        map.get(keyStr).add(s);
    }

    return new ArrayList<>(map.values());
}
```

[['acegikm', 'bdfhjln'], ['ciefgkm'], ['aekm']]

```python
from collections import defaultdict

def groupStrings(strings):
    groups = defaultdict(list)

    for s in strings:
        key = tuple((ord(c) - ord(s[0])) % 26 for c in s)
        groups[key].append(s)

    return list(groups.values())
```


```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;
    }
}

class Solution {
    public int countUnivalSubtrees(TreeNode root) {
        return helper(root, new int[1]);
    }

    private boolean helper(TreeNode node, int[] count) {
        if (node == null) return true;

        boolean left = helper(node.left, count);
        boolean right = helper(node.right, count);

        if (left && right) {
            if (node.left != null && node.val != node.left.val) return false;
            if (node.right != null && node.val != node.right.val) return false;
            count[0]++;
            return true;
        }

        return false;
    }
}
```

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

class Solution {
public:
    int countUnivalSubtrees(TreeNode* root) {
        int count = 0;
        helper(root, count);
        return count;
    }

    bool helper(TreeNode* node, int& count) {
        if (!node) return true;

        bool left = helper(node->left, count);
        bool right = helper(node->right, count);

        if (left && right) {
            if (node->left && node->val != node->left->val) return false;
            if (node->right && node->val != node->right->val) return false;
            count++;
            return true;
        }

        return false;
    }
};
```


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

bool canAttendMeetings(std::vector<std::vector<int>>& intervals) {
    std::sort(intervals.begin(), intervals.end());

    for (int i = 1; i < intervals.size(); ++i) {
        if (intervals[i][0] < intervals[i - 1][1])
            return false;
    }

    return true;
}
```

true false true true false false true true true

```java
import java.util.Arrays;

public boolean canAttendMeetings(int[][] intervals) {
    Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));

    for (int i = 1; i < intervals.length; ++i) {
        if (intervals[i][0] < intervals[i - 1][1])
            return false;
    }

    return true;
}
```


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

public int minMeetingRooms(int[][] intervals) {
    if (intervals == null || intervals.length == 0) return 0;

    Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
    PriorityQueue<Integer> minHeap = new PriorityQueue<>();

    minHeap.add(intervals[0][1]);
    for (int i = 1; i < intervals.length; i++) {
        if (intervals[i][0] >= minHeap.peek()) {
            minHeap.poll();
        }
        minHeap.add(intervals[i][1]);
    }

    return minHeap.size();
}
```

```python
import heapq

def minMeetingRooms(intervals):
    if not intervals:
        return 0

    intervals.sort(key=lambda x: x[0])

    min_heap = [intervals[0][1]]
    for start, end in intervals[1:]:
        if start >= min_heap[0]:
            heapq.heappop(min_heap)
        heapq.heappush(min_heap, end)

    return len(min_heap)
```


```cpp
#include <vector>

void helper(int n, int start, std::vector<int>& path, std::vector<std::vector<int>>& result) {
    if (n == 1) {
        if (path.size() > 1) {
            result.push_back(path);
        }
        return;
    }

    for (int i = start; i <= n; ++i) {
        if (n % i == 0) {
            path.push_back(i);
            helper(n / i, i, path, result);
            path.pop_back();
        }
    }
}

std::vector<std::vector<int>> getFactors(int n) {
    std::vector<std::vector<int>> result;
    std::vector<int> path;
    helper(n, 2, path, result);
    return result;
}
```

```python
def getFactors(n):
    def helper(n, start, path, result):
        if n == 1:
            if len(path) > 1:
                result.append(path[:])
            return

        for i in range(start, n + 1):
            if n % i == 0:
                path.append(i)
                helper(n // i, i, path, result)
                path.pop()

    result = []
    helper(n, 2, [], result)
    return result
```


```java
public boolean isValidPreorder(int[] preorder) {
    Stack<Integer> stack = new Stack<>();
    int lowerBound = Integer.MIN_VALUE;
    for (int num : preorder) {
        if (num < lowerBound) return false;
        while (!stack.isEmpty() && num > stack.peek()) {
            lowerBound = stack.pop();
        }
        stack.push(num);
    }
    return true;
}
```

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

```cpp
bool isValidPreorder(vector<int>& preorder) {
    stack<int> stk;
    int lower_bound = INT_MIN;
    for (int num : preorder) {
        if (num < lower_bound) return false;
        while (!stk.empty() && num > stk.top()) {
            lower_bound = stk.top();
            stk.pop();
        }
        stk.push(num);
    }
    return true;
}
```


```python
def minCost(costs: List[List[int]]) -> int:
    if not costs:
        return 0
    for i in range(1, len(costs)):
        costs[i][0] += min(costs[i - 1][1], costs[i - 1][2])
        costs[i][1] += min(costs[i - 1][0], costs[i - 1][2])
        costs[i][2] += min(costs[i - 1][0], costs[i - 1][1])
    return min(costs[-1][0], costs[-1][1], costs[-1][2])
```

```java
public int minCost(int[][] costs) {
    if (costs.length == 0) return 0;
    for (int i = 1; i < costs.length; i++) {
        costs[i][0] += Math.min(costs[i - 1][1], costs[i - 1][2]);
        costs[i][1] += Math.min(costs[i - 1][0], costs[i - 1][2]);
        costs[i][2] += Math.min(costs[i - 1][0], costs[i - 1][1]);
    }
    return Math.min(costs[costs.length - 1][0], Math.min(costs[costs.length - 1][1], costs[costs.length - 1][2]));
}
```


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

def binary_tree_paths(root: TreeNode):
    if not root:
        return []
    if not root.left and not root.right:
        return [str(root.val)]
    paths = []
    for path in binary_tree_paths(root.left):
        paths.append(str(root.val) + "->" + path)
    for path in binary_tree_paths(root.right):
        paths.append(str(root.val) + "->" + path)
    return paths
```

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

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

std::vector<std::string> binaryTreePaths(TreeNode* root) {
    std::vector<std::string> paths;
    if (!root)
        return paths;
    if (!root->left && !root->right) {
        paths.push_back(std::to_string(root->val));
        return paths;
    }
    for (const std::string &path : binaryTreePaths(root->left)) {
      paths.push_back(std::to_string(root->val) + "->" + path);
    }
    for (const std::string &path : binaryTreePaths(root->right)) {
      paths.push_back(std::to_string(root->val) + "->" + path);
    }
    return paths;
}
```


```java
public int addDigits(int num) {
    return 1 + (num - 1) % 9;
}
```

```python
def addDigits(num: int) -> int:
    return 1 + (num - 1) % 9
```


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

```java
public int threeSumSmaller(int[] nums, int target) {
    int count = 0;
    Arrays.sort(nums);
    for (int i = 0; i < nums.length; ++i) {
        int j = i + 1, k = nums.length - 1;
        while (j < k) {
            if (nums[i] + nums[j] + nums[k] < target) {
                count += k - j;
                ++j;
            } else {
                --k;
            }
        }
    }
    return count;
}
```


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

public boolean isTree(int n, int[][] edges) {
    List<List<Integer>> neighbors = new ArrayList<>(n);
    for (int i = 0; i < n; i++) neighbors.add(new ArrayList<>());
    for (int[] edge : edges) {
        neighbors.get(edge[0]).add(edge[1]);
        neighbors.get(edge[1]).add(edge[0]);
    }
    boolean[] visited = new boolean[n];
    if(hasCycle(neighbors, visited, -1, 0)) return false;
    for (boolean visit : visited)
        if (!visit) return false;
    return true;
}

private boolean hasCycle(List<List<Integer>> neighbors, boolean[] visited, int parent, int node) {
    visited[node] = true;
    for (int neighbor : neighbors.get(node))
        if ((neighbor != parent && visited[neighbor]) || (!visited[neighbor] && hasCycle(neighbors, visited, node, neighbor))) return true;
    return false;
}
```

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

```python
from typing import List

def isTree(n: int, edges: List[List[int]]) -> bool:
    neighbors = [[] for _ in range(n)]
    for edge in edges:
        neighbors[edge[0]].append(edge[1])
        neighbors[edge[1]].append(edge[0])
    visited = [False] * n
    if hasCycle(neighbors, visited, -1, 0): return False
    return all(visited)

def hasCycle(neighbors: List[List[int]], visited: List[bool], parent: int, node: int) -> bool:
    visited[node] = True
    for neighbor in neighbors[node]:
        if (neighbor != parent and visited[neighbor]) or (not visited[neighbor] and hasCycle(neighbors, visited, node, neighbor)): return True
    return False
```


```python
def nthUglyNumber(n: int) -> int:
    ugly_numbers = [0] * n
    ugly_numbers[0] = 1
    i2, i3, i5 = 0, 0, 0

    for i in range(1, n):
        ugly_numbers[i] = min(ugly_numbers[i2] * 2, ugly_numbers[i3] * 3, ugly_numbers[i5] * 5)
        if ugly_numbers[i] == ugly_numbers[i2] * 2: i2 += 1
        if ugly_numbers[i] == ugly_numbers[i3] * 3: i3 += 1
        if ugly_numbers[i] == ugly_numbers[i5] * 5: i5 += 1

    return ugly_numbers[n - 1]

```

```java
public int nthUglyNumber(int n) {
    int[] uglyNumbers = new int[n];
    uglyNumbers[0] = 1;
    int i2 = 0, i3 = 0, i5 = 0;

    for (int i = 1; i < n; i++) {
        uglyNumbers[i] = Math.min(Math.min(uglyNumbers[i2] * 2, uglyNumbers[i3] * 3), uglyNumbers[i5] * 5);
        if (uglyNumbers[i] == uglyNumbers[i2] * 2) i2++;
        if (uglyNumbers[i] == uglyNumbers[i3] * 3) i3++;
        if (uglyNumbers[i] == uglyNumbers[i5] * 5) i5++;
    }

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


```cpp
int minCost(vector<vector<int>>& costs) {
    if (costs.empty()) return 0;

    int n = costs.size();
    int k = costs[0].size();

    for (int i = 1; i < n; ++i) {
        for (int j = 0; j < k; ++j) {
            int minCost = INT_MAX;
            for (int l = 0; l < k; ++l) {
                if (l == j) continue;
                minCost = min(minCost, costs[i - 1][l]);
            }
            costs[i][j] += minCost;
        }
    }
    return *min_element(costs[n - 1].begin(), costs[n - 1].end());
}
```

```java
public int minCost(int[][] costs) {
    if (costs == null || costs.length == 0) return 0;

    int n = costs.length;
    int k = costs[0].length;

    for (int i = 1; i < n; i++) {
        for (int j = 0; j < k; j++) {
            int minCost = Integer.MAX_VALUE;
            for (int l = 0; l < k; l++) {
                if (l == j) continue;
                minCost = Math.min(minCost, costs[i - 1][l]);
            }
            costs[i][j] += minCost;
        }
    }
    return Arrays.stream(costs[n - 1]).min().getAsInt();
}
```


```java
public int missingNumber(int[] nums) {
    int n = nums.length;
    int expectedSum = (n * (n + 1)) / 2;
    int actualSum = 0;
    for (int num : nums) {
        actualSum += num;
    }
    return expectedSum - actualSum;
}
```

```python
def missingNumber(nums):
    n = len(nums)
    expected_sum = (n * (n + 1)) // 2
    actual_sum = sum(nums)
    return expected_sum - actual_sum
```


```python
from collections import deque, defaultdict, Counter

def alienOrder(words):
    graph = defaultdict(set)
    in_degree = Counter({c: 0 for word in words for c in word})

    for word1, word2 in zip(words, words[1:]):
        found = False
        for c1, c2 in zip(word1, word2):
            if c1 != c2:
                if c2 not in graph[c1]:
                    graph[c1].add(c2)
                    in_degree[c2] += 1
                found = True
                break
        if not found and len(word1) > len(word2):
            return ""

    q = deque([c for c in in_degree if in_degree[c] == 0])
    result = []
    while q:
        c = q.popleft()
        result.append(c)

        for neigh in graph[c]:
            in_degree[neigh] -= 1
            if in_degree[neigh] == 0:
                q.append(neigh)

    if len(result) < len(in_degree):
        return ""

    return "".join(result)
```

words = \[ "wrt ", "wrf ", "er ", "ett ", "rftt "\]

a b c d e f g h i j k l m n o p q r s t u v w x y z

z y x w v u t s r q p o n m l k j i h g f e d c b a

"za"
"abc"
"rozafb"
"dmuetarkq"
""
"w ertf"
""
"edtsrpquvwxbycza"
""
"wertf"

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

std::string alienOrder(std::vector<std::string> &words) {
    std::unordered_map<char, std::unordered_set<char>> graph;
    std::unordered_map<char, int> inDegree;

    for (const std::string &word : words)
        for (char c : word)
            inDegree[c] = 0;

    for (int i = 0; i < words.size() - 1; i++) {
        std::string word1 = words[i], word2 = words[i + 1];

        bool found = false;
        for (int j = 0; j < std::min(word1.size(), word2.size()); j++) {
            char c1 = word1[j], c2 = word2[j];
            if (c1 != c2) {
                if (!graph[c1].count(c2)) {
                    graph[c1].insert(c2);
                    inDegree[c2]++;
                }
                found = true;
                break;
            }
        }

        if (!found && word1.size() > word2.size())
            return "";
    }

    std::queue<char> q;
    for (auto &[c, deg] : inDegree)
        if (deg == 0)
            q.push(c);

    std::string result;
    while (!q.empty()) {
        char c = q.front();
        q.pop();
        result += c;

        for (char neigh : graph[c]) {
            inDegree[neigh]--;
            if (inDegree[neigh] == 0)
                q.push(neigh);
        }
    }

    if (result.size() < inDegree.size())
        return "";

    return result;
}
```


```python
class Solution:
    def closestValue(self, root: TreeNode, target: float) -> int:
        closest = root.val
        while root:
            if abs(target - closest) > abs(target - root.val):
                closest = root.val
            root = root.left if target < root.val else root.right
        return closest
```

```cpp
class Solution {
public:
    int closestValue(TreeNode* root, double target) {
        int closest = root->val;
        while (root != nullptr) {
            if (abs(target - closest) > abs(target - root->val)) {
                closest = root->val;
            }
            root = target < root->val ? root->left : root->right;
        }
        return closest;
    }
};
```


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

class Solution {
public:
    std::string numberToWords(int num) {
        if (num == 0) return "Zero";
        std::string result;
        int i = 0;
        while (num > 0) {
            if (num % 1000 != 0) {
                result = helper(num % 1000) + THOUSANDS[i] + " " + result;
            }
            num /= 1000;
            i++;
        }
        return trim(result);
    }

private:
    std::vector<std::string> LESS_THAN_20 = {
        "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"
    };
    std::vector<std::string> TENS = {
        "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
    };
    std::vector<std::string> THOUSANDS = {
        "", "Thousand", "Million", "Billion"
    };

    std::string helper(int num) {
        if (num == 0) {
            return "";
        } else if (num < 20) {
            return LESS_THAN_20[num] + " ";
        } else if (num < 100) {
            return TENS[num / 10] + " " + helper(num % 10);
        } else {
            return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100);
        }
    }

    std::string trim(const std::string& str) {
        return str.substr(0, str.find_last_not_of(' ') + 1);
    }
};
```

One Hundred Twenty Three
One
One Thousand Twenty Three
Two Hundred Twenty Three
One Hundred
One Thousand Two
Two Thousand
Two Hundred Twenty One
Nine Hundred Ninety Nine
Two Hundred Twenty
One Thousand Two Hundred Eleven
One Hundred Eleven
One Thousand One Hundred Eleven
One Hundred Two
One Thousand One
Nine
Two Hundred Ninety Nine
One Thousand Two Hundred Ninety Nine
One Thousand Twenty One
Two Thousand Twenty Three
One Hundred Twenty Two
Ten
Two Hundred Two
One Thousand Two Hundred Two
Two Thousand Two
Zero
One Hundred Ninety Nine
One Hundred Twenty Three
Two Hundred
Two Thousand Twenty One
Two Thousand Eleven
Two Hundred Twenty Two
One Thousand One Hundred Ninety Nine
Two Thousand Twenty
One Hundred
Twenty
One Thousand Two Hundred
One Thousand Eleven
Twelve
Two Hundred Eleven
Two Thousand Ninety Nine
One Thousand Two Hundred Twenty
Ninety Nine
One Hundred One
One Thousand Two Hundred Twenty Three
One Hundred Twenty
Two Thousand Twenty Two
One Hundred Twenty One
One Hundred Twenty Three
Two Thousand One
One
One Thousand Two Hundred Twenty One
Two Hundred One
One Thousand Twenty Two
One Thousand Two Hundred One
One Thousand
One Thousand Two Hundred Twenty Two
One Thousand Twenty
Nineteen

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

public class Solution {
    private final String[] LESS_THAN_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private final String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    private final String[] THOUSANDS = {"", "Thousand", "Million", "Billion"};

    public String numberToWords(int num) {
        if (num == 0) return "Zero";
        StringBuilder result = new StringBuilder();
        int i = 0;
        while (num > 0) {
            if (num % 1000 != 0) {
                result.insert(0, helper(num % 1000) + THOUSANDS[i] + " ");
            }
            num /= 1000;
            i++;
        }
        return result.toString().trim();
    }

    private String helper(int num) {
        if (num == 0) {
            return "";
        } else if (num < 20) {
            return LESS_THAN_20[num] + " ";
        } else if (num < 100) {
            return TENS[num / 10] + " " + helper(num % 10);
        } else {
            return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100);
        }
    }
}
```


```cpp
int hIndex(vector<int>& citations) {
    sort(citations.begin(), citations.end(), greater<int>());
    int h = 0;
    for (int i = 0; i < citations.size(); ++i) {
        if (citations[i] >= i + 1) {
            h = i + 1;
        } else {
            break;
        }
    }
    return h;
}
```

```python
def hIndex(citations: List[int]) -> int:
    citations.sort(reverse=True)
    h = 0
    for i, citation in enumerate(citations):
        if citation >= i + 1:
            h = i + 1
        else:
            break
    return h
```


```cpp
int hIndex(vector<int>& citations) {
    int n = citations.size();
    int left = 0, right = n - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (citations[mid] == n - mid) {
            return n - mid;
        } else if (citations[mid] < n - mid) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return n - left;
}
```

```python
def hIndex(citations: List[int]) -> int:
    n = len(citations)
    left, right = 0, n - 1

    while left <= right:
        mid = left + (right - left) // 2
        if citations[mid] == n - mid:
            return n - mid
        elif citations[mid] < n - mid:
            left = mid + 1
        else:
            right = mid - 1

    return n - left
```


```cpp
int numWays(int n, int k) {
    if (n == 0) return 0;
    if (n == 1) return k;
    int same = k;
    int different = k * (k - 1);
    for (int i = 2; i < n; ++i) {
        int temp = different;
        different = (same + different) * (k - 1);
        same = temp;
    }
    return same + different;
}
```

```python
def numWays(n, k):
    if n == 0:
        return 0
    if n == 1:
        return k
    same = k
    different = k * (k - 1)
    for i in range(2, n):
        temp = different
        different = (same + different) * (k - 1)
        same = temp
    return same + different
```


```java
public int numSquares(int n) {
    int[] dp = new int[n + 1];
    Arrays.fill(dp, Integer.MAX_VALUE);
    dp[0] = 0;

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j * j <= i; j++) {
            dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
        }
    }

    return dp[n];
}
```

```python
def numSquares(n):
    dp = [float('inf')] * (n + 1)
    dp[0] = 0

    for i in range(1, n + 1):
        j = 1
        while j * j <= i:
            dp[i] = min(dp[i], dp[i - j * j] + 1)
            j += 1

    return dp[n]
```


```cpp
void wiggleSort(vector<int>& nums) {
    for (int i = 1; i < nums.size(); i++) {
        if (i%2 == 0 && nums[i] > nums[i-1] || i%2 == 1 && nums[i] < nums[i-1]) {
            swap(nums[i], nums[i-1]);
        }
    }
}
```

```python
def wiggleSort(nums):
    for i in range(1, len(nums)):
        if (i % 2 == 0 and nums[i] > nums[i-1]) or (i % 2 == 1 and nums[i] < nums[i-1]):
            nums[i], nums[i-1] = nums[i-1], nums[i]
```


```java
public void moveZeroes(int[] nums) {
    int index = 0;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] != 0) {
            nums[index++] = nums[i];
        }
    }
    for (int i = index; i < nums.length; i++) {
        nums[i] = 0;
    }
}
```

```python
def moveZeroes(nums):
    index = 0
    for i in range(len(nums)):
        if nums[i] != 0:
            nums[index] = nums[i]
            index += 1
    for i in range(index, len(nums)):
        nums[i] = 0
```


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

void wallsAndGates(vector<vector<int>>& rooms) {
    const int INF = 2147483647;
    int m = rooms.size();
    int n = rooms[0].size();
    queue<pair<int, int>> q;

    for(int i = 0; i < m; i++) {
        for(int j = 0; j < n; j++) {
            if(rooms[i][j] == 0) {
                q.push(make_pair(i, j));
            }
        }
    }

    int directions[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    while(!q.empty()) {
        int i = q.front().first;
        int j = q.front().second;
        q.pop();

        for(auto d : directions) {
            int ni = i + d[0];
            int nj = j + d[1];

            if(ni >= 0 && ni < m && nj >= 0 && nj < n && rooms[ni][nj] == INF) {
                rooms[ni][nj] = rooms[i][j] + 1;
                q.push(make_pair(ni, nj));
            }
        }
    }
}
```

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

public void wallsAndGates(int[][] rooms) {
    int m = rooms.length;
    int n = rooms[0].length;
    Queue<int[]> q = new LinkedList<>();
    int INF = 2147483647;

    for(int i = 0; i < m; i++) {
        for(int j = 0; j < n; j++) {
            if(rooms[i][j] == 0) {
                q.offer(new int[]{i, j});
            }
        }
    }

    int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    while(!q.isEmpty()) {
        int[] cur = q.poll();
        int i = cur[0];
        int j = cur[1];

        for(int[] d : directions) {
            int ni = i + d[0];
            int nj = j + d[1];

            if(ni >= 0 && ni < m && nj >= 0 && nj < n && rooms[ni][nj] == INF) {
                rooms[ni][nj] = rooms[i][j] + 1;
                q.offer(new int[]{ni, nj});
            }
        }
    }
}
```


```java
public int findDuplicate(int[] nums) {
    int slow = nums[0];
    int fast = nums[0];

    do {
        slow = nums[slow];
        fast = nums[nums[fast]];
    } while (slow != fast);

    slow = nums[0];

    while (slow != fast) {
        slow = nums[slow];
        fast = nums[fast];
    }

    return slow;
}
```

```cpp
int findDuplicate(vector<int>& nums) {
    int slow = nums[0];
    int fast = nums[0];

    do {
        slow = nums[slow];
        fast = nums[nums[fast]];
    } while (slow != fast);

    slow = nums[0];

    while (slow != fast) {
        slow = nums[slow];
        fast = nums[fast];
    }

    return slow;
}
```


```java
public int[][] gameOfLife(int[][] board) {
    int m = board.length;
    int n = board[0].length;
    int[][] result = new int[m][n];
    int[][] dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            int liveNeighbors = 0;

            for (int[] dir : dirs) {
                int newRow = i + dir[0];
                int newCol = j + dir[1];

                if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n && board[newRow][newCol] == 1) {
                    liveNeighbors++;
                }
            }

            if (board[i][j] == 1 && (liveNeighbors == 2 || liveNeighbors == 3)) {
                result[i][j] = 1;
            } else if (board[i][j] == 0 && liveNeighbors == 3) {
                result[i][j] = 1;
            }
        }
    }

    return result;
}
```

```cpp
#include <vector>

std::vector<std::vector<int>> gameOfLife(std::vector<std::vector<int>>& board) {
    int m = board.size();
    int n = board[0].size();
    std::vector<std::vector<int>> result(m, std::vector<int>(n, 0));

    std::vector<std::vector<int>> dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            int liveNeighbors = 0;

            for (std::vector<int> dir : dirs) {
                int newRow = i + dir[0];
                int newCol = j + dir[1];

                if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n && board[newRow][newCol] == 1) {
                    liveNeighbors++;
                }
            }

            if (board[i][j] == 1 && (liveNeighbors == 2 || liveNeighbors == 3)) {
                result[i][j] = 1;
            } else if (board[i][j] == 0 && liveNeighbors == 3) {
                result[i][j] = 1;
            }
        }
    }

    return result;
}
```


```cpp
bool wordPatternMatch(string pattern, string s) {
    unordered_map<char, string> pattern_map;
    unordered_set<string> words;
    return backtrack(pattern, 0, s, 0, pattern_map, words);
}

bool backtrack(string& pattern, int p_index, string& s, int s_index, unordered_map<char, string>& pattern_map, unordered_set<string>& words) {
    if (p_index == pattern.size() && s_index == s.size()) return true;
    if (p_index == pattern.size() || s_index == s.size()) return false;

    char p = pattern[p_index];
    if (pattern_map.count(p)) {
        string word = pattern_map[p];
        if (s.substr(s_index, word.size()) != word) return false;
        return backtrack(pattern, p_index + 1, s, s_index + word.size(), pattern_map, words);
    } else {
        for (int length = 1; length <= s.size() - s_index; length++) {
            string word = s.substr(s_index, length);
            if (words.count(word)) continue;
            pattern_map[p] = word;
            words.insert(word);
            if (backtrack(pattern, p_index + 1, s, s_index + length, pattern_map, words)) return true;
            pattern_map.erase(p);
            words.erase(word);
        }
    }
    return false;
}
```

pattern =  "abab ", s =  "redblueredblue "

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

```python
def wordPatternMatch(pattern: str, s: str) -> bool:
    def backtrack(p_index, s_index, pattern_map, words):
        if p_index == len(pattern) and s_index == len(s):
            return True
        if p_index == len(pattern) or s_index == len(s):
            return False

        p = pattern[p_index]
        if p in pattern_map:
            word = pattern_map[p]
            if not s.startswith(word, s_index):
                return False
            return backtrack(p_index + 1, s_index + len(word), pattern_map, words)
        else:
            for length in range(1, len(s) - s_index + 1):
                word = s[s_index : s_index + length]
                if word in words:
                    continue
                pattern_map[p] = word
                words.add(word)
                if backtrack(p_index + 1, s_index + length, pattern_map, words):
                    return True
                pattern_map.pop(p)
                words.remove(word)
        return False

    return backtrack(0, 0, {}, set())
```


```python
def canWinNim(n):
    return n % 4 != 0
```

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

```java
public boolean canWinNim(int n) {
    return n % 4 != 0;
}
```


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

std::vector<std::string> generatePossibleNextMoves(std::string currentState) {
    std::vector<std::string> result;
    for (int i = 1; i < currentState.size(); ++i) {
        if (currentState[i] == '+' && currentState[i - 1] == '+') {
            currentState[i] = currentState[i - 1] = '-';
            result.push_back(currentState);
            currentState[i] = currentState[i - 1] = '+';
        }
    }
    return result;
}
```

```python
def generate_possible_next_moves(current_state):
    result = []
    for i in range(1, len(current_state)):
        if current_state[i] == '+' and current_state[i - 1] == '+':
            result.append(current_state[:i - 1] + '--' + current_state[i + 1:])
    return result
```


```python
def canWin(currentState: str) -> bool:
    for i in range(len(currentState) - 1):
        if currentState[i] == '+' and currentState[i + 1] == '+':
            temp = currentState[:i] + "--" + currentState[i + 2:]
            if not canWin(temp):
                return True
    return False
```

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

```java
public boolean canWin(String currentState) {
    for (int i = 0; i < currentState.length() - 1; ++i) {
        if (currentState.charAt(i) == '+' && currentState.charAt(i + 1) == '+') {
            String temp = currentState.substring(0, i) + "--" + currentState.substring(i + 2);
            if (!canWin(temp)) return true;
        }
    }
    return false;
}
```


```java
public int minTotalDistance(int[][] grid) {
    List<Integer> rows = new ArrayList<Integer>();
    List<Integer> cols = new ArrayList<Integer>();
    int m = grid.length, n = grid[0].length;
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (grid[i][j] == 1) {
                rows.add(i);
                cols.add(j);
            }
        }
    }
    Collections.sort(cols);
    int row_median = rows.get(rows.size() / 2), col_median = cols.get(cols.size() / 2);
    int distance = 0;
    for (int i : rows) distance += Math.abs(i - row_median);
    for (int j : cols) distance += Math.abs(j - col_median);
    return distance;
}
```

```cpp
int minTotalDistance(vector<vector<int>>& grid) {
    vector<int> rows, cols;
    int m = grid.size(), n = grid[0].size();
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (grid[i][j]) {
                rows.push_back(i);
                cols.push_back(j);
            }
        }
    }
    sort(cols.begin(), cols.end());
    int row_median = rows[rows.size() / 2], col_median = cols[cols.size() / 2];
    int distance = 0;
    for (int i : rows) distance += abs(i - row_median);
    for (int j : cols) distance += abs(j - col_median);
    return distance;
}
```


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

def longest_consecutive_sequence(root, longest_path):
    if root is None:
        return 0
    left = longest_consecutive_sequence(root.left, longest_path)
    right = longest_consecutive_sequence(root.right, longest_path)
    curr_path = 1
    if root.left and root.left.val == root.val + 1:
        curr_path = max(curr_path, left + 1)
    if root.right and root.right.val == root.val + 1:
        curr_path = max(curr_path, right + 1)
    longest_path[0] = max(longest_path[0], curr_path)
    return curr_path

def longest_consecutive(root):
    longest_path = [0]
    longest_consecutive_sequence(root, longest_path)
    return longest_path[0]
```

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

public int longestConsecutiveSequence(TreeNode root, int[] longestPath) {
    if (root == null) {
        return 0;
    }
    int left = longestConsecutiveSequence(root.left, longestPath);
    int right = longestConsecutiveSequence(root.right, longestPath);
    int currPath = 1;
    if (root.left != null && root.left.val == root.val + 1) {
        currPath = Math.max(currPath, left + 1);
    }
    if (root.right != null && root.right.val == root.val + 1) {
        currPath = Math.max(currPath, right + 1);
    }
    longestPath[0] = Math.max(longestPath[0], currPath);
    return currPath;
}

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


```java
public int lengthOfLIS(int[] nums) {
    int[] dp = new int[nums.length];
    int max_length = 1;
    Arrays.fill(dp, 1);
    for (int i = 1; i < nums.length; i++) {
        for (int j = 0; j < i; j++) {
            if (nums[i] > nums[j]) {
                dp[i] = Math.max(dp[i], dp[j] + 1);
            }
        }
        max_length = Math.max(max_length, dp[i]);
    }
    return max_length;
}
```

```cpp
int lengthOfLIS(vector<int>& nums) {
    vector<int> dp(nums.size(), 1);
    int max_length = 1;
    for (int i = 1; i < nums.size(); i++) {
        for (int j = 0; j < i; j++) {
            if (nums[i] > nums[j]) {
                dp[i] = max(dp[i], dp[j] + 1);
            }
        }
        max_length = max(max_length, dp[i]);
    }
    return max_length;
}
```


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

using namespace std;

class Solution {
public:
    vector<string> removeInvalidParentheses(string s) {
        set<string> visited;
        queue<string> q;
        vector<string> result;
        bool found = false;

        visited.insert(s);
        q.push(s);

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

            if (isValid(cur)) {
                found = true;
                result.push_back(cur);
            }

            if (found) continue;

            for (int i = 0; i < cur.length(); ++i) {
                if (cur[i] == '(' || cur[i] == ')') {
                    string next = cur.substr(0, i) + cur.substr(i+1);
                    if (visited.find(next) == visited.end()) {
                        visited.insert(next);
                        q.push(next);
                    }
                }
            }
        }
        return result;
    }

    bool isValid(const string &s) {
        int count = 0;
        for (char c : s) {
            if (c == '(') count++;
            if (c == ')') count--;
            if (count < 0) return false;
        }
        return count == 0;
    }
};
```

```java
import java.util.*;

class Solution {
    public List<String> removeInvalidParentheses(String s) {
        Set<String> visited = new HashSet<>();
        Queue<String> queue = new LinkedList<>();
        List<String> result = new ArrayList<>();
        boolean found = false;

        visited.add(s);
        queue.offer(s);

        while (!queue.isEmpty()) {
            String current = queue.poll();

            if (isValid(current)) {
                found = true;
                result.add(current);
            }

            if (found) continue;

            for (int i = 0; i < current.length(); i++) {
                if (current.charAt(i) == '(' || current.charAt(i) == ')') {
                    String next = current.substring(0, i) + current.substring(i + 1);
                    if (!visited.contains(next)) {
                        visited.add(next);
                        queue.offer(next);
                    }
                }
            }
        }
        return result;
    }

    private boolean isValid(String s) {
        int count = 0;
        for (char c : s.toCharArray()) {
            if (c == '(') count++;
            if (c == ')') count--;
            if (count < 0) return false;
        }
        return count == 0;
    }
}
```


```java
public int minArea(char[][] image, int x, int y) {
    int top = x, bottom = x, left = y, right = y;
    for (int i = 0; i < image.length; ++i) {
        for (int j = 0; j < image[i].length; ++j) {
            if (image[i][j] == '1') {
                top = Math.min(top, i);
                bottom = Math.max(bottom, i);
                left = Math.min(left, j);
                right = Math.max(right, j);
            }
        }
    }
    return (bottom - top + 1) * (right - left + 1);
}
```

```python
def minArea(image, x, y):
    top, bottom, left, right = x, x, y, y
    for i, row in enumerate(image):
        for j, cell in enumerate(row):
            if cell == '1':
                top, bottom = min(top, i), max(bottom, i)
                left, right = min(left, j), max(right, j)
    return (bottom - top + 1) * (right - left + 1)
```


```cpp
#include <vector>

using namespace std;

vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {
    vector<int> roots(m * n, -1);
    vector<vector<int>> dirs{{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
    int islandCount = 0;
    vector<int> result;

    auto getIndex = [&](int i, int j){
        return i * n + j;
    };

    function<int(int)> findRoot = [&](int x) {
        if (roots[x] != x) {
            roots[x] = findRoot(roots[x]);
        }
        return roots[x];
    };

    for(const auto& position : positions) {
        int i = position[0], j = position[1], index = getIndex(i, j);
        if (roots[index] != -1) {
            result.push_back(islandCount);
            continue;
        }
        islandCount++;
        roots[index] = index;
        for (const auto& dir : dirs) {
            int ni = i + dir[0], nj = j + dir[1], neighbor = getIndex(ni, nj);
            if (ni >= 0 && ni < m && nj >= 0 && nj < n && roots[neighbor] != -1) {
                int rootNb = findRoot(neighbor);
                if (index != rootNb) {
                    roots[rootNb] = index;
                    islandCount--;
                }
            }
        }
        result.push_back(islandCount);
    }
    return result;
}
```

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

public List<Integer> numIslands2(int m, int n, int[][] positions) {
    int[] roots = new int[m * n];
    Arrays.fill(roots, -1);
    int[][] dirs = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
    int islandCount = 0;
    List<Integer> result = new ArrayList<>();

    for (int[] position : positions) {
        int i = position[0], j = position[1], index = i * n + j;
        if (roots[index] != -1) {
            result.add(islandCount);
            continue;
        }
        islandCount++;
        roots[index] = index;
        for (int[] dir : dirs) {
            int ni = i + dir[0], nj = j + dir[1], neighbor = ni * n + nj;
            if (ni >= 0 && ni < m && nj >= 0 && nj < n && roots[neighbor] != -1) {
                int rootNb = find(roots, neighbor);
                if (index != rootNb) {
                    roots[rootNb] = index;
                    islandCount--;
                }
            }
        }
        result.add(islandCount);
    }
    return result;
}

private int find(int[] roots, int x) {
    if (roots[x] != x) roots[x] = find(roots, roots[x]);
    return roots[x];
}
```


```java
public int maxProfit(int[] prices) {
    int profit = 0;
    for (int i = 1; i < prices.length; i++) {
        profit += Math.max(prices[i] - prices[i - 1], 0);
    }
    return profit;
}
```

```python
def maxProfit(prices):
    profit = 0
    for i in range(1, len(prices)):
        profit += max(prices[i] - prices[i - 1], 0)
    return profit
```


```python
from collections import deque
from typing import List

def find_min_height_trees(n: int, edges: List[List[int]]) -> List[int]:
    if n == 1:
        return [0]

    adj_list = [set() for _ in range(n)]
    for a, b in edges:
        adj_list[a].add(b)
        adj_list[b].add(a)

    leaves = deque(i for i in range(n) if len(adj_list[i]) == 1)

    while n > 2:
        leaves_size = len(leaves)
        n -= leaves_size
        for _ in range(leaves_size):
            leaf = leaves.popleft()
            for neighbor in adj_list[leaf]:
                adj_list[neighbor].remove(leaf)
                if len(adj_list[neighbor]) == 1:
                    leaves.append(neighbor)

    return list(leaves)
```

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

vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
    if (n == 1) return {0};

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

    queue<int> q;
    for (int i = 0; i < n; ++i) {
        if (degrees[i] == 1) q.push(i);
    }

    while (n > 2) {
        int leaves_size = q.size();
        n -= leaves_size;
        for (int i = 0; i < leaves_size; i++) {
            int leaf = q.front(); q.pop();
            for (int neighbor : adjList[leaf]) {
                if (--degrees[neighbor] == 1) q.push(neighbor);
            }
        }
    }

    vector<int> result;
    while (!q.empty()) {
        result.push_back(q.front());
        q.pop();
    }

    return result;
}
```


```java
public int[][] multiply(int[][] mat1, int[][] mat2) {
    int m = mat1.length;
    int k = mat1[0].length;
    int n = mat2[0].length;
    int[][] result = new int[m][n];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < k; j++) {
            if (mat1[i][j] != 0) {
                for (int l = 0; l < n; l++) {
                    result[i][l] += mat1[i][j] * mat2[j][l];
                }
            }
        }
    }
    return result;
}
```

```python
def multiply(mat1, mat2):
    m, k, n = len(mat1), len(mat1[0]), len(mat2[0])
    result = [[0] * n for _ in range(m)]
    for i in range(m):
        for j in range(k):
            if mat1[i][j] != 0:
                for l in range(n):
                    result[i][l] += mat1[i][j] * mat2[j][l]
    return result
```


```python
def maxCoins(nums):
    nums = [1] + nums + [1]
    n = len(nums)
    dp = [[0] * n for _ in range(n)]

    for length in range(1, n - 1):
        for left in range(1, n - length):
            right = left + length - 1
            for i in range(left, right + 1):
                dp[left][right] = max(dp[left][right], nums[left - 1] * nums[i] * nums[right + 1] + dp[left][i - 1] + dp[i + 1][right])

    return dp[1][n - 2]
```

```java
public int maxCoins(int[] nums) {
    int n = nums.length;
    int[] newNums = new int[n + 2];
    newNums[0] = 1;
    newNums[n + 1] = 1;
    for (int i = 1; i <= n; i++) {
        newNums[i] = nums[i - 1];
    }

    int[][] dp = new int[n + 2][n + 2];
    for (int len = 1; len <= n; len++) {
        for (int left = 1; left <= n - len + 1; left++) {
            int right = left + len - 1;
            for (int i = left; i <= right; i++) {
                dp[left][right] = Math.max(dp[left][right], newNums[left - 1] * newNums[i] * newNums[right + 1] + dp[left][i - 1] + dp[i + 1][right]);
            }
        }
    }

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


```python
def nthSuperUglyNumber(n, primes):
    ugly = [0] * n
    ugly[0] = 1
    indices = [0] * len(primes)

    for i in range(1, n):
        min_val = float("inf")

        for j in range(len(primes)):
            min_val = min(min_val, ugly[indices[j]] * primes[j])

        ugly[i] = min_val

        for j in range(len(primes)):
            if ugly[i] == ugly[indices[j]] * primes[j]:
                indices[j] += 1

    return ugly[-1]
```

```cpp
int nthSuperUglyNumber(int n, vector<int>& primes) {
    vector<int> ugly(n);
    ugly[0] = 1;
    vector<int> indices(primes.size(), 0);

    for (int i = 1; i < n; i++) {
        int min_val = INT_MAX;

        for (int j = 0; j < primes.size(); j++)
            min_val = min(min_val, ugly[indices[j]] * primes[j]);

        ugly[i] = min_val;

        for (int j = 0; j < primes.size(); j++)
            if (ugly[i] == ugly[indices[j]] * primes[j])
                indices[j]++;
    }

    return ugly.back();
}
```


```python
def countSmaller(nums):
    def merge_sort(indices):
        if len(indices) <= 1:
            return indices
        mid = len(indices) // 2
        left = merge_sort(indices[:mid])
        right = merge_sort(indices[mid:])
        return merge(left, right)

    def merge(left, right):
        merged, count = [], 0
        while left and right:
            if nums[left[0]] <= nums[right[0]]:
                counts[left[0]] += count
                merged.append(left.pop(0))
            else:
                count += len(left)
                merged.append(right.pop(0))
        for i in left:
            counts[i] += count
        return merged + left + right

    counts = [0] * len(nums)
    merge_sort(list(range(len(nums))))
    return counts
```

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

public List<Integer> countSmaller(int[] nums) {
    int n = nums.length;
    int[] indices = new int[n];
    int[] counts = new int[n];

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

    mergeSort(nums, indices, counts, 0, n - 1);
    List<Integer> result = new ArrayList<>();
    for (int count : counts) {
        result.add(count);
    }
    return result;
}

private void mergeSort(int[] nums, int[] indices, int[] counts, int left, int right) {
    if (left >= right) {
        return;
    }

    int mid = left + (right - left) / 2;
    mergeSort(nums, indices, counts, left, mid);
    mergeSort(nums, indices, counts, mid + 1, right);

    int[] temp = new int[right - left + 1];
    int i = left, j = mid + 1, k = 0;
    while (i <= mid && j <= right) {
        if (nums[indices[i]] <= nums[indices[j]]) {
            counts[indices[i]] += j - mid - 1;
            temp[k++] = indices[i++];
        } else {
            temp[k++] = indices[j++];
        }
    }

    while (i <= mid) {
        counts[indices[i]] += j - mid - 1;
        temp[k++] = indices[i++];
    }

    while (j <= right) {
        temp[k++] = indices[j++];
    }

    System.arraycopy(temp, 0, indices, left, right - left + 1);
}
```


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

using namespace std;

int shortestDistance(vector<vector<int>>& grid) {
    int m = grid.size();
    int n = grid[0].size();

    vector<vector<int>> total_count(m, vector<int>(n, 0));
    vector<vector<int>> dist_sum(m, vector<int>(n, 0));
    int house_count = 0;

    int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (grid[i][j] == 1) {
                house_count++;
                queue<pair<int, int>> q;
                q.push({i, j});
                vector<vector<bool>> visited(m, vector<bool>(n, false));
                int level = 1;
                while (!q.empty()) {
                    int sz = q.size();
                    for (int q_i = 0; q_i < sz; q_i++) {
                        int x = q.front().first;
                        int y = q.front().second;
                        q.pop();
                        for (auto &dir : dirs) {
                            int x_new = x + dir[0];
                            int y_new = y + dir[1];
                            if (x_new >= 0 && x_new < m && y_new >= 0 && y_new < n && !visited[x_new][y_new] && grid[x_new][y_new] == 0) {
                                visited[x_new][y_new] = true;
                                q.push({x_new, y_new});
                                dist_sum[x_new][y_new] += level;
                                total_count[x_new][y_new]++;
                            }
                        }
                    }
                    level++;
                }
            }
        }
    }

    int min_dist = INT_MAX;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (total_count[i][j] == house_count) {
                min_dist = min(min_dist, dist_sum[i][j]);
            }
        }
    }

    return min_dist == INT_MAX ? -1 : min_dist;
}
```

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

public int shortestDistance(int[][] grid) {
    int m = grid.length;
    int n = grid[0].length;

    int[][] total_count = new int[m][n];
    int[][] dist_sum = new int[m][n];
    int house_count = 0;

    int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (grid[i][j] == 1) {
                house_count++;
                Queue<int[]> q = new LinkedList<>();
                q.offer(new int[]{i, j});
                boolean[][] visited = new boolean[m][n];
                int level = 1;
                while (!q.isEmpty()) {
                    int sz = q.size();
                    for (int q_i = 0; q_i < sz; q_i++) {
                        int[] cur = q.poll();
                        int x = cur[0];
                        int y = cur[1];
                        for (int[] dir : dirs) {
                            int x_new = x + dir[0];
                            int y_new = y + dir[1];
                            if (x_new >= 0 && x_new < m && y_new >= 0 && y_new < n && !visited[x_new][y_new] && grid[x_new][y_new] == 0) {
                                visited[x_new][y_new] = true;
                                q.offer(new int[]{x_new, y_new});
                                dist_sum[x_new][y_new] += level;
                                total_count[x_new][y_new]++;
                            }
                        }
                    }
                    level++;
                }
            }
        }
    }

    int min_dist = Integer.MAX_VALUE;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (total_count[i][j] == house_count) {
                min_dist = Math.min(min_dist, dist_sum[i][j]);
            }
        }
    }

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


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

int maxProduct(std::vector<std::string>& words) {
    int n = words.size();
    std::vector<int> mask(n, 0);
    for (int i = 0; i < n; ++i) {
        for (char c : words[i]) {
            mask[i] |= (1 << (c - 'a'));
        }
    }

    int max_product = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            if ((mask[i] & mask[j]) == 0) {
                max_product = std::max(max_product, int(words[i].length() * words[j].length()));
            }
        }
    }

    return max_product;
}
```

words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\]

redapple greenbanana yellowcherry purpledate

applepie orangepizza pearmilkshake grapejuice

redapplejuice
greenbanana smoothie
yellowcherry sorbet
purpledate cake

hellofriend goodbyefoe farewellwishes adiosamigo

```java
import java.util.*;

class Solution {
    public int maxProduct(String[] words) {
        int n = words.length;
        int[] mask = new int[n];
        for (int i = 0; i < n; i++) {
            for (char c : words[i].toCharArray()) {
                mask[i] |= (1 << (c - 'a'));
            }
        }

        int maxProduct = 0;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if ((mask[i] & mask[j]) == 0) {
                    maxProduct = Math.max(maxProduct, words[i].length() * words[j].length());
                }
            }
        }

        return maxProduct;
    }
}
```


```java
public int bulbSwitch(int n) {
    return (int)Math.sqrt(n);
}
```

```python
def bulbSwitch(n):
    return int(n**0.5)
```


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

int coinChange(std::vector<int>& coins, int amount) {
    std::vector<int> dp(amount + 1, amount + 1);
    dp[0] = 0;

    for (int i = 0; i < coins.size(); i++) {
        for (int j = coins[i]; j <= amount; j++) {
            dp[j] = std::min(dp[j], dp[j - coins[i]] + 1);
        }
    }

    return dp[amount] <= amount ? dp[amount] : -1;
}
```

```java
public int coinChange(int[] coins, int amount) {
    int[] dp = new int[amount + 1];
    Arrays.fill(dp, amount + 1);
    dp[0] = 0;

    for (int coin : coins) {
        for (int i = coin; i <= amount; i++) {
            dp[i] = Math.min(dp[i], dp[i - coin] + 1);
        }
    }

    return dp[amount] <= amount ? dp[amount] : -1;
}
```


```cpp
#include <vector>

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

    std::vector<bool> visited(n, false);
    int connectedComponents = 0;

    for (int i = 0; i < n; ++i) {
        if (!visited[i]) {
            std::function<void(int)> dfs = [&](int node) {
                visited[node] = true;
                for (int neighbor : adjList[node]) {
                    if (!visited[neighbor]) {
                        dfs(neighbor);
                    }
                }
            };
            dfs(i);
            connectedComponents++;
        }
    }
    return connectedComponents;
}
```

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

public int countComponents(int n, int[][] edges) {
    List<List<Integer>> adjList = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        adjList.add(new ArrayList<>());
    }
    for (int[] edge : edges) {
        adjList.get(edge[0]).add(edge[1]);
        adjList.get(edge[1]).add(edge[0]);
    }

    boolean[] visited = new boolean[n];
    int connectedComponents = 0;

    for (int i = 0; i < n; i++) {
        if (!visited[i]) {
            dfs(i, visited, adjList);
            connectedComponents++;
        }
    }
    return connectedComponents;
}

void dfs(int node, boolean[] visited, List<List<Integer>> adjList) {
    visited[node] = true;
    for (int neighbor : adjList.get(node)) {
        if (!visited[neighbor]) {
            dfs(neighbor, visited, adjList);
        }
    }
}
```


```java
import java.util.Arrays;
public void wiggleSort(int[] nums) {
    Arrays.sort(nums);
    for (int i = 1; i < nums.length - 1; i += 2) {
        int temp = nums[i];
        nums[i] = nums[i + 1];
        nums[i + 1] = temp;
    }
}
```

```cpp
#include <algorithm>
void wiggleSort(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    for (int i = 1; i < nums.size() - 1; i += 2) {
        swap(nums[i], nums[i + 1]);
    }
}
```


```cpp
int maxSubArrayLen(vector<int>& nums, int k) {
    unordered_map<int, int> sumIndex;
    int maxLength = 0, sum = 0;
    for(int i = 0; i < nums.size(); i++) {
        sum += nums[i];
        if(sum == k) maxLength = i + 1;
        if(sumIndex.count(sum - k)) maxLength = max(maxLength, i - sumIndex[sum - k]);
        if(!sumIndex.count(sum)) sumIndex[sum] = i;
    }
    return maxLength;
}
```

```java
public int maxSubArrayLen(int[] nums, int k) {
    Map<Integer, Integer> sumIndex = new HashMap<>();
    int maxLength = 0, sum = 0;
    for(int i = 0; i < nums.length; i++) {
        sum += nums[i];
        if (sum == k) maxLength = i + 1;
        if (sumIndex.containsKey(sum - k)) maxLength = Math.max(maxLength, i - sumIndex.get(sum - k));
        if (!sumIndex.containsKey(sum)) sumIndex.put(sum, i);
    }
    return maxLength;
}
```


```python
def countRangeSum(nums, lower, upper):
    sums = [0] * (len(nums) + 1)
    for i in range(len(nums)):
        sums[i + 1] = sums[i] + nums[i]

    def mergeSort(start, end):
        if start == end:
            return 0
        mid = start + (end - start) // 2
        count = mergeSort(start, mid) + mergeSort(mid + 1, end)

        j, k = mid + 1, mid + 1
        for i in range(start, mid + 1):
            while j <= end and sums[j] - sums[i] < lower: j += 1
            while k <= end and sums[k] - sums[i] <= upper: k += 1
            count += k - j

        sums[start:end + 1] = sorted(sums[start:end + 1])
        return count

    return mergeSort(0, len(nums))
```

```java
public int countRangeSum(int[] nums, int lower, int upper) {
    long[] sums = new long[nums.length + 1];
    for (int i = 0; i < nums.length; ++i)
        sums[i + 1] = sums[i] + nums[i];

    return countWhileMergeSort(sums, lower, upper, 0, nums.length);
}

private int countWhileMergeSort(long[] sums, int lower, int upper, int start, int end) {
    if (start >= end)
        return 0;

    int mid = start + (end - start) / 2;
    int count = countWhileMergeSort(sums, lower, upper, start, mid) + countWhileMergeSort(sums, lower, upper, mid + 1, end);

    int j = mid + 1, k = mid + 1;
    for (int i = start; i <= mid; ++i) {
        while (j <= end && sums[j] - sums[i] < lower) ++j;
        while (k <= end && sums[k] - sums[i] <= upper) ++k;
        count += k - j;
    }

    Arrays.sort(sums, start, end + 1);
    return count;
}
```


```cpp
struct ListNode {
     int val;
     ListNode *next;
     ListNode() : val(0), next(nullptr) {}
     ListNode(int x) : val(x), next(nullptr) {}
     ListNode(int x, ListNode *next) : val(x), next(next) {}
};

ListNode* oddEvenList(ListNode* head) {
    if (!head) return nullptr;
    ListNode *odd = head, *even = head->next, *even_head = even;
    while (even && even->next) {
        odd->next = even->next;
        odd = odd->next;
        even->next = odd->next;
        even = even->next;
    }
    odd->next = even_head;
    return head;
}
```

```java
public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

public ListNode oddEvenList(ListNode head) {
    if (head == null) return null;
    ListNode odd = head, even = head.next, evenHead = even;
    while (even != null && even.next != null) {
        odd.next = even.next;
        odd = odd.next;
        even.next = odd.next;
        even = even.next;
    }
    odd.next = evenHead;
    return head;
}
```


```python
dx = (0, 0, 1, -1)
dy = (1, -1, 0, 0)

def dfs(matrix, memo, i, j):
    if memo[i][j] != 0:
        return memo[i][j]

    max_len = 0
    for k in range(4):
        ni, nj = i + dx[k], j + dy[k]
        if (0 <= ni < len(matrix) and 0 <= nj < len(matrix[0]) and matrix[ni][nj] > matrix[i][j]):
            max_len = max(max_len, dfs(matrix, memo, ni, nj))

    memo[i][j] = max_len + 1
    return memo[i][j]

def longest_increasing_path(matrix):
    m, n = len(matrix), len(matrix[0])

    memo = [[0] * n for _ in range(m)]

    ans = 0
    for i in range(m):
        for j in range(n):
            ans = max(ans, dfs(matrix, memo, i, j))

    return ans
```

```java
int[] dx = {0, 0, 1, -1};
int[] dy = {1, -1, 0, 0};

public int dfs(int[][] matrix, int[][] memo, int i, int j) {
    if (memo[i][j] != 0) return memo[i][j];

    int max_len = 0;
    for (int k = 0; k < 4; ++k) {
        int ni = i + dx[k], nj = j + dy[k];
        if (ni >= 0 && ni < matrix.length && nj >= 0 && nj < matrix[0].length && matrix[ni][nj] > matrix[i][j]) {
            max_len = Math.max(max_len, dfs(matrix, memo, ni, nj));
        }
    }

    memo[i][j] = max_len + 1;
    return memo[i][j];
}

public int longestIncreasingPath(int[][] matrix) {
    int m = matrix.length, n = matrix[0].length;

    int[][] memo = new int[m][n];

    int ans = 0;
    for (int i = 0; i < m; ++i)
        for (int j = 0; j < n; ++j)
            ans = Math.max(ans, dfs(matrix, memo, i, j));

    return ans;
}
```


```java
public int minPatches(int[] nums, int n) {
    long maxSum = 0;
    int patches = 0, i = 0;

    while (maxSum < n) {
        if (i < nums.length && nums[i] <= maxSum + 1) {
            maxSum += nums[i];
            i++;
        } else {
            maxSum += maxSum + 1;
            patches++;
        }
    }
    return patches;
}
```

```python
def minPatches(nums, n):
    max_sum = 0
    patches = 0
    i = 0

    while max_sum < n:
        if i < len(nums) and nums[i] <= max_sum + 1:
            max_sum += nums[i]
            i += 1
        else:
            max_sum += max_sum + 1
            patches += 1

    return patches
```


```java
public boolean isValidSerialization(String preorder) {
    String[] nodes = preorder.split(",");
    int node_count = 1;

    for (String node : nodes) {
        node_count--;

        if (node_count < 0) return false;
        if (!node.equals("#")) node_count += 2;
    }

    return node_count == 0;
}
```

True False True True True True False False False

```python
def is_valid_serialization(preorder: str) -> bool:
    nodes = preorder.split(',')
    node_count = 1

    for node in nodes:
        node_count -= 1
        if node_count < 0:
            return False
        if node != '#':
            node_count += 2

    return node_count == 0
```


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

class TreeInfo {
    boolean isBST;
    int size;
    int minValue;
    int maxValue;

    TreeInfo(boolean isBST, int size, int minValue, int maxValue) {
        this.isBST = isBST;
        this.size = size;
        this.minValue = minValue;
        this.maxValue = maxValue;
    }
}

public int largestBSTSubtree(TreeNode root) {
    return largestBSTUtil(root, new int[1]).size;
}

private TreeInfo largestBSTUtil(TreeNode root, int[] largestBST) {
    if (root == null) return new TreeInfo(true, 0, Integer.MAX_VALUE, Integer.MIN_VALUE);

    TreeInfo left = largestBSTUtil(root.left, largestBST);
    TreeInfo right = largestBSTUtil(root.right, largestBST);

    if (left.isBST && root.val > left.maxValue && right.isBST && root.val <right.minValue) {
        largestBST[0] = Math.max(largestBST[0], left.size + 1 + right.size);
        return new TreeInfo(true, left.size + 1 + right.size, Math.min(root.val, left.minValue), Math.max(root.val, right.maxValue));
    }

    return new TreeInfo(false, -1, Integer.MAX_VALUE, Integer.MIN_VALUE);
}
```

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

def largestBSTSubtree(root: TreeNode) -> int:
    def largestBSTUtil(root):
        if not root:
            return True, 0, float('inf'), float('-inf')

        left = largestBSTUtil(root.left)
        right = largestBSTUtil(root.right)

        if left[0] and root.val > left[3] and right[0] and root.val < right[2]:
            largestBST[0] = max(largestBST[0], left[1] + 1 + right[1])
            return True, left[1] + 1 + right[1], min(root.val, left[2]), max(root.val, right[3])

        return False, -1, float('inf'), float('-inf')

    largestBST = [0]
    largestBSTUtil(root)

    return largestBST[0]
```


```python
def findTriplets(nums: List[int]) -> bool:
    first = float('inf')
    second = float('inf')

    for num in nums:
        if num <= first:
            first = num
        elif num <= second:
            second = num
        else:
            return True
    return False
```

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

```java
public boolean findTriplets(int[] nums) {
    int first = Integer.MAX_VALUE;
    int second = Integer.MAX_VALUE;

    for (int num : nums) {
        if (num <= first) {
            first = num;
        } else if (num <= second) {
            second = num;
        } else {
            return true;
        }
    }
    return false;
}
```


```cpp
bool isPathCrossing(const std::vector<int>& distance) {
    std::unordered_set<std::pair<int, int>, pair_hash> visited;
    int x = 0, y = 0;
    visited.insert({x, y});
    int dx[] = {0, -1, 0, 1};
    int dy[] = {1, 0, -1, 0};

    for (int i = 0; i < distance.size(); ++i) {
        int direction = i % 4;
        for (int j = 0; j < distance[i]; ++j) {
            x += dx[direction];
            y += dy[direction];
            if (!visited.insert({x, y}).second) {
                return true;
            }
        }
    }
    return false;
}
```

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

```python
def is_path_crossing(distance):
    visited = set([(0, 0)])
    x, y = 0, 0
    directions = [(0, 1), (-1, 0), (0, -1), (1, 0)]

    for i, d in enumerate(distance):
        dx, dy = directions[i % 4]
        for _ in range(d):
            x += dx
            y += dy
            if (x, y) in visited:
                return True
            visited.add((x, y))
    return False
```


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

std::vector<std::pair<int, int>> palindromePairs(const std::vector<std::string> &words) {
    std::vector<std::pair<int, int>> result;

    for (size_t i = 0; i < words.size(); i++) {
        for (size_t j = 0; j < words.size(); j++) {
            if (i == j) continue;
            std::string concat = words[i] + words[j];

            bool is_palindrome = true;
            for (size_t left = 0, right = concat.size() - 1; left < right; left++, right--) {
                if (concat[left] != concat[right]) {
                    is_palindrome = false;
                    break;
                }
            }

            if (is_palindrome) {
                result.push_back(std::make_pair(i, j));
            }
        }
    }

    return result;
}
```

words = \[ "abcd ", "dcba ", "lls ", "s ", "sssll "\]

abc cba def fed ghi ihg jkl lkj mno onm pqr

```python
def palindrome_pairs(words):
    def is_palindrome(s):
        return s == s[::-1]

    result = []
    for i in range(len(words)):
        for j in range(len(words)):
            if i == j:
                continue
            concat = words[i] + words[j]
            if is_palindrome(concat):
                result.append([i, j])
    return result
```


```java
public int rob(TreeNode root) {
    int[] result = robHelper(root);
    return Math.max(result[0], result[1]);
}

private int[] robHelper(TreeNode node) {
    if (node == null) return new int[2];

    int[] left = robHelper(node.left);
    int[] right = robHelper(node.right);
    int[] result = new int[2];

    result[0] = node.val + left[1] + right[1];
    result[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
    return result;
}
```

```python
def rob(self, root: TreeNode) -> int:
    def rob_helper(node):
        if not node:
            return 0, 0

        left_with_node, left_without_node = rob_helper(node.left)
        right_with_node, right_without_node = rob_helper(node.right)

        with_node = node.val + left_without_node + right_without_node
        without_node = max(left_with_node, left_without_node) + max(right_with_node, right_without_node)
        return with_node, without_node

    return max(rob_helper(root))
```


```java
public int[] countBits(int n) {
    int[] ans = new int[n + 1];
    for (int i = 1; i <= n; ++i) {
        ans[i] = ans[i & (i - 1)] + 1;
    }
    return ans;
}
```

```python
def countBits(n):
    ans = [0] * (n + 1)
    for i in range(1, n + 1):
        ans[i] = ans[i & (i - 1)] + 1
    return ans
```


```java
import java.util.HashMap;

public int lengthOfLongestSubstringKDistinct(String s, int k) {
    HashMap<Character, Integer> charCount = new HashMap<>();
    int left = 0, maxLength = 0;

    for (int right = 0; right < s.length(); ++right) {
        charCount.put(s.charAt(right), charCount.getOrDefault(s.charAt(right), 0) + 1);

        while (charCount.size() > k) {
            charCount.put(s.charAt(left), charCount.get(s.charAt(left)) - 1);
            if (charCount.get(s.charAt(left)) == 0) {
                charCount.remove(s.charAt(left));
            }
            left++;
        }

        maxLength = Math.max(maxLength, right - left + 1);
    }
    return maxLength;
}
```

```python
def length_of_longest_substring_k_distinct(s: str, k: int) -> int:
    char_count = {}
    left = 0
    max_length = 0

    for right, char in enumerate(s):
        char_count[char] = char_count.get(char, 0) + 1

        while len(char_count) > k:
            char_count[s[left]] -= 1
            if char_count[s[left]] == 0:
                del char_count[s[left]]
            left += 1

        max_length = max(max_length, right - left + 1)

    return max_length
```


```java
public int integerBreak(int n) {
    if (n <= 3) return n - 1;
    int product = 1;
    while (n > 4) {
        product *= 3;
        n -= 3;
    }
    return product * n;
}
```

```python
def integer_break(n):
    if n <= 3:
        return n - 1
    product = 1
    while n > 4:
        product *= 3
        n -= 3
    return product * n
```


```python
def reverseString(s: List[str]) -> None:
    left, right = 0, len(s) - 1
    while left < right:
        s[left], s[right] = s[right], s[left]
        left, right = left + 1, right - 1
```

```cpp
void reverseString(vector<char>& s) {
    int left = 0, right = s.size() - 1;
    while (left < right) {
        swap(s[left++], s[right--]);
    }
}
```


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

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

    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> min_heap;
    for (const auto& entry : frequency) {
        min_heap.push({entry.second, entry.first});
        if (min_heap.size() > k) {
            min_heap.pop();
        }
    }

    vector<int> result;
    while (!min_heap.empty()) {
        result.push_back(min_heap.top().second);
        min_heap.pop();
    }

    return result;
}
```

```python
from heapq import heappush, heappop
from collections import Counter

def k_most_frequent(nums, k):
    frequency = Counter(nums)
    min_heap = []

    for num, freq in frequency.items():
        heappush(min_heap, (freq, num))
        if len(min_heap) > k:
            heappop(min_heap)

    return [heappop(min_heap)[1] for _ in range(k)]
```


```python
def intersect(nums1, nums2):
    count_map = {}
    result = []

    for num in nums1:
        count_map[num] = count_map.get(num, 0) + 1

    for num in nums2:
        if count_map.get(num, 0) > 0:
            result.append(num)
            count_map[num] -= 1

    return result
```

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

std::vector<int> intersect(std::vector<int>& nums1, std::vector<int>& nums2) {
    std::unordered_map<int, int> count_map;
    std::vector<int> result;

    for (int num : nums1) {
        count_map[num]++;
    }

    for (int num : nums2) {
        if (count_map[num] > 0) {
            result.push_back(num);
            count_map[num]--;
        }
    }

    return result;
}
```


```cpp
int numberOfPatterns(int m, int n) {
    const vector<vector<int>> jumps(10, vector<int>(10, 0));
    jumps[1][3] = jumps[3][1] = 2;
    jumps[1][7] = jumps[7][1] = 4;
    jumps[3][9] = jumps[9][3] = 6;
    jumps[7][9] = jumps[9][7] = 8;
    jumps[1][9] = jumps[9][1] = jumps[2][8] = jumps[8][2] = jumps[3][7] = jumps[7][3] = jumps[4][6] = jumps[6][4] = 5;

    vector<bool> visited(10, false);

    int cnt = 0;
    for (int i = m; i <= n; ++i) {
        cnt += dfs(jumps, visited, 1, i - 1) * 4; // 1, 3, 7, 9
        cnt += dfs(jumps, visited, 2, i - 1) * 4; // 2, 4, 6, 8
        cnt += dfs(jumps, visited, 5, i - 1);     // 5
    }

    return cnt;
}

int dfs(const vector<vector<int>>& jumps, vector<bool>& visited, int curr, int remaining) {
    if (remaining < 0) return 0;
    if (remaining == 0) return 1;

    visited[curr] = true;
    int cnt = 0;
    for (int next = 1; next <= 9; ++next) {
        if (!visited[next] && (jumps[curr][next] == 0 || visited[jumps[curr][next]])) {
            cnt += dfs(jumps, visited, next, remaining - 1);
        }
    }
    visited[curr] = false;

    return cnt;
}
```

```java
public int numberOfPatterns(int m, int n) {
    int[][] jumps = new int[10][10];
    jumps[1][3] = jumps[3][1] = 2;
    jumps[1][7] = jumps[7][1] = 4;
    jumps[3][9] = jumps[9][3] = 6;
    jumps[7][9] = jumps[9][7] = 8;
    jumps[1][9] = jumps[9][1] = jumps[2][8] = jumps[8][2] = jumps[3][7] = jumps[7][3] = jumps[4][6] = jumps[6][4] = 5;

    boolean[] visited = new boolean[10];

    int cnt = 0;
    for (int i = m; i <= n; ++i) {
        cnt += dfs(jumps, visited, 1, i - 1) * 4; // 1, 3, 7, 9
        cnt += dfs(jumps, visited, 2, i - 1) * 4; // 2, 4, 6, 8
        cnt += dfs(jumps, visited, 5, i - 1);     // 5
    }

    return cnt;
}

private int dfs(int[][] jumps, boolean[] visited, int curr, int remaining) {
    if (remaining < 0) return 0;
    if (remaining == 0) return 1;

    visited[curr] = true;
    int cnt = 0;
    for (int next = 1; next <= 9; ++next) {
        if (!visited[next] && (jumps[curr][next] == 0 || visited[jumps[curr][next]])) {
            cnt += dfs(jumps, visited, next, remaining - 1);
        }
    }
    visited[curr] = false;

    return cnt;
}
```


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

int maxEnvelopes(std::vector<std::vector<int>>& envelopes) {
    std::sort(envelopes.begin(), envelopes.end(), [](const std::vector<int>& a, const std::vector<int>& b) {
        return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0];
    });

    std::vector<int> dp;
    for (const auto& envelope : envelopes) {
        auto it = std::lower_bound(dp.begin(), dp.end(), envelope[1]);
        if (it == dp.end()) {
            dp.push_back(envelope[1]);
        } else {
            *it = envelope[1];
        }
    }

    return dp.size();
}
```

```python
from bisect import bisect_left

def max_envelopes(envelopes):
    envelopes.sort(key=lambda x: (x[0], -x[1]))
    dp = []

    for _, h in envelopes:
        idx = bisect_left(dp, h)
        if idx == len(dp):
            dp.append(h)
        else:
            dp[idx] = h

    return len(dp)
```