```python
def fourSum(nums, target):
    nums.sort()
    result = []
    for i in range(len(nums) - 3):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        for j in range(i + 1, len(nums) - 2):
            if j > i + 1 and nums[j] == nums[j - 1]:
                continue
            left = j + 1
            right = len(nums) - 1
            while left < right:
                cur_sum = nums[i] + nums[j] + nums[left] + nums[right]
                if cur_sum == target:
                    result.append([nums[i], nums[j], nums[left], nums[right]])
                    left += 1
                    right -= 1
                    while left < right and nums[left] == nums[left - 1]: left += 1
                    while left < right and nums[right] == nums[right + 1]: right -= 1
                elif cur_sum < target:
                    left += 1
                else:
                    right -= 1
    return result
```

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

vector<vector<int>> fourSum(vector<int>& nums, int target) {
    vector<vector<int>> result;
    int n = nums.size();
    if(n < 4)
        return result;

    sort(nums.begin(), nums.end());
    for(int i = 0; i < n - 3; i++) {
        if(i > 0 && nums[i] == nums[i-1])
            continue;

        for(int j = i + 1; j < n - 2; j++) {
            if(j > i + 1 && nums[j] == nums[j-1])
                continue;

            int left = j + 1;
            int right = n - 1;
            while(left < right) {
                int sum = nums[i] + nums[j] + nums[left] + nums[right];
                if(sum == target) {
                    result.push_back({nums[i], nums[j], nums[left], nums[right]});
                    ++left;
                    --right;
                    while(left < right && nums[left] == nums[left-1]) ++left;
                    while(left < right && nums[right] == nums[right+1]) --right;
                } else if(sum < target) {
                    ++left;
                } else {
                    --right;
                }
            }
        }
    }
    return result;
}
```


```cpp
bool isValid(std::string s) {
    std::stack<char> stack;

    for (char c : s) {
        if (c == '(' || c == '{' || c == '[') {
            stack.push(c);
        } else {
            if (stack.empty()) return false;
            if (c == ')' && stack.top() != '(') return false;
            if (c == '}' && stack.top() != '{') return false;
            if (c == ']' && stack.top() != '[') return false;
            stack.pop();
        }
    }

    return stack.empty();
}
```

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 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 False True True True True True True True True False True False True True 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 False True

```python
def is_valid(s: str) -> bool:
    stack = []

    for c in s:
        if c in '([{':
            stack.append(c)
        else:
            if not stack:
                return False
            if c == ')' and stack[-1] != '(':
                return False
            if c == '}' and stack[-1] != '{':
                return False
            if c == ']' and stack[-1] != '[':
                return False
            stack.pop()

    return not stack
```


```cpp
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
    if (list1 == nullptr) return list2;
    if (list2 == nullptr) return list1;

    if (list1->val < list2->val) {
        list1->next = mergeTwoLists(list1->next, list2);
        return list1;
    } else {
        list2->next = mergeTwoLists(list1, list2->next);
        return list2;
    }
}
```

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

def merge_two_lists(list1, list2):
    if list1 is None:
        return list2
    if list2 is None:
        return list1

    if list1.val < list2.val:
        list1.next = merge_two_lists(list1.next, list2)
        return list1
    else:
        list2.next = merge_two_lists(list1, list2.next)
        return list2
```


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

void generateParenthesisHelper(int open, int close, std::string current, std::vector<std::string>& result) {
    if (open == 0 && close == 0) {
        result.push_back(current);
        return;
    }
    if (open > 0) {
        generateParenthesisHelper(open - 1, close + 1, current + '(', result);
    }
    if (close > 0) {
        generateParenthesisHelper(open, close - 1, current + ')', result);
    }
}

std::vector<std::string> generateParenthesis(int n) {
    std::vector<std::string> result;
    generateParenthesisHelper(n, 0, "", result);
    return result;
}
```

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

public List<String> generateParenthesis(int n) {
    List<String> result = new ArrayList<>();
    generateParenthesisHelper(n, 0, "", result);
    return result;
}

private void generateParenthesisHelper(int open, int close, String current, List<String> result) {
    if (open == 0 && close == 0) {
        result.add(current);
        return;
    }
    if (open > 0) {
        generateParenthesisHelper(open - 1, close + 1, current + '(', result);
    }
    if (close > 0) {
        generateParenthesisHelper(open, close - 1, current + ')', result);
    }
}
```


```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* reverseKGroup(ListNode* head, int k) {
    if (head == nullptr || k == 1) return head;

    int len = 0;
    ListNode *cur = head;
    while (cur != nullptr) {
        len++;
        cur = cur->next;
    }

    ListNode dummy(0);
    dummy.next = head;
    ListNode *prev = &dummy;
    cur = head;

    while (len >= k) {
        for (int i = 1; i < k; i++) {
            ListNode *temp = cur->next;
            cur->next = temp->next;
            temp->next = prev->next;
            prev->next = temp;
        }
        prev = cur;
        cur = cur->next;
        len -= k;
    }

    return dummy.next;
}
```

```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 reverseKGroup(ListNode head, int k) {
    if (head == null || k == 1) return head;

    int len = 0;
    ListNode cur = head;
    while (cur != null) {
        len++;
        cur = cur.next;
    }

    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode prev = dummy;
    cur = head;

    while (len >= k) {
        for (int i = 1; i < k; i++) {
            ListNode temp = cur.next;
            cur.next = temp.next;
            temp.next = prev.next;
            prev.next = temp;
        }
        prev = cur;
        cur = cur.next;
        len -= k;
    }

    return dummy.next;
}
```


```python
def removeDuplicates(nums):
    if not nums: return 0
    i = 0
    for j in range(1, len(nums)):
        if nums[j] != nums[i]:
            i += 1
            nums[i] = nums[j]
    return i + 1
```

```cpp
int removeDuplicates(vector<int>& nums) {
    if (nums.empty()) return 0;
    int i = 0;
    for (int j = 1; j < nums.size(); j++) {
        if (nums[j] != nums[i]) {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1;
}
```


```java
public int removeElement(int[] nums, int val) {
    int i = 0;
    for (int j = 0; j < nums.length; j++) {
        if (nums[j] != val) {
            nums[i] = nums[j];
            i++;
        }
    }
    return i;
}
```

```python
def removeElement(nums, val):
    i = 0
    for j in range(len(nums)):
        if nums[j] != val:
            nums[i] = nums[j]
            i += 1
    return i
```


```cpp
int strStr(string haystack, string needle) {
    if(needle.empty()) return 0;

    size_t pos = haystack.find(needle);
    if(pos != string::npos)
        return pos;
    return -1;
}
```

haystack =  "sadbutsad ", needle =  "sad "

```python
def strStr(haystack: str, needle: str) -> int:
    if not needle:
        return 0
    try:
        index = haystack.index(needle)
        return index
    except ValueError:
        return -1
```


```java
public int divide(int dividend, int divisor) {
    if (dividend == Integer.MIN_VALUE && divisor == -1) {
        return Integer.MAX_VALUE;
    }

    int sign = (dividend > 0) ^ (divisor > 0) ? -1 : 1;

    long dvd = Math.abs((long) dividend);
    long dvs = Math.abs((long) divisor);
    int ans = 0;

    while (dvd >= dvs) {
        long temp = dvs, multiple = 1;
        while (dvd >= (temp << 1)) {
            temp <<= 1;
            multiple <<= 1;
        }
        dvd -= temp;
        ans += multiple;
    }

    return ans * sign;
}
```

```cpp
int divide(int dividend, int divisor) {
    if (dividend == INT_MIN && divisor == -1) {
        return INT_MAX;
    }

    int sign = (dividend > 0) ^ (divisor > 0) ? -1 : 1;

    long long dvd = labs(dividend);
    long long dvs = labs(divisor);
    int ans = 0;

    while (dvd >= dvs) {
        long long temp = dvs, multiple = 1;
        while (dvd >= (temp << 1)) {
            temp <<= 1;
            multiple <<= 1;
        }
        dvd -= temp;
        ans += multiple;
    }

    return ans * sign;
}
```


```python
from collections import Counter

def findSubstring(s, words):
    if not s or not words:
        return []

    word_count = Counter(words)
    word_length = len(words[0])
    total_words = len(words)
    total_length = word_length * total_words
    result = []

    for i in range(len(s) - total_length + 1):
        temp_word_count = Counter()
        for j in range(total_words):
            current_word = s[i + j * word_length:i + (j + 1) * word_length]
            if current_word not in word_count:
                break
            temp_word_count[current_word] += 1
            if temp_word_count[current_word] > word_count[current_word]:
                break
            if j + 1 == total_words:
                result.append(i)

    return result
```

s =  "barfoothefoobarman ", words = \[ "foo ", "bar "\]

wordgoodgoodgoodbestword
["word", "good", "best"]

barfoofoobarthefoobarman
["bar", "foo", "the"]

wordgoodgoodgoodbestword
["word ", "good ", "best ", "word "]

wordgoodgoodgoodbestword
["word", "good", "best", "word"]

lingmindraboofooowingdingbarrwingmonkeypoundcake
["fooo ", "barr ", "wing ", "ding ", "wing "]

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

std::vector<int> findSubstring(std::string s, std::vector<std::string>& words) {
    if (s.empty() || words.empty()) return {};

    std::unordered_map<std::string, int> word_count;
    for (const auto& word : words) {
        ++word_count[word];
    }

    int word_length = words[0].size();
    int total_words = words.size();
    int total_length = word_length * total_words;
    std::vector<int> result;

    for (int i = 0; i <= (int)s.size() - total_length; ++i) {
        std::unordered_map<std::string, int> temp_word_count;
        for (int j = 0; j < total_words; ++j) {
            std::string current_word = s.substr(i + j * word_length, word_length);
            if (word_count.find(current_word) == word_count.end()) break;
            ++temp_word_count[current_word];
            if (temp_word_count[current_word] > word_count[current_word]) break;
            if (j + 1 == total_words) result.push_back(i);
        }
    }

    return result;
}
```


```python
def nextPermutation(nums):
    n, k = len(nums), -1
    for i in range(n - 1, 0, -1):
        if nums[i - 1] < nums[i]:
            k = i - 1
            break
    if k == -1:
        nums.reverse()
    else:
        l = 0
        for i in range(n - 1, k, -1):
            if nums[i] > nums[k]:
                l = i
                break
        nums[k], nums[l] = nums[l], nums[k]
        nums[k + 1:] = reversed(nums[k + 1:])
```

```java
public void nextPermutation(int[] nums) {
    int n = nums.length, k = n - 2, l;
    while(k >= 0 && nums[k] >= nums[k + 1]) k--;

    if(k < 0) {
        Arrays.sort(nums);
    } else {
        for (l = n - 1; l > k; l--) {
            if (nums[l] > nums[k]) break;
        }
        int temp = nums[k];
        nums[k] = nums[l];
        nums[l] = temp;
        Arrays.sort(nums, k + 1, n);
    }
}
```


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

```cpp
int search(vector<int>& nums, int target) {
    int left = 0, right = nums.size() - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) {
            return mid;
        }
        if (nums[mid] >= nums[left]) {
            if (target >= nums[left] && target < nums[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        } else {
            if (target > nums[mid] && target <= nums[right]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
    }
    return -1;
}
```


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

```cpp
int searchInsert(vector<int>& nums, int target) {
    int left = 0, right = nums.size() - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) return mid;
        if (nums[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return left;
}
```


```java
public String countAndSay(int n) {
    if (n == 1) return "1";
    String previous = countAndSay(n-1);
    StringBuilder result = new StringBuilder();
    int count = 1;
    for (int i = 1; i < previous.length(); i++) {
        if (previous.charAt(i) == previous.charAt(i-1)) {
            count++;
        } else {
            result.append(count).append(previous.charAt(i-1));
            count = 1;
        }
    }
    result.append(count).append(previous.charAt(previous.length()-1));
    return result.toString();
}
```

```python
def count_and_say(n):
    if n == 1:
        return "1"
    previous = count_and_say(n - 1)
    result = []
    count = 1
    for i in range(1, len(previous)):
        if previous[i] == previous[i - 1]:
            count += 1
        else:
            result.append(str(count))
            result.append(previous[i - 1])
            count = 1
    result.append(str(count))
    result.append(previous[-1])
    return "".join(result)
```


```cpp
#include <vector>

void findCombinations(std::vector<int>& candidates, int target, int startIndex, std::vector<int>& current, std::vector<std::vector<int>>& result) {
    if (target == 0) {
        result.push_back(current);
        return;
    }
    if (startIndex == candidates.size() || target < 0) {
        return;
    }

    findCombinations(candidates, target, startIndex + 1, current, result);

    current.push_back(candidates[startIndex]);
    findCombinations(candidates, target - candidates[startIndex], startIndex, current, result);
    current.pop_back();
}

std::vector<std::vector<int>> combinationSum(std::vector<int>& candidates, int target) {
    std::vector<int> current;
    std::vector<std::vector<int>> result;
    findCombinations(candidates, target, 0, current, result);
    return result;
}
```


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

void combine(std::vector<int>& candidates, int target, std::vector<std::vector<int>>& result, std::vector<int>& combination, int index) {
    if (target == 0) {
        result.push_back(combination);
        return;
    }

    for (int i = index; i < candidates.size() && target >= candidates[i]; ++i) {
        if (i == index || candidates[i] != candidates[i - 1]) {
            combination.push_back(candidates[i]);
            combine(candidates, target - candidates[i], result, combination, i + 1);
            combination.pop_back();
        }
    }
}

std::vector<std::vector<int>> combinationSum2(std::vector<int>& candidates, int target) {
    std::vector<std::vector<int>> result;
    std::vector<int> combination;
    std::sort(candidates.begin(), candidates.end());
    combine(candidates, target, result, combination, 0);
    return result;
}
```

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

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    List<List<Integer>> result = new ArrayList<>();
    Arrays.sort(candidates);
    combine(candidates, target, 0, result, new ArrayList<Integer>());
    return result;
}

private void combine(int[] candidates, int target, int start, List<List<Integer>> result, List<Integer> current) {
    if (target == 0) {
        result.add(new ArrayList<>(current));
        return;
    }

    for (int i = start; i < candidates.length && target >= candidates[i]; i++) {
        if (i == start || candidates[i] != candidates[i - 1]) {
            current.add(candidates[i]);
            combine(candidates, target - candidates[i], i + 1, result, current);
            current.remove(current.size() - 1);
        }
    }
}
```


```java
public int firstMissingPositive(int[] nums) {
    int n = nums.length;
    for(int i = 0; i < n; i++) {
        while(nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
            int temp = nums[i];
            nums[i] = nums[temp - 1];
            nums[temp - 1] = temp;
        }
    }

    for(int i = 0; i < n; i++) {
        if(nums[i] != i + 1) {
            return i + 1;
        }
    }
    return n + 1;
}
```

```cpp
int firstMissingPositive(vector<int>& nums) {
    int n = nums.size();
    for(int i = 0; i < n; ++i)
        while(nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i])
            swap(nums[i], nums[nums[i] - 1]);

    for(int i = 0; i < n; ++i)
        if(nums[i] != i + 1)
            return i + 1;
    return n + 1;
}
```


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

int trap(vector<int>& height) {
    int n = height.size();
    int left = 0, right = n - 1, maxLeft = 0, maxRight = 0, water = 0;

    while (left < right) {
        if (height[left] <= height[right]) {
            maxLeft = max(maxLeft, height[left]);
            water += maxLeft - height[left];
            left++;
        } else {
            maxRight = max(maxRight, height[right]);
            water += maxRight - height[right];
            right--;
        }
    }

    return water;
}
```

```python
def trap(height):
    n = len(height)
    left, right, max_left, max_right, water = 0, n - 1, 0, 0, 0

    while left < right:
        if height[left] <= height[right]:
            max_left = max(max_left, height[left])
            water += max_left - height[left]
            left += 1
        else:
            max_right = max(max_right, height[right])
            water += max_right - height[right]
            right -= 1

    return water
```


```python
def jump(nums):
    jumps = 0
    current_end = 0
    current_farthest = 0

    for i in range(len(nums) - 1):
        current_farthest = max(current_farthest, i + nums[i])
        if i == current_end:
            jumps += 1
            current_end = current_farthest

    return jumps
```

```java
public int jump(int[] nums) {
    int jumps = 0, currentEnd = 0, currentFarthest = 0;

    for (int i = 0; i < nums.length - 1; i++) {
        currentFarthest = Math.max(currentFarthest, i + nums[i]);
        if (i == currentEnd) {
            jumps++;
            currentEnd = currentFarthest;
        }
    }
    return jumps;
}
```


```python
from typing import List

def permute(nums: List[int]) -> List[List[int]]:
    def helper(index):
        if index == len(nums) - 1:
            results.append(nums[:])
            return

        for i in range(index, len(nums)):
            nums[index], nums[i] = nums[i], nums[index]
            helper(index + 1)
            nums[index], nums[i] = nums[i], nums[index]

    results = []
    helper(0)
    return results
```


```python
from typing import List

def permuteUnique(nums: List[int]) -> List[List[int]]:
    def backtrack(start):
        if start == len(nums):
            result.append(nums[:])
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[start]:
                continue
            nums[start], nums[i] = nums[i], nums[start]
            backtrack(start + 1)
            nums[start], nums[i] = nums[i], nums[start]

    nums.sort()
    result = []
    backtrack(0)
    return result
```

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

void backtrack(std::vector<std::vector<int>>& result, std::vector<int>& nums, int start) {
    if (start == nums.size()) {
        result.push_back(nums);
        return;
    }
    for (int i = start; i < nums.size(); i++) {
        if (i > start && nums[i] == nums[start]) continue;
        std::swap(nums[start], nums[i]);
        backtrack(result, nums, start + 1);
        std::swap(nums[start], nums[i]);
    }
}

std::vector<std::vector<int>> permuteUnique(std::vector<int>& nums) {
    std::sort(nums.begin(), nums.end());
    std::vector<std::vector<int>> result;
    backtrack(result, nums, 0);
    return result;
}
```


```java
public void rotate(int[][] matrix) {
    int n = matrix.length;
    for (int i = 0; i < n / 2; i++) {
        for (int j = i; j < n - i - 1; j++) {
            int temp = matrix[i][j];
            matrix[i][j] = matrix[n - j - 1][i];
            matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];
            matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];
            matrix[j][n - i - 1] = temp;
        }
    }
}
```

```cpp
void rotate(vector<vector<int>>& matrix) {
    int n = matrix.size();
    for (int i = 0; i < n / 2; i++) {
        for (int j = i; j < n - i - 1; j++) {
            int temp = matrix[i][j];
            matrix[i][j] = matrix[n - j - 1][i];
            matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];
            matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];
            matrix[j][n - i - 1] = temp;
        }
    }
}
```


```python
from collections import defaultdict

def group_anagrams(strs):
    anagram_map = defaultdict(list)

    for s in strs:
        key = ''.join(sorted(s))
        anagram_map[key].append(s)

    return list(anagram_map.values())
```

potato topota potaot topaot topota topaot topotat topotaot

race care area acre rcae eraa aera aaera aaaera aaaaera

listen silent enlist inlets ltnesi eltnis slient sielnt sliente slientee

abba baba baab aabb abbaa aabba aaabba aaaabba aaaaabba

hello world dolr wohle drlwo ldrow dorlw dlrow drlwo drlwoe

[[area, eraa, aera], [race, care, acre, rcae], [aaera]]

[[listen, silent, enlist, inlets, ltnesi, eltnis, slient]]

[[area, eraa, aera], [race, care, acre, rcae], [aaaera], [aaaaera], [aaera]]

[[area, eraa], [race, care, acre, rcae]]

[[wohle], [dolr], [hello], [world, drlwo, ldrow, dorlw]]

[[area, eraa, aera], [race, care, acre, rcae], [aaaera], [aaera]]

[[listen, silent, enlist, inlets, ltnesi, eltnis, slient, sielnt]]

[[area, eraa, aera], [race, care, acre, rcae]]

[[abbaa, aabba], [abba, baba, baab, aabb]]

[[pqp, qpp], [abc], [def], [qqpp], [ghi], [jkl], [mno], [qqqpp]]

[[wohle], [dolr], [hello], [world, drlwo, ldrow, dorlw, dlrow]]

[[wohle], [dolr], [hello], [world, drlwo]]

[[pqp, qpp], [abc], [def], [qqpp], [ghi], [jkl], [mno]]

[[topotat], [topotaot], [potato, topota, potaot, topaot, topota, topaot]]

[[listen, silent, enlist, inlets, ltnesi]]

[[listen, silent, enlist, inlets, ltnesi, eltnis]]

[[topotat], [potato, topota, potaot, topaot, topota, topaot]]

[[abbaa, aabba], [aaaabba], [aaabba], [abba, baba, baab, aabb]]

[[potato, topota, potaot, topaot, topota]]

[[wohle], [dolr], [hello], [world, drlwo, ldrow]]

[[listen, silent, enlist, inlets, ltnesi, eltnis, slient, sielnt], [sliente]]

[[wohle], [dolr], [hello], [world, drlwo, ldrow, dorlw, dlrow, drlwo], [drlwoe]]

[[listen, silent, enlist, inlets, ltnesi, eltnis, slient, sielnt], [sliente], [slientee]]

[[pqp, qpp], [abc], [def], [ghi], [jkl], [mno]]

[[wohle], [dolr], [hello], [world, drlwo, ldrow, dorlw, dlrow, drlwo]]

[[abbaa, aabba], [aaaabba], [aaaaabba], [aaabba], [abba, baba, baab, aabb]]

[[abbaa, aabba], [aaabba], [abba, baba, baab, aabb]]

```java
import java.util.*;

public List<List<String>> groupAnagrams(String[] strs) {
    Map<String, List<String>> anagramMap = new HashMap<>();

    for (String str : strs) {
        char[] keyChars = str.toCharArray();
        Arrays.sort(keyChars);
        String key = new String(keyChars);

        anagramMap.putIfAbsent(key, new ArrayList<>());
        anagramMap.get(key).add(str);
    }

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


```python
def solveNQueens(n):
    def isSafe(board, row, col):
        for i in range(col):
            if board[row][i] == 'Q': return False
        i, j = row, col
        while i >= 0 and j >= 0:
            if board[i][j] == 'Q': return False
            i, j = i - 1, j - 1
        i, j = row, col
        while i < n and j >= 0:
            if board[i][j] == 'Q': return False
            i, j = i + 1, j - 1
        return True

    def solve(result, board, n, col):
        if col == n:
            result.append(board.copy())
            return
        for row in range(n):
            if isSafe(board, row, col):
                board[row] = board[row][:col] + 'Q' + board[row][col + 1:]
                solve(result, board, n, col + 1)
                board[row] = board[row][:col] + '.' + board[row][col + 1:]

    result, board = [], ['.' * n for _ in range(n)]
    solve(result, board, n, 0)
    return result
```

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

public List<List<String>> solveNQueens(int n) {
    List<List<String>> result = new ArrayList<>();
    solve(result, new ArrayList<>(), n, 0);
    return result;
}

private void solve(List<List<String>> result, List<Integer> current, int n, int col) {
    if (col == n) {
        result.add(generateBoard(current, n));
        return;
    }
    for (int row = 0; row < n; row++) {
        if(isSafe(current, row, col)) {
            current.add(row);
            solve(result, current, n, col + 1);
            current.remove(col);
        }
    }
}

private boolean isSafe(List<Integer> current, int row, int col) {
    for (int i = 0; i < col; i++) {
        int prevRow = current.get(i);
        if (prevRow == row || (Math.abs(col - i) == Math.abs(row - prevRow))) {
            return false;
        }
    }
    return true;
}

private List<String> generateBoard(List<Integer> current, int n) {
    List<String> board = new ArrayList<>();
    for (int row : current) {
        StringBuilder sb = new StringBuilder();
        for (int col = 0; col < n; col++)
            sb.append((col == row) ? "Q" : ".");
        board.add(sb.toString());
    }
    return board;
}
```


```python
def is_safe(cols, row):
    col = len(cols)
    for i, r in enumerate(cols):
        if r == row or abs(i - col) == abs(r - row):
            return False
    return True

def backtrack(n, cols):
    if len(cols) == n:
        return 1

    count = 0
    for i in range(n):
        if is_safe(cols, i):
            cols.append(i)
            count += backtrack(n, cols)
            cols.pop()

    return count

def total_n_queens(n):
    cols = []
    return backtrack(n, cols)
```

```java
import java.util.ArrayList;

public int totalNQueens(int n) {
    ArrayList<Integer> cols = new ArrayList<>();
    return backtrack(n, cols);
}

public int backtrack(int n, ArrayList<Integer> cols) {
    if (cols.size() == n) {
        return 1;
    }

    int count = 0;
    for (int i = 0; i < n; i++) {
        if (isSafe(cols, i)) {
            cols.add(i);
            count += backtrack(n, cols);
            cols.remove(cols.size() - 1);
        }
    }
    return count;
}

public boolean isSafe(ArrayList<Integer> cols, int row) {
    int col = cols.size();
    for (int i = 0; i < cols.size(); i++) {
        if (cols.get(i) == row || Math.abs(i - col) == Math.abs(cols.get(i) - row)) {
            return false;
        }
    }
    return true;
}
```


```cpp
int maxSubArray(vector<int>& nums) {
    int max_sum = nums[0];
    int current_sum = max_sum;

    for (int i = 1; i < nums.size(); i++) {
        current_sum = max(current_sum + nums[i], nums[i]);
        max_sum = max(max_sum, current_sum);
    }

    return max_sum;
}
```

```python
def maxSubArray(nums):
    max_sum = current_sum = nums[0]

    for num in nums[1:]:
        current_sum = max(current_sum + num, num)
        max_sum = max(max_sum, current_sum)

    return max_sum
```


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

public List<Integer> spiralOrder(int[][] matrix) {
    List<Integer> result = new ArrayList<>();
    if (matrix == null || matrix.length == 0) return result;
    int m = matrix.length, n = matrix[0].length;
    int rowStart = 0, colStart = 0, rowEnd = m - 1, colEnd = n - 1;

    while (rowStart <= rowEnd && colStart <= colEnd) {
        for (int i = colStart; i <= colEnd; i++) {
            result.add(matrix[rowStart][i]);
        }
        rowStart++;
        for (int i = rowStart; i <= rowEnd; i++) {
            result.add(matrix[i][colEnd]);
        }
        colEnd--;
        if (rowStart <= rowEnd) {
            for (int i = colEnd; i >= colStart; i--) {
                result.add(matrix[rowEnd][i]);
            }
        }
        rowEnd--;
        if (colStart <= colEnd) {
            for (int i = rowEnd; i >= rowStart; i--) {
                result.add(matrix[i][colStart]);
            }
        }
        colStart++;
    }
    return result;
}
```

```python
def spiralOrder(matrix):
    result = []
    if not matrix: return result
    m, n = len(matrix), len(matrix[0])
    rowStart, colStart, rowEnd, colEnd = 0, 0, m - 1, n - 1

    while rowStart <= rowEnd and colStart <= colEnd:
        for i in range(colStart, colEnd + 1):
            result.append(matrix[rowStart][i])
        rowStart += 1

        for i in range(rowStart, rowEnd + 1):
            result.append(matrix[i][colEnd])
        colEnd -= 1

        if rowStart <= rowEnd:
            for i in range(colEnd, colStart - 1, -1):
                result.append(matrix[rowEnd][i])
        rowEnd -= 1

        if colStart <= colEnd:
            for i in range(rowEnd, rowStart - 1, -1):
                result.append(matrix[i][colStart])
        colStart += 1

    return result
```


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

public String getPermutation(int n, int k) {
    List<Integer> nums = new ArrayList<>();
    int[] factorials = new int[n];
    StringBuilder sb = new StringBuilder();
    int index;

    factorials[0] = 1;
    for (int i = 1; i <= n; ++i) {
        nums.add(i);
        factorials[i - 1] = i * factorials[i - 1];
    }

    k--;

    for (int i = n; i >= 1; --i) {
        index = k / factorials[i - 1];
        k %= factorials[i - 1];
        sb.append(nums.get(index));
        nums.remove(index);
    }

    return sb.toString();
}
```

```python
def getPermutation(n, k):
    factorials = [1]
    nums = list(range(1, n + 1))
    result = []

    for i in range(1, n):
        factorials.append(factorials[-1] * i)

    k -= 1

    for i in range(n, 0, -1):
        index = k // factorials[i - 1]
        k %= factorials[i - 1]
        result.append(str(nums.pop(index)))

    return ''.join(result)
```


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

};

ListNode* rotateRight(ListNode* head, int k) {
    if (!head || !head->next || k == 0) return head;

    ListNode *current = head;
    int len = 1;
    while (current->next) {
        len++;
        current = current->next;
    }
    current->next = head;
    k = len - k % len;

    while (k--) {
        current = current->next;
    }
    head = current->next;
    current->next = nullptr;

    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 rotateRight(ListNode head, int k) {
    if (head == null || head.next == null || k == 0) return head;

    ListNode current = head;
    int len = 1;
    while (current.next != null) {
        len++;
        current = current.next;
    }
    current.next = head;
    k = len - k % len;

    while (k-- > 0) {
        current = current.next;
    }
    head = current.next;
    current.next = null;

    return head;
}
```


```java
public int uniquePaths(int m, int n) {
    int[][] dp = new int[m][n];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (i == 0 || j == 0) {
                dp[i][j] = 1;
            } else {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
            }
        }
    }
    return dp[m - 1][n - 1];
}
```

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


```python
def uniquePathsWithObstacles(grid):
    m, n = len(grid), len(grid[0])
    if grid[0][0] == 1:
        return 0

    grid[0][0] = 1
    for i in range(1, m):
        grid[i][0] = 1 if grid[i][0] == 0 and grid[i - 1][0] == 1 else 0
    for i in range(1, n):
        grid[0][i] = 1 if grid[0][i] == 0 and grid[0][i - 1] == 1 else 0

    for i in range(1, m):
        for j in range(1, n):
            if grid[i][j] == 0:
                grid[i][j] = grid[i - 1][j] + grid[i][j - 1]
            else:
                grid[i][j] = 0

    return grid[m - 1][n - 1]
```

```java
public int uniquePathsWithObstacles(int[][] grid) {
    int m = grid.length;
    int n = grid[0].length;
    if (grid[0][0] == 1) return 0;

    grid[0][0] = 1;
    for (int i = 1; i < m; ++i)
        grid[i][0] = (grid[i][0] == 0 && grid[i - 1][0] == 1) ? 1 : 0;
    for (int i = 1; i < n; ++i)
        grid[0][i] = (grid[0][i] == 0 && grid[0][i - 1] == 1) ? 1 : 0;

    for (int i = 1; i < m; ++i)
        for (int j = 1; j < n; ++j)
            if (grid[i][j] == 0)
                grid[i][j] = grid[i - 1][j] + grid[i][j - 1];
            else
                grid[i][j] = 0;

    return grid[m - 1][n - 1];
}
```


```python
def minPathSum(grid):
    m, n = len(grid), len(grid[0])

    for i in range(1, m):
        grid[i][0] += grid[i - 1][0]

    for i in range(1, n):
        grid[0][i] += grid[0][i - 1]

    for i in range(1, m):
        for j in range(1, n):
            grid[i][j] += min(grid[i - 1][j], grid[i][j - 1])

    return grid[m - 1][n - 1]
```

```java
public int minPathSum(int[][] grid) {
    int m = grid.length, n = grid[0].length;

    for(int i = 1; i < m; i++)
        grid[i][0] += grid[i - 1][0];

    for(int i = 1; i < n; i++)
        grid[0][i] += grid[0][i - 1];

    for(int i = 1; i < m; i++){
        for(int j = 1; j < n; j++){
            grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);
        }
    }
    return grid[m - 1][n - 1];
}
```


```cpp
std::string addBinary(std::string a, std::string b) {
    std::string result = "";
    int i = a.size() - 1, j = b.size() - 1, carry = 0;
    while (i >= 0 || j >= 0 || carry) {
        if (i >= 0) carry += a[i--] - '0';
        if (j >= 0) carry += b[j--] - '0';
        result = char(carry % 2 + '0') + result;
        carry /= 2;
    }
    return result;
}
```

```python
def addBinary(a: str, b: str) -> str:
    result, carry, i, j = "", 0, len(a) - 1, len(b) - 1
    while i >= 0 or j >= 0 or carry:
        if i >= 0:
            carry += int(a[i])
            i -= 1
        if j >= 0:
            carry += int(b[j])
            j -= 1
        result = str(carry % 2) + result
        carry //= 2
    return result
```


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

public List<String> fullJustify(String[] words, int maxWidth) {
    List<String> result = new ArrayList<>();
    int idx = 0;
    while (idx < words.length) {
        int totalChars = words[idx].length();
        int last = idx + 1;
        while (last < words.length) {
            if (totalChars + 1 + words[last].length() > maxWidth) break;
            totalChars += 1 + words[last].length();
            last++;
        }
        int gaps = last - idx - 1;
        StringBuilder line = new StringBuilder();
        if (last == words.length || gaps == 0) {
            for (int i = idx; i < last; i++) {
                line.append(words[i]);
                if (i < last - 1) line.append(" ");
            }
            while (line.length() < maxWidth) line.append(" ");
        } else {
            int evenSpaces = (maxWidth - totalChars) / gaps;
            int extraSpaces = (maxWidth - totalChars) % gaps;
            for (int i = idx; i < last; i++) {
                line.append(words[i]);
                if (i < last - 1) {
                    line.append(" ".repeat(evenSpaces + (i - idx < extraSpaces ? 1 : 0)));
                }
            }
        }
        idx = last;
        result.add(line.toString());
    }
    return result;
}
```

words = \[ "This ",  "is ",  "an ",  "example ",  "of ",  "text ",  "justification. "\], maxWidth = 16

\[
    "This    is    an ",
    "example  of text ",
    "justification.   "
\]

["What", "must", "be", "acknowledgment", "shall", "be"]
16

["Science", "is", "what", "we", "understand", "well", "enough", "to", "explain", "to", "a", "computer.", "Art", "is", "everything", "else", "we", "do"]
20

["Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. "]
20

["Hello ", "world! ", "this ", "is ", "a ", "test ", "for ", "text ", "justification. "]
16

["This", "is", "an", "example", "of", "text", "justification."]
16

["The ", "quick ", "brown ", "fox ", "jumps ", "over ", "the ", "lazy ", "dog. "]
16

[ "This ",  "is ",  "an ",  "example ",  "of ",  "text ",  "justification. "]
16

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

Science  is  what
we      understand
well   enough  to
explain    to   a
computer.

Hello   world!
this   is   a
test for text
justification.

This   is  an
example     of
text
justification.

The      quick
brown      fox
jumps     over
the  lazy  dog.

123  456
789  0ab
cde  fgh
ijkl
mnop
qrst
uvwx
yzAB

Science is whatwe
understand     well
enoughtoexplainto
a computer. Artis
everything else we
do

This   is   an
example oftext
justification.

To  be  or not
to be, that is
the  question.

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

vector<string> fullJustify(vector<string>& words, int maxWidth) {
    vector<string> result;
    int idx = 0;
    while (idx < words.size()) {
        int totalChars = words[idx].size();
        int last = idx + 1;
        while (last < words.size()) {
            if (totalChars + 1 + words[last].length() > maxWidth) break;
            totalChars += 1 + words[last].length();
            last++;
        }
        int gaps = last - idx - 1;
        stringstream line;
        if (last == words.size() || gaps == 0) {
            for (int i = idx; i < last; i++) {
                line << words[i];
                if (i < last - 1) line << " ";
            }
            line << string(maxWidth - line.str().size(), ' ');
        } else {
            int evenSpaces = (maxWidth - totalChars) / gaps;
            int extraSpaces = (maxWidth - totalChars) % gaps;
            for (int i = idx; i < last; i++) {
                line << words[i];
                if (i < last - 1) {
                    line << string(evenSpaces + (i - idx < extraSpaces ? 1 : 0), ' ');
                }
            }
        }
        idx = last;
        result.push_back(line.str());
    }
    return result;
}
```


```java
public int mySqrt(int x) {
    if (x == 0 || x == 1) return x;
    int start = 1, end = x, ans = 0;
    while (start <= end) {
        int mid = (start + end) / 2;
        if (mid * mid == x) return mid;
        if (mid <= x / mid) {
            start = mid + 1;
            ans = mid;
        } else {
            end = mid - 1;
        }
    }
    return ans;
}
```

```cpp
int mySqrt(int x) {
    if (x == 0 || x == 1) return x;
    int start = 1, end = x, ans;
    while (start <= end) {
        int mid = (start + end) / 2;
        if (mid * mid == x) return mid;
        if (mid * mid < x) {
            start = mid + 1;
            ans = mid;
        } else {
            end = mid - 1;
        }
    }
    return ans;
}
```


```java
public int climbStairs(int n) {
    if(n <= 2) return n;
    int a = 1, b = 2, c;
    for(int i = 3; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }
    return c;
}
```

```python
def climbStairs(n):
    if n <= 2:
        return n
    a, b = 1, 2
    for _ in range(3, n+1):
        a, b = b, a + b
    return b
```


```java
import java.util.LinkedList;

public String simplifyPath(String path) {
    String[] parts = path.split("/");
    LinkedList<String> stack = new LinkedList<>();

    for (String part : parts) {
        if (part.isEmpty() || part.equals(".")) continue;
        if (part.equals("..")) {
            if (!stack.isEmpty()) stack.removeLast();
        } else {
            stack.addLast(part);
        }
    }

    StringBuilder canonicalPath = new StringBuilder();
    for (String piece : stack) {
        canonicalPath.append('/').append(piece);
    }
    return stack.isEmpty() ? "/" : canonicalPath.toString();
}
```

```python
def simplifyPath(path: str) -> str:
    stack = []
    parts = path.split("/")

    for part in parts:
        if not part or part == ".":
            continue
        if part == "..":
            if stack:
                stack.pop()
        else:
            stack.append(part)

    return "/" + "/".join(stack)
```


```python
def searchMatrix(matrix, target):
    m, n = len(matrix), len(matrix[0])
    l, r = 0, m * n - 1

    while l <= r:
        mid = l + (r - l) // 2
        mid_val = matrix[mid // n][mid % n]

        if mid_val == target:
            return True
        elif mid_val < target:
            l = mid + 1
        else:
            r = mid - 1

    return False
```

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

```cpp
bool searchMatrix(vector<vector<int>>& matrix, int target) {
    int m = matrix.size();
    int n = matrix[0].size();
    int l = 0, r = m * n - 1;

    while (l <= r) {
        int mid = l + (r - l) / 2;
        int midVal = matrix[mid / n][mid % n];

        if (midVal == target) {
            return true;
        } else if (midVal < target) {
            l = mid + 1;
        } else {
            r = mid - 1;
        }
    }

    return false;
}
```


```java
public void sortColors(int[] nums) {
    int red = 0, white = 0, blue = nums.length - 1;
    while (white <= blue) {
        if (nums[white] == 0) {
            int temp = nums[red];
            nums[red++] = nums[white];
            nums[white++] = temp;
        } else if (nums[white] == 1) {
            white++;
        } else {
            int temp = nums[white];
            nums[white] = nums[blue];
            nums[blue--] = temp;
        }
    }
}
```

```python
def sortColors(nums: List[int]) -> None:
    red, white, blue = 0, 0, len(nums) - 1
    while white <= blue:
        if nums[white] == 0:
            nums[red], nums[white] = nums[white], nums[red]
            red += 1
            white += 1
        elif nums[white] == 1:
            white += 1
        else:
            nums[white], nums[blue] = nums[blue], nums[white]
            blue -= 1
```


```python
from collections import Counter

def min_window(s, t):
    need = Counter(t)
    window = {}

    left = 0
    right = 0
    valid = 0
    start = 0
    length = float('inf')

    while right < len(s):
        c = s[right]
        right += 1
        if c in need:
            window[c] = window.get(c, 0) + 1
            if window[c] <= need[c]:
                valid += 1

        while valid == len(t):
            if right - left < length:
                start = left
                length = right - left

            d = s[left]
            left += 1
            if d in need:
                if window[d] <= need[d]:
                    valid -= 1
                window[d] -= 1

    return "" if length == float('inf') else s[start : start + length]
```

```java
import java.util.HashMap;

public String minWindow(String s, String t) {
    HashMap<Character, Integer> need = new HashMap<>();
    HashMap<Character, Integer> window = new HashMap<>();
    for (char c : t.toCharArray()) need.put(c, need.getOrDefault(c, 0) + 1);

    int left = 0, right = 0;
    int valid = 0;
    int start = 0, length = Integer.MAX_VALUE;

    while (right < s.length()) {
        char c = s.charAt(right);
        right++;
        if (need.containsKey(c)) {
            window.put(c, window.getOrDefault(c, 0) + 1);
            if (window.get(c) <= need.get(c)) valid++;
        }

        while (valid == t.length()) {
            if (right - left < length) {
                start = left;
                length = right - left;
            }

            char d = s.charAt(left);
            left++;
            if (need.containsKey(d)) {
                if (window.get(d) <= need.get(d)) valid--;
                window.put(d, window.get(d) - 1);
            }
        }
    }
    return length == Integer.MAX_VALUE ? "" : s.substring(start, start + length);
}
```


```cpp
#include <vector>

void backtrack(int n, int k, int start, std::vector<int>& current, std::vector<std::vector<int>>& result) {
    if (current.size() == k) {
        result.push_back(current);
        return;
    }

    for (int i = start; i <= n; ++i) {
        current.push_back(i);
        backtrack(n, k, i + 1, current, result);
        current.pop_back();
    }
}

std::vector<std::vector<int>> combine(int n, int k) {
    std::vector<std::vector<int>> result;
    std::vector<int> current;
    backtrack(n, k, 1, current, result);
    return result;
}
```

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

public List<List<Integer>> combine(int n, int k) {
    List<List<Integer>> result = new ArrayList<>();
    backtrack(n, k, 1, new ArrayList<>(), result);
    return result;
}

private void backtrack(int n, int k, int start, List<Integer> current, List<List<Integer>> result) {
    if (current.size() == k) {
        result.add(new ArrayList<>(current));
        return;
    }

    for (int i = start; i <= n; i++) {
        current.add(i);
        backtrack(n, k, i + 1, current, result);
        current.remove(current.size() - 1);
    }
}
```


```java
public int removeDuplicates(int[] nums) {
    int i = 0;
    for (int num : nums) {
        if (i < 2 || num > nums[i - 2]) {
            nums[i++] = num;
        }
    }
    return i;
}
```

```python
def remove_duplicates(nums):
    i = 0
    for num in nums:
        if i < 2 or num > nums[i - 2]:
            nums[i] = num
            i += 1
    return i
```


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

        if (nums[mid] == nums[left]) {
            left++;
        } else if (nums[mid] > nums[left]) {
            if (nums[left] <= target && target < nums[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        } else {
            if (nums[mid] < target && target <= nums[right]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
    }
    return false;
}
```

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

```cpp
bool search(vector<int>& nums, int target) {
    int left = 0, right = nums.size() - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) return true;

        if (nums[mid] == nums[left]) {
            left++;
        } else if (nums[mid] > nums[left]) {
            if (nums[left] <= target && target < nums[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        } else {
            if (nums[mid] < target && target <= nums[right]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
    }
    return false;
}
```


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

ListNode* deleteDuplicates(ListNode* head) {
    ListNode dummy(0);
    dummy.next = head;
    ListNode *prev = &dummy, *curr = head;
    while (curr) {
        while (curr->next && curr->val == curr->next->val)
            curr = curr->next;
        if (prev->next == curr)
            prev = prev->next;
        else
            prev->next = curr->next;
        curr = curr->next;
    }
    return dummy.next;
}
```

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

public ListNode deleteDuplicates(ListNode head) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode prev = dummy, curr = head;
    while (curr != null) {
        while (curr.next != null && curr.val == curr.next.val)
            curr = curr.next;
        if (prev.next == curr)
            prev = prev.next;
        else
            prev.next = curr.next;
        curr = curr.next;
    }
    return dummy.next;
}
```


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

def delete_duplicates(head):
    current = head
    while current and current.next:
        if current.next.val == current.val:
            current.next = current.next.next
        else:
            current = current.next
    return head
```

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

ListNode* deleteDuplicates(ListNode* head) {
    ListNode* current = head;
    while (current && current->next) {
        if (current->next->val == current->val) {
            ListNode* temp = current->next;
            current->next = temp->next;
            delete temp;
        } else {
            current = current->next;
        }
    }
    return head;
}
```


```java
import java.util.Stack;

public int maximalRectangle(char[][] matrix) {
    if (matrix.length == 0) return 0;

    int m = matrix.length;
    int n = matrix[0].length;
    int[] height = new int[n + 1];
    int maxArea = 0;

    for (int i = 0; i < m; ++i) {
        Stack<Integer> s = new Stack<>();
        for (int j = 0; j <= n; ++j) {
            if (j < n) {
                height[j] = matrix[i][j] == '1' ? height[j] + 1 : 0;
            }
            while (!s.empty() && height[j] < height[s.peek()]) {
                int h = height[s.pop()];
                int w = s.empty() ? j : j - s.peek() - 1;
                maxArea = Math.max(maxArea, h * w);
            }
            s.push(j);
        }
    }

    return maxArea;
}
```

```python
def maximalRectangle(matrix):
    if not matrix:
        return 0

    m = len(matrix)
    n = len(matrix[0])
    height = [0] * (n + 1)
    max_area = 0

    for i in range(m):
        s = []
        for j in range(n + 1):
            if j < n:
                height[j] = height[j] + 1 if matrix[i][j] == '1' else 0
            while s and height[j] < height[s[-1]]:
                h = height[s.pop()]
                w = j if not s else j - s[-1] - 1
                max_area = max(max_area, h * w)
            s.append(j)

    return max_area
```


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

ListNode* partition(ListNode* head, int x) {
    ListNode less_head(0), more_head(0);
    ListNode *less_ptr = &less_head, *more_ptr = &more_head;

    while (head) {
        if (head->val < x) {
            less_ptr->next = head;
            less_ptr = head;
        } else {
            more_ptr->next = head;
            more_ptr = head;
        }
        head = head->next;
    }

    less_ptr->next = more_head.next;
    more_ptr->next = NULL;

    return less_head.next;
}
```

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

def partition(head, x):
    less_head = ListNode(0)
    more_head = ListNode(0)
    less_ptr, more_ptr = less_head, more_head

    while head:
        if head.val < x:
            less_ptr.next = head
            less_ptr = head
        else:
            more_ptr.next = head
            more_ptr = head
        head = head.next

    less_ptr.next = more_head.next
    more_ptr.next = None

    return less_head.next
```


```cpp
bool isScramble(string s1, string s2) {
    if (s1 == s2) return true;
    if (s1.size() != s2.size() || sort(s1.begin(), s1.end()) != sort(s2.begin(), s2.end())) return false;

    for (int i = 1; i < s1.size(); i++) {
        if (isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i), s2.substr(i)))
            return true;
        if (isScramble(s1.substr(0, i), s2.substr(s2.size() - i)) && isScramble(s1.substr(i), s2.substr(0, s2.size() - i)))
            return true;
    }
    return false;
}
```

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

```python
def isScramble(s1: str, s2: str) -> bool:
    if s1 == s2:
        return True
    if len(s1) != len(s2) or sorted(s1) != sorted(s2):
        return False

    for i in range(1, len(s1)):
        if (isScramble(s1[:i], s2[:i]) and isScramble(s1[i:], s2[i:])) or \
           (isScramble(s1[:i], s2[-i:]) and isScramble(s1[i:], s2[:-i])):
            return True
    return False
```


```cpp
#include <vector>

std::vector<int> grayCode(int n) {
    std::vector<int> result;
    for (int i = 0; i < (1 << n); i++) {
        result.push_back(i ^ (i >> 1));
    }
    return result;
}
```


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

vector<vector<int>> subsetsWithDup(vector<int>& nums) {
    set<vector<int>> result;
    vector<int> subset;
    sort(nums.begin(), nums.end());
    backtrack(nums, 0, subset, result);
    return vector<vector<int>>(result.begin(), result.end());
}

void backtrack(vector<int>& nums, int index, vector<int>& subset, set<vector<int>>& result) {
    result.insert(subset);
    for (int i = index; i < nums.size(); i++) {
        subset.push_back(nums[i]);
        backtrack(nums, i + 1, subset, result);
        subset.pop_back();
    }
}
```

```python
from itertools import combinations

def subsetsWithDup(nums):
    result = set()
    nums.sort()
    for i in range(len(nums) + 1):
        for combo in combinations(nums, i):
            result.add(combo)
    return list(result)
```


```python
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
    if not head or left == right:
        return head
    dummy = ListNode(0)
    dummy.next = head
    pre = dummy
    for _ in range(left - 1):
        pre = pre.next
    cur = pre.next
    for _ in range(left, right):
        t = cur.next
        cur.next = t.next
        t.next = pre.next
        pre.next = t
    return dummy.next
```

```java
public ListNode reverseBetween(ListNode head, int left, int right) {
    if (head == null || left == right) return head;
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode pre = dummy;
    for (int i = 1; i < left; ++i) pre = pre.next;
    ListNode cur = pre.next;
    for (int i = left; i < right; ++i) {
        ListNode t = cur.next;
        cur.next = t.next;
        t.next = pre.next;
        pre.next = t;
    }
    return dummy.next;
}
```


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

vector<string> restore_ip_address(string s) {
    vector<string> result;
    string ip;
    dfs(result, s, ip, 0, 0);
    return result;
}

void dfs(vector<string>& result, string s, string ip, int start, int part) {
    if (part == 4 && start == s.size()) {
        ip.pop_back();
        result.push_back(ip);
        return;
    }
    if (part == 4 || start == s.size()) return;

    int num = 0;
    for (int i = start; i < s.size(); i++) {
        num = num * 10 + (s[i] - '0');
        if (num > 255) break;
        ip += s[i];
        dfs(result, s, ip + '.', i + 1, part + 1);
        if (num == 0) break;
    }
}
```

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

public List<String> restoreIpAddresses(String s) {
    List<String> result = new ArrayList<>();
    dfs(s, 0, "", result, 0);
    return result;
}

private void dfs(String s, int start, String ip, List<String> result, int part) {
    if (part == 4 && start == s.length()) {
        result.add(ip.substring(0, ip.length() - 1));
        return;
    }
    if (part == 4 || start >= s.length()) return;

    int num = 0;
    for (int i = start; i < s.length(); i++) {
        num = num * 10 + (s.charAt(i) - '0');
        if (num > 255) break;
        dfs(s, i + 1, ip + s.charAt(i) + ".", result, part + 1);
        if (num == 0) break;
    }
}
```


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

class TreeNode {
public:
    int val;
    TreeNode *left;
    TreeNode *right;
};

void inorderTraversalHelper(TreeNode* root, vector<int>& result) {
    if (!root) return;
    inorderTraversalHelper(root->left, result);
    result.push_back(root->val);
    inorderTraversalHelper(root->right, result);
}

vector<int> inorderTraversal(TreeNode* root){
    vector<int> result;
    inorderTraversalHelper(root, result);
    return result;
}
```

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

def inorderTraversalHelper(root, result):
    if not root:
        return
    inorderTraversalHelper(root.left, result)
    result.append(root.val)
    inorderTraversalHelper(root.right, result)

def inorderTraversal(root):
    result = []
    inorderTraversalHelper(root, result)
    return result
```


```java
public int numTrees(int n) {
    int[] dp = new int[n + 1];
    dp[0] = 1;
    dp[1] = 1;
    for (int i = 2; i <= n; i++) {
        for (int j = 0; j < i; j++) {
            dp[i] += dp[j] * dp[i - j - 1];
        }
    }
    return dp[n];
}
```

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


```python
def isInterleave(s1, s2, s3):
    m, n = len(s1), len(s2)
    if m + n != len(s3):
        return False

    dp = [[False] * (n + 1) for _ in range(m + 1)]
    dp[0][0] = True
    for i in range(1, m + 1):
        dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1]
    for j in range(1, n + 1):
        dp[0][j] = dp[0][j - 1] and s2[j - 1] == s3[j - 1]

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            dp[i][j] = (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or \
                       (dp[i][j - 1] and s2[j - 1] == s3[i + j - 1])

    return dp[m][n]
```

s1 =  "aabcc ", s2 =  "dbbca ", s3 =  "aadbbcbcac "

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

```java
public boolean isInterleave(String s1, String s2, String s3) {
    int m = s1.length(), n = s2.length();
    if (m + n != s3.length()) return false;

    boolean[][] dp = new boolean[m + 1][n + 1];
    dp[0][0] = true;
    for (int i = 1; i <= m; i++)
        dp[i][0] = dp[i - 1][0] && s1.charAt(i - 1) == s3.charAt(i - 1);
    for (int j = 1; j <= n; j++)
        dp[0][j] = dp[0][j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1);

    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            dp[i][j] = (dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) ||
                       (dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1));
        }
    }

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


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

def isValidBSTHelper(node, min_val, max_val):
    if node is None:
        return True
    if not min_val < node.val < max_val:
        return False
    return (isValidBSTHelper(node.left, min_val, node.val) and
            isValidBSTHelper(node.right, node.val, max_val))

def isValidBST(root):
    return isValidBSTHelper(root, float('-inf'), float('inf'))
```

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

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

public boolean isValidBST(TreeNode root) {
    return isValidBSTHelper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

private boolean isValidBSTHelper(TreeNode node, long min, long max) {
    if (node == null) return true;
    if (node.val <= min || node.val >= max) return false;
    return isValidBSTHelper(node.left, min, node.val) && isValidBSTHelper(node.right, node.val, max);
}
```


```cpp
void inorder(TreeNode* node, TreeNode*& first, TreeNode*& second, TreeNode*& prev) {
    if (!node) return;
    inorder(node->left, first, second, prev);
    if (prev && prev->val > node->val) {
        if (!first) first = prev;
        second = node;
    }
    prev = node;
    inorder(node->right, first, second, prev);
}

void recoverTree(TreeNode* root) {
    TreeNode *first = nullptr, *second = nullptr, *prev = nullptr;
    inorder(root, first, second, prev);
    std::swap(first->val, second->val);
}
```

```java
void inorder(TreeNode node, TreeNode[] nodes) {
    if (node == null) return;
    inorder(node.left, nodes);
    if (nodes[1] != null && nodes[1].val > node.val) {
        if (nodes[0] == null) nodes[0] = nodes[1];
        nodes[2] = node;
    }
    nodes[1] = node;
    inorder(node.right, nodes);
}

public void recoverTree(TreeNode root) {
    TreeNode[] nodes = new TreeNode[3];
    inorder(root, nodes);
    int temp = nodes[0].val;
    nodes[0].val = nodes[2].val;
    nodes[2].val = temp;
}
```


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

bool isSameTree(TreeNode* p, TreeNode* q) {
    if (p == nullptr && q == nullptr) {
        return true;
    }
    if (p == nullptr || q == nullptr) {
        return false;
    }
    if (p->val != q->val) {
        return false;
    }
    return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
```

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

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

public boolean isSameTree(TreeNode p, TreeNode q) {
    if (p == null && q == null) {
        return true;
    }
    if (p == null || q == null) {
        return false;
    }
    if (p.val != q.val) {
        return false;
    }
    return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
```


```java
public boolean isSymmetric(TreeNode root) {
    return checkSymmetry(root, root);
}

public boolean checkSymmetry(TreeNode node1, TreeNode node2) {
    if (node1 == null && node2 == null) return true;
    if (node1 == null || node2 == null) return false;
    return (node1.val == node2.val) && checkSymmetry(node1.right, node2.left) && checkSymmetry(node1.left, node2.right);
}
```

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

```cpp
bool isSymmetric(TreeNode* root) {
    return checkSymmetry(root, root);
}

bool checkSymmetry(TreeNode* node1, TreeNode* node2) {
    if (!node1 && !node2) return true;
    if (!node1 || !node2) return false;
    return (node1->val == node2->val) && checkSymmetry(node1->right, node2->left) && checkSymmetry(node1->left, node2->right);
}
```


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

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

std::vector<std::vector<int>> levelOrder(TreeNode* root) {
    std::vector<std::vector<int>> result;
    if(root == nullptr) return result;

    std::queue<TreeNode*> q;
    q.push(root);

    while(!q.empty()) {
        int size = q.size();
        std::vector<int> level;

        for(int i=0; i<size; i++) {
            TreeNode* currNode = q.front();
            level.push_back(currNode->val);

            if(currNode->left) q.push(currNode->left);
            if(currNode->right) q.push(currNode->right);

            q.pop();
        }

        result.push_back(level);
    }

    return result;
}
```

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

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

public List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> result = new ArrayList<>();
    if(root == null) return result;

    Queue<TreeNode> q = new LinkedList<>();
    q.offer(root);

    while(!q.isEmpty()) {
        int size = q.size();
        List<Integer> level = new ArrayList<>();

        for(int i=0; i<size; i++) {
            TreeNode currNode = q.poll();
            level.add(currNode.val);

            if(currNode.left != null) q.offer(currNode.left);
            if(currNode.right != null) q.offer(currNode.right);
        }

        result.add(level);
    }

    return result;
}
```


```java
import java.util.*;

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

public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    if (root == null) return new ArrayList<>();

    List<List<Integer>> result = new ArrayList<>();
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    boolean zigzag = false;

    while (!queue.isEmpty()) {
        int size = queue.size();
        List<Integer> level = new ArrayList<>(size);

        for (int i = 0; i < size; i++) {
            TreeNode node = queue.poll();
            if (zigzag) level.add(0, node.val);
            else level.add(node.val);

            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }

        zigzag = !zigzag;
        result.add(level);
    }

    return result;
}
```

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

using namespace std;

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

vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
    if (!root) return {};

    vector<vector<int>> result;
    queue<TreeNode*> q;
    q.push(root);
    bool zigzag = false;

    while (!q.empty()) {
        int size = q.size();
        vector<int> level(size);

        for (int i = 0; i < size; i++) {
            TreeNode* node = q.front();
            q.pop();

            int index = (zigzag) ? (size - 1 - i) : i;
            level[index] = node->val;

            if (node->left) q.push(node->left);
            if (node->right) q.push(node->right);
        }

        zigzag = !zigzag;
        result.push_back(move(level));
    }

    return result;
}
```


```cpp
int maxDepth(TreeNode* root) {
    if (root == nullptr) {
        return 0;
    }
    return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
```

```python
def maxDepth(root):
    if root is None:
        return 0
    return 1 + max(maxDepth(root.left), maxDepth(root.right))
```


```python
from collections import deque

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

def levelOrderBottom(root):
    result = []
    if not root:
        return result

    queue = deque([root])

    while queue:
        level = []
        size = len(queue)

        for i in range(size):
            current = queue.popleft()
            level.append(current.val)

            if current.left:
                queue.append(current.left)
            if current.right:
                queue.append(current.right)

        result.insert(0, level)

    return result
```

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

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

public List<List<Integer>> levelOrderBottom(TreeNode root) {
    List<List<Integer>> result = new ArrayList<>();
    if (root == null) return result;

    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);

    while (!queue.isEmpty()) {
        List<Integer> level = new ArrayList<>();
        int size = queue.size();

        for (int i = 0; i < size; i++) {
            TreeNode current = queue.poll();
            level.add(current.val);

            if (current.left != null) queue.add(current.left);
            if (current.right != null) queue.add(current.right);
        }
        result.add(0, level);
    }

    return result;
}
```


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

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

def sortedListToBST(head):
    if not head:
        return None
    if not head.next:
        return TreeNode(head.val)
    slow = head
    fast = head
    prev = None

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

    prev.next = None

    root = TreeNode(slow.val)
    root.left = sortedListToBST(head)
    root.right = sortedListToBST(slow.next)
    return root
```

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

class ListNode {
public:
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

TreeNode* sortedListToBST(ListNode* head) {
    if (!head) return NULL;
    if (!head->next) return new TreeNode(head->val);
    ListNode* slow = head;
    ListNode* fast = head;
    ListNode* prev = NULL;

    while (fast && fast->next) {
        prev = slow;
        slow = slow->next;
        fast = fast->next->next;
    }

    prev->next = NULL;

    TreeNode* root = new TreeNode(slow->val);
    root->left = sortedListToBST(head);
    root->right = sortedListToBST(slow->next);
    return root;
}
```


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

def getHeight(node):
    if not node:
        return 0
    left_height = getHeight(node.left)
    right_height = getHeight(node.right)
    if left_height == -1 or right_height == -1 or abs(left_height - right_height) > 1:
        return -1
    return 1 + max(left_height, right_height)

def isBalanced(root):
    return getHeight(root) != -1
```

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

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

public int getHeight(TreeNode node) {
    if (node == null) return 0;
    int leftHeight = getHeight(node.left);
    int rightHeight = getHeight(node.right);
    if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1)
        return -1;
    return 1 + Math.max(leftHeight, rightHeight);
}

public boolean isBalanced(TreeNode root) {
    return getHeight(root) != -1;
}
```


```java
public int minDepth(TreeNode root) {
    if (root == null) return 0;
    int left = minDepth(root.left);
    int right = minDepth(root.right);
    return (left == 0 || right == 0) ? left + right + 1 : Math.min(left, right) + 1;
}
```

```python
def minDepth(root):
    if not root:
        return 0
    left = minDepth(root.left)
    right = minDepth(root.right)
    return (left == 0 or right == 0) and left + right + 1 or min(left, right) + 1
```


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

def hasPathSum(root, targetSum):
    if root is None:
        return False
    if root.left is None and root.right is None:
        return targetSum - root.val == 0
    return hasPathSum(root.left, targetSum - root.val) or hasPathSum(root.right, targetSum - root.val)
```

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

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

bool hasPathSum(TreeNode* root, int targetSum) {
    if (!root) return false;
    if (!root->left && !root->right) return targetSum - root->val == 0;
    return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);
}
```


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

void helper(TreeNode* root, int targetSum, vector<int>& current, vector<vector<int>>& ans) {
    if (!root) return;
    current.push_back(root->val);
    if (!root->left && !root->right && targetSum == root->val) {
        ans.push_back(current);
    }
    helper(root->left, targetSum - root->val, current, ans);
    helper(root->right, targetSum - root->val, current, ans);
    current.pop_back();
}

vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
    vector<vector<int>> ans;
    vector<int> current;
    helper(root, targetSum, current, ans);
    return ans;
}
```

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

def pathSum(root, targetSum):
    def helper(root, targetSum, current, ans):
        if not root:
            return
        current.append(root.val)
        if not root.left and not root.right and targetSum == root.val:
            ans.append(current[:])
        helper(root.left, targetSum - root.val, current, ans)
        helper(root.right, targetSum - root.val, current, ans)
        current.pop()

    ans = []
    helper(root, targetSum, [], ans)
    return ans
```


```java
public void flatten(TreeNode root) {
    if (root == null) return;
    flatten(root.left);
    flatten(root.right);
    if (root.left != null) {
        TreeNode temp = root.right;
        root.right = root.left;
        root.left = null;
        while (root.right != null) root = root.right;
        root.right = temp;
    }
}
```

```python
def flatten(root):
    if not root:
        return
    flatten(root.left)
    flatten(root.right)
    if root.left:
        temp = root.right
        root.right = root.left
        root.left = None
        while root.right:
            root = root.right
        root.right = temp
```


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

    for i in range(m + 1):
        dp[i][0] = 1

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if s[i - 1] == t[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]
            else:
                dp[i][j] = dp[i - 1][j]

    return dp[m][n]
```

```java
public int numDistinct(String s, String t) {
    int m = s.length(), n = t.length();
    int[][] dp = new int[m + 1][n + 1];

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

    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (s.charAt(i - 1) == t.charAt(j - 1)) {
                dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
            } else {
                dp[i][j] = dp[i - 1][j];
            }
        }
    }

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


```python
def generate(numRows):
    pascalsTriangle = []
    for i in range(numRows):
        row = [1]
        if i > 0:
            for j in range(1, i):
                row.append(pascalsTriangle[i-1][j-1] + pascalsTriangle[i-1][j])
            row.append(1)
        pascalsTriangle.append(row)
    return pascalsTriangle
```

```cpp
vector<vector<int>> generate(int numRows) {
    vector<vector<int>> pascalsTriangle(numRows);
    for (int i = 0; i < numRows; i++) {
        pascalsTriangle[i].resize(i + 1);
        pascalsTriangle[i][0] = pascalsTriangle[i][i] = 1;
        for (int j = 1; j < i; j++) {
            pascalsTriangle[i][j] = pascalsTriangle[i - 1][j - 1] + pascalsTriangle[i - 1][j];
        }
    }
    return pascalsTriangle;
}
```


```python
def get_row(rowIndex):
    row = [1] * (rowIndex + 1)
    for i in range(1, rowIndex + 1):
        for j in range(i - 1, 0, -1):
            row[j] += row[j - 1]
    return row
```

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

vector<int> getRow(int rowIndex) {
    vector<int> row(rowIndex + 1, 1);
    for (int i = 1; i <= rowIndex; i++) {
        for (int j = i - 1; j > 0; j--) {
            row[j] += row[j - 1];
        }
    }
    return row;
}
```


```java
public int maxProfit(int[] prices) {
    int minPrice = Integer.MAX_VALUE;
    int maxProfit = 0;
    for (int price : prices) {
        minPrice = Math.min(minPrice, price);
        maxProfit = Math.max(maxProfit, price - minPrice);
    }
    return maxProfit;
}
```

```python
def maxProfit(prices):
    minPrice = float('inf')
    maxProfit = 0
    for price in prices:
        minPrice = min(minPrice, price)
        maxProfit = max(maxProfit, price - minPrice)
    return maxProfit
```


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

public int maxPathSum(TreeNode root) {
    int[] maxSum = new int[]{Integer.MIN_VALUE};
    helper(root, maxSum);
    return maxSum[0];
}

private int helper(TreeNode root, int[] maxSum) {
    if (root == null) return 0;

    int left = Math.max(0, helper(root.left, maxSum));
    int right = Math.max(0, helper(root.right, maxSum));

    maxSum[0] = Math.max(maxSum[0], left + right + root.val);

    return Math.max(left, right) + root.val;
}
```

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

def maxPathSum(root: TreeNode) -> int:
    def helper(root):
        nonlocal maxSum
        if not root:
            return 0

        left = max(0, helper(root.left))
        right = max(0, helper(root.right))

        maxSum = max(maxSum, left + right + root.val)

        return max(left, right) + root.val

    maxSum = float('-inf')
    helper(root)
    return maxSum
```


```python
from collections import defaultdict, deque

def findLadders(beginWord, endWord, wordList):
    wordList = set(wordList)
    if endWord not in wordList:
        return []

    adjacent = defaultdict(list)
    distance = defaultdict(int)
    queue = deque([beginWord])
    distance[beginWord] = 0

    def neighbors(word):
        for i in range(len(word)):
            for j in range(ord('a'), ord('z') + 1):
                yield word[:i] + chr(j) + word[i + 1:]

    while queue:
        current = queue.popleft()
        if current == endWord:
            break
        for neighbor in neighbors(current):
            if neighbor not in wordList:
                continue
            if neighbor not in distance:
                distance[neighbor] = distance[current] + 1
                queue.append(neighbor)
            if distance[neighbor] == distance[current] + 1:
                adjacent[current].append(neighbor)

    result = []
    path = [beginWord]

    def backtrack(word):
        if word == endWord:
            result.append(path[:])
        else:
            for next_word in adjacent[word]:
                path.append(next_word)
                backtrack(next_word)
                path.pop()

    backtrack(beginWord)
    return result
```

beginWord =  "hit ", endWord =  "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]

cat
dog
["cat", "cot", "cog", "dog", "cog", "dog"]

hit
cog
[ "hot ", "dot ", "dog ", "cog ", "lot ", "log "]

create
destroy
["create", "created", "created", "created", "created", "destroy"]

run
walk
["run", "ran", "rang", "rung", "rung", "walk"]

buy
sell
["buy", "buy", "buy", "buy", "buy", "sell"]

open
close
["open", "opened", "opened", "opened", "opened", "close"]

eat
drink
["eat", "eaten", "eaten", "eaten", "eaten", "drink"]

hit
cog
[ "hot ", "dot ", "dog ", "lot ", "log "]

earth
moon
["earth", "mars", "mars", "mars", "mars", "moon"]

read
blue
["bred", "breed", "bleed", "blue", "blew"]

learn
forget
["learn", "learnt", "learnt", "learnt", "learnt", "forget"]

paper
rock
["paper", "per", "pear", "pear", "pear", "rock"]

ruby
sapphire
["rubs", "rube", "ruse", "rush", "sush", "sapphire"]

cake
pie
["cake", "bake", "baker", "pie", "piecrust", "pies"]

go
stop
["go", "got", "got", "got", "got", "stop"]

hit
cog
[ "cog ", "log ", "lot ", "dog ", "dot ", "hot "]

apple
banana
["apple", "app", "apply", "applied", "apply", "banana"]

sing
dance
["sing", "sang", "sung", "sung", "sung", "dance"]

hit
cog
[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "]

pear
grape
["pear", "bear", "sear", "grape", "grape", "grapes"]

gold
silver
["gold", "golf", "golfed", "golfers", "golfing", "silver"]

horse
zebra
["hose", "horse", "hover", "hovercraft", "zebra", "zebrahead"]

oak
beech
["oak", "oakland", "beech", "beechwood", "beechtree", "beechforest"]

drive
fly
["drive", "drived", "drove", "droven", "droven", "fly"]

win
lose
["win", "won", "won", "won", "won", "lose"]

book
film
["book", "look", "lock", "clook", "clock", "film"]

mud
stone
["mud", "muddle", "muddler", "muddling", "muddled", "stone"]

cake
bread
["cake", "cakey", "cake", "bake", "bread", "bread"]

water
air
["water", "wate", "watt", "watt", "watt", "air"]

lead
gold
["load", "goad", "gold", "mold", "hold", "gold"]

play
work
["play", "ply", "ply", "ply", "ply", "work"]

love
hate
["love", "loved", "loved", "loved", "loved", "hate"]

start
finish
["start", "started", "started", "started", "started", "finish"]

tree
plant
["tree", "trie", "triad", "triad", "triad", "plant"]

hit
cog
[ "hot ", "dot ", "dog ", "lot ", "log ", "cog ", "hit "]

code
decode
["code", "coded", "coder", "coders", "coders", "decode"]

read
write
["read", "red", "wed", "wed", "wed", "write"]

build
demolish
["build", "built", "built", "built", "built", "demolish"]

grape
apple
["grasp", "grass", "grasshopper", "graze", "gaze", "gazebo", "apple"]

dirt
sand
["dirty", "dirt", "dirtier", "dirties", "dirtiest", "sand"]

sea
land
["sea", "see", "see", "see", "see", "land"]

jump
fly
["jump", "jumbo", "jumbo", "jumbo", "jumbo", "fly"]

pine
oak
["pine", "oak", "oaken", "oakens", "oakley", "oakwood", "oakland"]

hit
cog
[ "hot ", "dot ", "dog ", "lot ", "log ", "cog ", "hog ", "hop "]

make
break
["make", "made", "made", "made", "made", "break"]

fire
ice
["fire", "fiery", "fiery", "fiery", "fiery", "ice"]

live
die
["live", "lived", "lived", "lived", "lived", "die"]

sky
moon
["skew", "sky", "skim", "skate", "skull", "moon"]

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

std::vector<std::vector<std::string>> findLadders(std::string beginWord, std::string endWord, std::vector<std::string>& wordList) {
    std::unordered_set<std::string> dict(wordList.begin(), wordList.end());
    if (dict.find(endWord) == dict.end()) {
        return {};
    }
    std::unordered_map<std::string, std::vector<std::string>> adjacent;
    std::unordered_map<std::string, int> distance;

    auto neighbors = [&](const std::string& word) {
        std::vector<std::string> result;
        std::string temp = word;
        for (char& ch : temp) {
            char original = ch;
            for (int i = 'a'; i <= 'z'; ++i) {
                ch = i;
                if (dict.count(temp) && temp != word) {
                    result.push_back(temp);
                }
            }
            ch = original;
        }
        return result;
    };

    std::queue<std::string> q;
    q.push(beginWord);
    distance[beginWord] = 0;

    while (!q.empty()) {
        std::string current = q.front();
        q.pop();
        if (current == endWord) {
            break;
        }
        for (const std::string& neighbor : neighbors(current)) {
            if (!distance.count(neighbor)) {
                distance[neighbor] = distance[current] + 1;
                q.push(neighbor);
            }
            if (distance[neighbor] == distance[current] + 1) {
                adjacent[current].push_back(neighbor);
            }
        }
    }

    std::vector<std::vector<std::string>> result;
    std::vector<std::string> path = {beginWord};
    std::function<void(const std::string&)> backtrack = [&](const std::string& word) {
        if (word == endWord) {
            result.push_back(path);
            return;
        }
        for (const std::string& next : adjacent[word]) {
            path.push_back(next);
            backtrack(next);
            path.pop_back();
        }
    };

    backtrack(beginWord);
    return result;
}
```


```python
from collections import deque

def ladderLength(beginWord, endWord, wordList):
    word_set = set(wordList)
    if endWord not in word_set:
        return 0

    q = deque([beginWord])
    steps = 1

    while q:
        size = len(q)
        current_level = set()

        for _ in range(size):
            current_word = q.popleft()
            if current_word == endWord:
                return steps

            word_chars = list(current_word)
            for i in range(len(word_chars)):
                original_char = word_chars[i]
                for j in range(26):
                    word_chars[i] = chr(ord('a') + j)
                    new_word = ''.join(word_chars)
                    if new_word in word_set:
                        q.append(new_word)
                        current_level.add(new_word)

                word_chars[i] = original_char

        word_set -= current_level
        steps += 1

    return 0
```

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "dot", "log"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "dot", "lot", "log"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "dot", "dog", "lot", "log"]

sea
eat
["eat", "ate", "ats", "bat", "bet", "bit"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "dot", "dog"]

hit
cog
["hot", "dot", "dog", "lot", "log"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "dog", "lot"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "lot"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "dot", "dog", "log"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "dot", "lot"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "dot", "dog", "log"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "log"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "dog", "log"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "dog"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "dog", "lot"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "dot", "dog"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "dot", "log"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "lot", "log"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "dot", "lot", "log"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "dot", "lot"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "lot"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "lot", "log"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "cog"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "dot"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "log"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "dot", "dog", "lot"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "dog", "lot", "log"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "dog"]

hot
cog
["hot", "dot", "dog", "cog", "hog"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "dog", "lot", "log"]

hit
cog
[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "dot"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "dot", "dog", "lot"]

hit
cog
["hot", "dot", "dog", "lot", "log", "cog", "hit", "hot", "dog", "log"]

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

int ladderLength(std::string beginWord, std::string endWord, std::vector<std::string>& wordList) {
    std::unordered_set<std::string> dict(wordList.begin(), wordList.end());
    if (!dict.count(endWord)) return 0;

    std::queue<std::string> q;
    q.push(beginWord);
    int steps = 1;

    while (!q.empty()) {
        int size = q.size();
        for (int i = 0; i < size; ++i) {
            std::string currentWord = q.front();
            q.pop();
            if (currentWord == endWord) return steps;

            for (char& c : currentWord) {
                char originalChar = c;
                for (int j = 0; j < 26; ++j) {
                    c = 'a' + j;
                    if (dict.count(currentWord)) {
                        q.push(currentWord);
                        dict.erase(currentWord);
                    }
                }
                c = originalChar;
            }
        }
        ++steps;
    }
    return 0;
}
```


```python
def longest_consecutive(nums):
    elements = set(nums)
    longest_seq = 0

    for num in nums:
        if num - 1 not in elements:
            current_num = num
            current_seq = 1

            while current_num + 1 in elements:
                current_num += 1
                current_seq += 1

            longest_seq = max(longest_seq, current_seq)

    return longest_seq
```

```java
public int longestConsecutive(int[] nums) {
    Set<Integer> elements = new HashSet<>();
    for (int num : nums) {
        elements.add(num);
    }

    int longestSeq = 0;

    for (int num : nums) {
        if (!elements.contains(num - 1)) {
            int currentNum = num;
            int currentSeq = 1;

            while (elements.contains(currentNum + 1)) {
                currentNum++;
                currentSeq++;
            }

            longestSeq = Math.max(longestSeq, currentSeq);
        }
    }
    return longestSeq;
}
```


```python
def sumNumbers(root, cur=0):
    if root is None: return 0
    cur = cur * 10 + root.val
    if root.left is None and root.right is None: return cur
    return sumNumbers(root.left, cur) + sumNumbers(root.right, cur)
```

```cpp
int sumNumbers(TreeNode* root, int cur = 0) {
    if (!root) return 0;
    cur = cur * 10 + root->val;
    if (!root->left && !root->right) return cur;
    return sumNumbers(root->left, cur) + sumNumbers(root->right, cur);
}
```


```java
class Solution {
    public void solve(char[][] board) {
        if (board.length == 0) return;
        int m = board.length, n = board[0].length;

        for (int i = 0; i < m; ++i) {
            dfs(board, i, 0);
            dfs(board, i, n - 1);
        }
        for (int i = 0; i < n; ++i) {
            dfs(board, 0, i);
            dfs(board, m - 1, i);
        }
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (board[i][j] == '#') board[i][j] = 'O';
                else if (board[i][j] == 'O') board[i][j] = 'X';
            }
        }
    }

    private void dfs(char[][] board, int x, int y) {
        if (x < 0 || x >= board.length || y < 0 || y >= board[0].length || board[x][y] != 'O') {
            return;
        }
        board[x][y] = '#';
        dfs(board, x - 1, y);
        dfs(board, x + 1, y);
        dfs(board, x, y - 1);
        dfs(board, x, y + 1);
    }
}
```

```cpp
#include <vector>

void dfs(std::vector<std::vector<char>> &board, int x, int y) {
    if (x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || board[x][y] != 'O') {
        return;
    }
    board[x][y] = '#';
    dfs(board, x - 1, y);
    dfs(board, x + 1, y);
    dfs(board, x, y - 1);
    dfs(board, x, y + 1);
}

void solve(std::vector<std::vector<char>>& board) {
    if (board.empty()) return;
    int m = board.size(), n = board[0].size();

    for (int i = 0; i < m; ++i) {
        dfs(board, i, 0);
        dfs(board, i, n - 1);
    }
    for (int i = 0; i < n; ++i) {
        dfs(board, 0, i);
        dfs(board, m - 1, i);
    }
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (board[i][j] == '#') board[i][j] = 'O';
            else if (board[i][j] == 'O') board[i][j] = 'X';
        }
    }
}
```