ShwStone/humaneval-leetcode huggingface dataset:
# class TreeNode:
#     def __init__(val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(root: Optional[TreeNode]) -> int:
    """
    Given the root of a binary tree, return the length of the diameter of the tree.
    The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
    The length of a path between two nodes is represented by the number of edges between them.
    
    Example 1:
    
    
    >>> __init__(root = [1,2,3,4,5])
    >>> 3
    Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
    
    Example 2:
    
    >>> __init__(root = [1,2])
    >>> 1
    """
def findContestMatch(n: int) -> str:
    """
    During the NBA playoffs, we always set the rather strong team to play with the rather weak team, like making the rank 1 team play with the rank nth team, which is a good strategy to make the contest more interesting.
    Given n teams, return their final contest matches in the form of a string.
    The n teams are labeled from 1 to n, which represents their initial rank (i.e., Rank 1 is the strongest team and Rank n is the weakest team).
    We will use parentheses '(', and ')' and commas ',' to represent the contest team pairing. We use the parentheses for pairing and the commas for partition. During the pairing process in each round, you always need to follow the strategy of making the rather strong one pair with the rather weak one.
    
    Example 1:
    
    >>> findContestMatch(n = 4)
    >>> "((1,4),(2,3))"
    Explanation:
    In the first round, we pair the team 1 and 4, the teams 2 and 3 together, as we need to make the strong team and weak team together.
    And we got (1, 4),(2, 3).
    In the second round, the winners of (1, 4) and (2, 3) need to play again to generate the final winner, so you need to add the paratheses outside them.
    And we got the final answer ((1,4),(2,3)).
    
    Example 2:
    
    >>> findContestMatch(n = 8)
    >>> "(((1,8),(4,5)),((2,7),(3,6)))"
    Explanation:
    First round: (1, 8),(2, 7),(3, 6),(4, 5)
    Second round: ((1, 8),(4, 5)),((2, 7),(3, 6))
    Third round: (((1, 8),(4, 5)),((2, 7),(3, 6)))
    Since the third round will generate the final winner, you need to output the answer (((1,8),(4,5)),((2,7),(3,6))).
    """
# class TreeNode:
#     def __init__(val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def boundaryOfBinaryTree(root: Optional[TreeNode]) -> List[int]:
    """
    The boundary of a binary tree is the concatenation of the root, the left boundary, the leaves ordered from left-to-right, and the reverse order of the right boundary.
    The left boundary is the set of nodes defined by the following:
    
    The root node's left child is in the left boundary. If the root does not have a left child, then the left boundary is empty.
    If a node in the left boundary and has a left child, then the left child is in the left boundary.
    If a node is in the left boundary, has no left child, but has a right child, then the right child is in the left boundary.
    The leftmost leaf is not in the left boundary.
    
    The right boundary is similar to the left boundary, except it is the right side of the root's right subtree. Again, the leaf is not part of the right boundary, and the right boundary is empty if the root does not have a right child.
    The leaves are nodes that do not have any children. For this problem, the root is not a leaf.
    Given the root of a binary tree, return the values of its boundary.
    
    Example 1:
    
    
    >>> __init__(root = [1,null,2,3,4])
    >>> [1,3,4,2]
    Explanation:
    - The left boundary is empty because the root does not have a left child.
    - The right boundary follows the path starting from the root's right child 2 -> 4.
      4 is a leaf, so the right boundary is [2].
    - The leaves from left to right are [3,4].
    Concatenating everything results in [1] + [] + [3,4] + [2] = [1,3,4,2].
    
    Example 2:
    
    
    >>> __init__(root = [1,2,3,4,5,6,null,null,null,7,8,9,10])
    >>> [1,2,4,7,8,9,10,6,3]
    Explanation:
    - The left boundary follows the path starting from the root's left child 2 -> 4.
      4 is a leaf, so the left boundary is [2].
    - The right boundary follows the path starting from the root's right child 3 -> 6 -> 10.
      10 is a leaf, so the right boundary is [3,6], and in reverse order is [6,3].
    - The leaves from left to right are [4,7,8,9,10].
    Concatenating everything results in [1] + [2] + [4,7,8,9,10] + [6,3] = [1,2,4,7,8,9,10,6,3].
    """
def removeBoxes(boxes: List[int]) -> int:
    """
    You are given several boxes with different colors represented by different positive numbers.
    You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1), remove them and get k * k points.
    Return the maximum points you can get.
    
    Example 1:
    
    >>> removeBoxes(boxes = [1,3,2,2,2,3,4,3,1])
    >>> 23
    Explanation:
    [1, 3, 2, 2, 2, 3, 4, 3, 1]
    ----> [1, 3, 3, 4, 3, 1] (3*3=9 points)
    ----> [1, 3, 3, 3, 1] (1*1=1 points)
    ----> [1, 1] (3*3=9 points)
    ----> [] (2*2=4 points)
    
    Example 2:
    
    >>> removeBoxes(boxes = [1,1,1])
    >>> 9
    
    Example 3:
    
    >>> removeBoxes(boxes = [1])
    >>> 1
    """
def findCircleNum(isConnected: List[List[int]]) -> int:
    """
    There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
    A province is a group of directly or indirectly connected cities and no other cities outside of the group.
    You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.
    Return the total number of provinces.
    
    Example 1:
    
    
    >>> findCircleNum(isConnected = [[1,1,0],[1,1,0],[0,0,1]])
    >>> 2
    
    Example 2:
    
    
    >>> findCircleNum(isConnected = [[1,0,0],[0,1,0],[0,0,1]])
    >>> 3
    """
def splitArray(nums: List[int]) -> bool:
    """
    Given an integer array nums of length n, return true if there is a triplet (i, j, k) which satisfies the following conditions:
    
    0 < i, i + 1 < j, j + 1 < k < n - 1
    The sum of subarrays (0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1) is equal.
    
    A subarray (l, r) represents a slice of the original array starting from the element indexed l to the element indexed r.
    
    Example 1:
    
    >>> splitArray(nums = [1,2,1,2,1,2,1])
    >>> true
    Explanation:
    i = 1, j = 3, k = 5.
    sum(0, i - 1) = sum(0, 0) = 1
    sum(i + 1, j - 1) = sum(2, 2) = 1
    sum(j + 1, k - 1) = sum(4, 4) = 1
    sum(k + 1, n - 1) = sum(6, 6) = 1
    
    Example 2:
    
    >>> splitArray(nums = [1,2,1,2,1,2,1,2])
    >>> false
    """
# class TreeNode:
#     def __init__(val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def longestConsecutive(root: Optional[TreeNode]) -> int:
    """
    Given the root of a binary tree, return the length of the longest consecutive path in the tree.
    A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either increasing or decreasing.
    
    For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid.
    
    On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.
    
    Example 1:
    
    
    >>> __init__(root = [1,2,3])
    >>> 2
    Explanation: The longest consecutive path is [1, 2] or [2, 1].
    
    Example 2:
    
    
    >>> __init__(root = [2,1,3])
    >>> 3
    Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].
    """
def checkRecord(s: str) -> bool:
    """
    You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
    
    'A': Absent.
    'L': Late.
    'P': Present.
    
    The student is eligible for an attendance award if they meet both of the following criteria:
    
    The student was absent ('A') for strictly fewer than 2 days total.
    The student was never late ('L') for 3 or more consecutive days.
    
    Return true if the student is eligible for an attendance award, or false otherwise.
    
    Example 1:
    
    >>> checkRecord(s = "PPALLP")
    >>> true
    Explanation: The student has fewer than 2 absences and was never late 3 or more consecutive days.
    
    Example 2:
    
    >>> checkRecord(s = "PPALLL")
    >>> false
    Explanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.
    """
def checkRecord(n: int) -> int:
    """
    An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
    
    'A': Absent.
    'L': Late.
    'P': Present.
    
    Any student is eligible for an attendance award if they meet both of the following criteria:
    
    The student was absent ('A') for strictly fewer than 2 days total.
    The student was never late ('L') for 3 or more consecutive days.
    
    Given an integer n, return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large, so return it modulo 109 + 7.
    
    Example 1:
    
    >>> checkRecord(n = 2)
    >>> 8
    Explanation: There are 8 records with length 2 that are eligible for an award:
    "PP", "AP", "PA", "LP", "PL", "AL", "LA", "LL"
    Only "AA" is not eligible because there are 2 absences (there need to be fewer than 2).
    
    Example 2:
    
    >>> checkRecord(n = 1)
    >>> 3
    
    Example 3:
    
    >>> checkRecord(n = 10101)
    >>> 183236316
    """
def optimalDivision(nums: List[int]) -> str:
    """
    You are given an integer array nums. The adjacent integers in nums will perform the float division.
    
    For example, for nums = [2,3,4], we will evaluate the expression "2/3/4".
    
    However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.
    Return the corresponding expression that has the maximum value in string format.
    Note: your expression should not contain redundant parenthesis.
    
    Example 1:
    
    >>> optimalDivision(nums = [1000,100,10,2])
    >>> "1000/(100/10/2)"
    Explanation: 1000/(100/10/2) = 1000/((100/10)/2) = 200
    However, the bold parenthesis in "1000/((100/10)/2)" are redundant since they do not influence the operation priority.
    So you should return "1000/(100/10/2)".
    Other cases:
    1000/(100/10)/2 = 50
    1000/(100/(10/2)) = 50
    1000/100/10/2 = 0.5
    1000/100/(10/2) = 2
    
    Example 2:
    
    >>> optimalDivision(nums = [2,3,4])
    >>> "2/(3/4)"
    Explanation: (2/(3/4)) = 8/3 = 2.667
    It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667
    """
def leastBricks(wall: List[List[int]]) -> int:
    """
    There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.
    Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.
    Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line.
    
    Example 1:
    
    
    >>> leastBricks(wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]])
    >>> 2
    
    Example 2:
    
    >>> leastBricks(wall = [[1],[1],[1]])
    >>> 3
    """
def splitLoopedString(strs: List[str]) -> str:
    """
    You are given an array of strings strs. You could concatenate these strings together into a loop, where for each string, you could choose to reverse it or not. Among all the possible loops
    Return the lexicographically largest string after cutting the loop, which will make the looped string into a regular one.
    Specifically, to find the lexicographically largest string, you need to experience two phases:
    
    Concatenate all the strings into a loop, where you can reverse some strings or not and connect them in the same order as given.
    Cut and make one breakpoint in any place of the loop, which will make the looped string into a regular one starting from the character at the cutpoint.
    
    And your job is to find the lexicographically largest one among all the possible regular strings.
    
    Example 1:
    
    >>> splitLoopedString(strs = ["abc","xyz"])
    >>> "zyxcba"
    Explanation: You can get the looped string "-abcxyz-", "-abczyx-", "-cbaxyz-", "-cbazyx-", where '-' represents the looped status.
    The answer string came from the fourth looped one, where you could cut from the middle character 'a' and get "zyxcba".
    
    Example 2:
    
    >>> splitLoopedString(strs = ["abc"])
    >>> "cba"
    """
def nextGreaterElement(n: int) -> int:
    """
    Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1.
    Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.
    
    Example 1:
    >>> nextGreaterElement(n = 12)
    >>> 21
    Example 2:
    >>> nextGreaterElement(n = 21)
    >>> -1
    """
def reverseWords(s: str) -> str:
    """
    Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
    
    Example 1:
    
    >>> reverseWords(s = "Let's take LeetCode contest")
    >>> "s'teL ekat edoCteeL tsetnoc"
    
    Example 2:
    
    >>> reverseWords(s = "Mr Ding")
    >>> "rM gniD"
    """
def subarraySum(nums: List[int], k: int) -> int:
    """
    Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.
    A subarray is a contiguous non-empty sequence of elements within an array.
    
    Example 1:
    >>> subarraySum(nums = [1,1,1], k = 2)
    >>> 2
    Example 2:
    >>> subarraySum(nums = [1,2,3], k = 3)
    >>> 2
    """
def arrayPairSum(nums: List[int]) -> int:
    """
    Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.
    
    Example 1:
    
    >>> arrayPairSum(nums = [1,4,3,2])
    >>> 4
    Explanation: All possible pairings (ignoring the ordering of elements) are:
    1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
    2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
    3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
    So the maximum possible sum is 4.
    Example 2:
    
    >>> arrayPairSum(nums = [6,2,6,5,1,2])
    >>> 9
    Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
    """
def longestLine(mat: List[List[int]]) -> int:
    """
    Given an m x n binary matrix mat, return the length of the longest line of consecutive one in the matrix.
    The line could be horizontal, vertical, diagonal, or anti-diagonal.
    
    Example 1:
    
    
    >>> longestLine(mat = [[0,1,1,0],[0,1,1,0],[0,0,0,1]])
    >>> 3
    
    Example 2:
    
    
    >>> longestLine(mat = [[1,1,1,1],[0,1,1,0],[0,0,0,1]])
    >>> 4
    """
# class TreeNode:
#     def __init__(val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findTilt(root: Optional[TreeNode]) -> int:
    """
    Given the root of a binary tree, return the sum of every tree node's tilt.
    The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if the node does not have a right child.
    
    Example 1:
    
    
    >>> __init__(root = [1,2,3])
    >>> 1
    Explanation:
    Tilt of node 2 : |0-0| = 0 (no children)
    Tilt of node 3 : |0-0| = 0 (no children)
    Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)
    Sum of every tilt : 0 + 0 + 1 = 1
    
    Example 2:
    
    
    >>> __init__(root = [4,2,9,3,5,null,7])
    >>> 15
    Explanation:
    Tilt of node 3 : |0-0| = 0 (no children)
    Tilt of node 5 : |0-0| = 0 (no children)
    Tilt of node 7 : |0-0| = 0 (no children)
    Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)
    Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)
    Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)
    Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15
    
    Example 3:
    
    
    >>> __init__(root = [21,7,14,1,1,2,2,3,3])
    >>> 9
    """
def nearestPalindromic(n: str) -> str:
    """
    Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.
    The closest is defined as the absolute difference minimized between two integers.
    
    Example 1:
    
    >>> nearestPalindromic(n = "123")
    >>> "121"
    
    Example 2:
    
    >>> nearestPalindromic(n = "1")
    >>> "0"
    Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.
    """
def arrayNesting(nums: List[int]) -> int:
    """
    You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1].
    You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:
    
    The first element in s[k] starts with the selection of the element nums[k] of index = k.
    The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.
    We stop adding right before a duplicate element occurs in s[k].
    
    Return the longest length of a set s[k].
    
    Example 1:
    
    >>> arrayNesting(nums = [5,4,0,3,1,6,2])
    >>> 4
    Explanation:
    nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
    One of the longest sets s[k]:
    s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}
    
    Example 2:
    
    >>> arrayNesting(nums = [0,1,2])
    >>> 1
    """
def matrixReshape(mat: List[List[int]], r: int, c: int) -> List[List[int]]:
    """
    In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.
    You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.
    The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.
    If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
    
    Example 1:
    
    
    >>> matrixReshape(mat = [[1,2],[3,4]], r = 1, c = 4)
    >>> [[1,2,3,4]]
    
    Example 2:
    
    
    >>> matrixReshape(mat = [[1,2],[3,4]], r = 2, c = 4)
    >>> [[1,2],[3,4]]
    """
def checkInclusion(s1: str, s2: str) -> bool:
    """
    Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
    In other words, return true if one of s1's permutations is the substring of s2.
    
    Example 1:
    
    >>> checkInclusion(s1 = "ab", s2 = "eidbaooo")
    >>> true
    Explanation: s2 contains one permutation of s1 ("ba").
    
    Example 2:
    
    >>> checkInclusion(s1 = "ab", s2 = "eidboaoo")
    >>> false
    """
# class TreeNode:
#     def __init__(val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSubtree(root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
    """
    Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.
    A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.
    
    Example 1:
    
    
    >>> __init__(root = [3,4,5,1,2], subRoot = [4,1,2])
    >>> true
    
    Example 2:
    
    
    >>> __init__(root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2])
    >>> false
    """
def minDistance(height: int, width: int, tree: List[int], squirrel: List[int], nuts: List[List[int]]) -> int:
    """
    You are given two integers height and width representing a garden of size height x width. You are also given:
    
    an array tree where tree = [treer, treec] is the position of the tree in the garden,
    an array squirrel where squirrel = [squirrelr, squirrelc] is the position of the squirrel in the garden,
    and an array nuts where nuts[i] = [nutir, nutic] is the position of the ith nut in the garden.
    
    The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell.
    Return the minimal distance for the squirrel to collect all the nuts and put them under the tree one by one.
    The distance is the number of moves.
    
    Example 1:
    
    
    >>> minDistance(height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]])
    >>> 12
    Explanation: The squirrel should go to the nut at [2, 5] first to achieve a minimal distance.
    
    Example 2:
    
    
    >>> minDistance(height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]])
    >>> 3
    """