ShwStone/humaneval-leetcode huggingface dataset:
def minSwaps(data: List[int]) -> int:
    """
    Given a binary array data, return the minimum number of swaps required to group all 1’s present in the array together in any place in the array.
    
    Example 1:
    
    >>> minSwaps(data = [1,0,1,0,1])
    >>> 1
    Explanation: There are 3 ways to group all 1's together:
    [1,1,1,0,0] using 1 swap.
    [0,1,1,1,0] using 2 swaps.
    [0,0,1,1,1] using 1 swap.
    The minimum is 1.
    
    Example 2:
    
    >>> minSwaps(data = [0,0,0,1,0])
    >>> 0
    Explanation: Since there is only one 1 in the array, no swaps are needed.
    
    Example 3:
    
    >>> minSwaps(data = [1,0,1,0,1,0,0,1,1,0,1])
    >>> 3
    Explanation: One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].
    """
def mostVisitedPattern(username: List[str], timestamp: List[int], website: List[str]) -> List[str]:
    """
    You are given two string arrays username and website and an integer array timestamp. All the given arrays are of the same length and the tuple [username[i], website[i], timestamp[i]] indicates that the user username[i] visited the website website[i] at time timestamp[i].
    A pattern is a list of three websites (not necessarily distinct).
    
    For example, ["home", "away", "love"], ["leetcode", "love", "leetcode"], and ["luffy", "luffy", "luffy"] are all patterns.
    
    The score of a pattern is the number of users that visited all the websites in the pattern in the same order they appeared in the pattern.
    
    For example, if the pattern is ["home", "away", "love"], the score is the number of users x such that x visited "home" then visited "away" and visited "love" after that.
    Similarly, if the pattern is ["leetcode", "love", "leetcode"], the score is the number of users x such that x visited "leetcode" then visited "love" and visited "leetcode" one more time after that.
    Also, if the pattern is ["luffy", "luffy", "luffy"], the score is the number of users x such that x visited "luffy" three different times at different timestamps.
    
    Return the pattern with the largest score. If there is more than one pattern with the same largest score, return the lexicographically smallest such pattern.
    Note that the websites in a pattern do not need to be visited contiguously, they only need to be visited in the order they appeared in the pattern.
    
    Example 1:
    
    >>> mostVisitedPattern(username = ["joe","joe","joe","james","james","james","james","mary","mary","mary"], timestamp = [1,2,3,4,5,6,7,8,9,10], website = ["home","about","career","home","cart","maps","home","home","about","career"])
    >>> ["home","about","career"]
    Explanation: The tuples in this example are:
    ["joe","home",1],["joe","about",2],["joe","career",3],["james","home",4],["james","cart",5],["james","maps",6],["james","home",7],["mary","home",8],["mary","about",9], and ["mary","career",10].
    The pattern ("home", "about", "career") has score 2 (joe and mary).
    The pattern ("home", "cart", "maps") has score 1 (james).
    The pattern ("home", "cart", "home") has score 1 (james).
    The pattern ("home", "maps", "home") has score 1 (james).
    The pattern ("cart", "maps", "home") has score 1 (james).
    The pattern ("home", "home", "home") has score 0 (no user visited home 3 times).
    
    Example 2:
    
    >>> mostVisitedPattern(username = ["ua","ua","ua","ub","ub","ub"], timestamp = [1,2,3,4,5,6], website = ["a","b","a","a","b","c"])
    >>> ["a","b","a"]
    """
def canConvert(str1: str, str2: str) -> bool:
    """
    Given two strings str1 and str2 of the same length, determine whether you can transform str1 into str2 by doing zero or more conversions.
    In one conversion you can convert all occurrences of one character in str1 to any other lowercase English character.
    Return true if and only if you can transform str1 into str2.
    
    Example 1:
    
    >>> canConvert(str1 = "aabcc", str2 = "ccdee")
    >>> true
    Explanation: Convert 'c' to 'e' then 'b' to 'd' then 'a' to 'c'. Note that the order of conversions matter.
    
    Example 2:
    
    >>> canConvert(str1 = "leetcode", str2 = "codeleet")
    >>> false
    Explanation: There is no way to transform str1 to str2.
    """
def dayOfYear(date: str) -> int:
    """
    Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.
    
    Example 1:
    
    >>> dayOfYear(date = "2019-01-09")
    >>> 9
    Explanation: Given date is the 9th day of the year in 2019.
    
    Example 2:
    
    >>> dayOfYear(date = "2019-02-10")
    >>> 41
    """
def numRollsToTarget(n: int, k: int, target: int) -> int:
    """
    You have n dice, and each dice has k faces numbered from 1 to k.
    Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice, so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7.
    
    Example 1:
    
    >>> numRollsToTarget(n = 1, k = 6, target = 3)
    >>> 1
    Explanation: You throw one die with 6 faces.
    There is only one way to get a sum of 3.
    
    Example 2:
    
    >>> numRollsToTarget(n = 2, k = 6, target = 7)
    >>> 6
    Explanation: You throw two dice, each with 6 faces.
    There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.
    
    Example 3:
    
    >>> numRollsToTarget(n = 30, k = 30, target = 500)
    >>> 222616187
    Explanation: The answer must be returned modulo 109 + 7.
    """
def maxRepOpt1(text: str) -> int:
    """
    You are given a string text. You can swap two of the characters in the text.
    Return the length of the longest substring with repeated characters.
    
    Example 1:
    
    >>> maxRepOpt1(text = "ababa")
    >>> 3
    Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3.
    
    Example 2:
    
    >>> maxRepOpt1(text = "aaabaaa")
    >>> 6
    Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6.
    
    Example 3:
    
    >>> maxRepOpt1(text = "aaaaa")
    >>> 5
    Explanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5.
    """
def countCharacters(words: List[str], chars: str) -> int:
    """
    You are given an array of strings words and a string chars.
    A string is good if it can be formed by characters from chars (each character can only be used once).
    Return the sum of lengths of all good strings in words.
    
    Example 1:
    
    >>> countCharacters(words = ["cat","bt","hat","tree"], chars = "atach")
    >>> 6
    Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
    
    Example 2:
    
    >>> countCharacters(words = ["hello","world","leetcode"], chars = "welldonehoneyr")
    >>> 10
    Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
    """
# class TreeNode:
#     def __init__(val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxLevelSum(root: Optional[TreeNode]) -> int:
    """
    Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.
    Return the smallest level x such that the sum of all the values of nodes at level x is maximal.
    
    Example 1:
    
    
    >>> __init__(root = [1,7,0,7,-8,null,null])
    >>> 2
    Explanation:
    Level 1 sum = 1.
    Level 2 sum = 7 + 0 = 7.
    Level 3 sum = 7 + -8 = -1.
    So we return the level with the maximum sum which is level 2.
    
    Example 2:
    
    >>> __init__(root = [989,null,10250,98693,-89388,null,null,null,-32127])
    >>> 2
    """
def maxDistance(grid: List[List[int]]) -> int:
    """
    Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.
    The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.
    
    Example 1:
    
    
    >>> maxDistance(grid = [[1,0,1],[0,0,0],[1,0,1]])
    >>> 2
    Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.
    
    Example 2:
    
    
    >>> maxDistance(grid = [[1,0,0],[0,0,0],[0,0,0]])
    >>> 4
    Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.
    """
def lastSubstring(s: str) -> str:
    """
    Given a string s, return the last substring of s in lexicographical order.
    
    Example 1:
    
    >>> lastSubstring(s = "abab")
    >>> "bab"
    Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".
    
    Example 2:
    
    >>> lastSubstring(s = "leetcode")
    >>> "tcode"
    """
def calculateTime(keyboard: str, word: str) -> int:
    """
    There is a special keyboard with all keys in a single row.
    Given a string keyboard of length 26 indicating the layout of the keyboard (indexed from 0 to 25). Initially, your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i to index j is |i - j|.
    You want to type a string word. Write a function to calculate how much time it takes to type it with one finger.
    
    Example 1:
    
    >>> calculateTime(keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba")
    >>> 4
    Explanation: The index moves from 0 to 2 to write 'c' then to 1 to write 'b' then to 0 again to write 'a'.
    Total time = 2 + 1 + 1 = 4.
    
    Example 2:
    
    >>> calculateTime(keyboard = "pqrstuvwxyzabcdefghijklmno", word = "leetcode")
    >>> 73
    """
def connectSticks(sticks: List[int]) -> int:
    """
    You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the ith stick.
    You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must connect all the sticks until there is only one stick remaining.
    Return the minimum cost of connecting all the given sticks into one stick in this way.
    
    Example 1:
    
    >>> connectSticks(sticks = [2,4,3])
    >>> 14
    Explanation: You start with sticks = [2,4,3].
    1. Combine sticks 2 and 3 for a cost of 2 + 3 = 5. Now you have sticks = [5,4].
    2. Combine sticks 5 and 4 for a cost of 5 + 4 = 9. Now you have sticks = [9].
    There is only one stick left, so you are done. The total cost is 5 + 9 = 14.
    
    Example 2:
    
    >>> connectSticks(sticks = [1,8,3,5])
    >>> 30
    Explanation: You start with sticks = [1,8,3,5].
    1. Combine sticks 1 and 3 for a cost of 1 + 3 = 4. Now you have sticks = [4,8,5].
    2. Combine sticks 4 and 5 for a cost of 4 + 5 = 9. Now you have sticks = [9,8].
    3. Combine sticks 9 and 8 for a cost of 9 + 8 = 17. Now you have sticks = [17].
    There is only one stick left, so you are done. The total cost is 4 + 9 + 17 = 30.
    
    Example 3:
    
    >>> connectSticks(sticks = [5])
    >>> 0
    Explanation: There is only one stick, so you don't need to do anything. The total cost is 0.
    """
def minCostToSupplyWater(n: int, wells: List[int], pipes: List[List[int]]) -> int:
    """
    There are n houses in a village. We want to supply water for all the houses by building wells and laying pipes.
    For each house i, we can either build a well inside it directly with cost wells[i - 1] (note the -1 due to 0-indexing), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array pipes where each pipes[j] = [house1j, house2j, costj] represents the cost to connect house1j and house2j together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs.
    Return the minimum total cost to supply water to all houses.
    
    Example 1:
    
    
    >>> minCostToSupplyWater(n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]])
    >>> 3
    Explanation: The image shows the costs of connecting houses using pipes.
    The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3.
    
    Example 2:
    
    >>> minCostToSupplyWater(n = 2, wells = [1,1], pipes = [[1,2,1],[1,2,2]])
    >>> 2
    Explanation: We can supply water with cost two using one of the three options:
    Option 1:
      - Build a well inside house 1 with cost 1.
      - Build a well inside house 2 with cost 1.
    The total cost will be 2.
    Option 2:
      - Build a well inside house 1 with cost 1.
      - Connect house 2 with house 1 with cost 1.
    The total cost will be 2.
    Option 3:
      - Build a well inside house 2 with cost 1.
      - Connect house 1 with house 2 with cost 1.
    The total cost will be 2.
    Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose the cheapest option.
    """
def invalidTransactions(transactions: List[str]) -> List[str]:
    """
    A transaction is possibly invalid if:
    
    the amount exceeds $1000, or;
    if it occurs within (and including) 60 minutes of another transaction with the same name in a different city.
    
    You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.
    Return a list of transactions that are possibly invalid. You may return the answer in any order.
    
    Example 1:
    
    >>> invalidTransactions(transactions = ["alice,20,800,mtv","alice,50,100,beijing"])
    >>> ["alice,20,800,mtv","alice,50,100,beijing"]
    Explanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.
    Example 2:
    
    >>> invalidTransactions(transactions = ["alice,20,800,mtv","alice,50,1200,mtv"])
    >>> ["alice,50,1200,mtv"]
    
    Example 3:
    
    >>> invalidTransactions(transactions = ["alice,20,800,mtv","bob,50,1200,mtv"])
    >>> ["bob,50,1200,mtv"]
    """
def numSmallerByFrequency(queries: List[str], words: List[str]) -> List[int]:
    """
    Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = "dcce" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2.
    You are given an array of strings words and another array of query strings queries. For each query queries[i], count the number of words in words such that f(queries[i]) < f(W) for each W in words.
    Return an integer array answer, where each answer[i] is the answer to the ith query.
    
    Example 1:
    
    >>> numSmallerByFrequency(queries = ["cbd"], words = ["zaaaz"])
    >>> [1]
    Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").
    
    Example 2:
    
    >>> numSmallerByFrequency(queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"])
    >>> [1,2]
    Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").
    """
# class ListNode:
#     def __init__(val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeZeroSumSublists(head: Optional[ListNode]) -> Optional[ListNode]:
    """
    Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.\r
    \r
    After doing so, return the head of the final linked list.  You may return any such answer.\r
    
    
    (Note that in the examples below, all sequences are serializations of ListNode objects.)
    Example 1:
    
    >>> __init__(head = [1,2,-3,3,1])
    >>> [3,1]
    Note: The answer [1,2,1] would also be accepted.
    
    Example 2:
    
    >>> __init__(head = [1,2,3,-3,4])
    >>> [1,2,4]
    
    Example 3:
    
    >>> __init__(head = [1,2,3,-3,-2])
    >>> [1]
    """
def numPrimeArrangements(n: int) -> int:
    """
    Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.)
    (Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)
    Since the answer may be large, return the answer modulo 10^9 + 7.
    
    Example 1:
    
    >>> numPrimeArrangements(n = 5)
    >>> 12
    Explanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.
    
    Example 2:
    
    >>> numPrimeArrangements(n = 100)
    >>> 682289015
    """
def dietPlanPerformance(calories: List[int], k: int, lower: int, upper: int) -> int:
    """
    A dieter consumes calories[i] calories on the i-th day.
    Given an integer k, for every consecutive sequence of k days (calories[i], calories[i+1], ..., calories[i+k-1] for all 0 <= i <= n-k), they look at T, the total calories consumed during that sequence of k days (calories[i] + calories[i+1] + ... + calories[i+k-1]):
    
    If T < lower, they performed poorly on their diet and lose 1 point;
    If T > upper, they performed well on their diet and gain 1 point;
    Otherwise, they performed normally and there is no change in points.
    
    Initially, the dieter has zero points. Return the total number of points the dieter has after dieting for calories.length days.
    Note that the total points can be negative.
    
    Example 1:
    
    >>> dietPlanPerformance(calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3)
    >>> 0
    Explanation: Since k = 1, we consider each element of the array separately and compare it to lower and upper.
    calories[0] and calories[1] are less than lower so 2 points are lost.
    calories[3] and calories[4] are greater than upper so 2 points are gained.
    
    Example 2:
    
    >>> dietPlanPerformance(calories = [3,2], k = 2, lower = 0, upper = 1)
    >>> 1
    Explanation: Since k = 2, we consider subarrays of length 2.
    calories[0] + calories[1] > upper so 1 point is gained.
    
    Example 3:
    
    >>> dietPlanPerformance(calories = [6,5,0,0], k = 2, lower = 1, upper = 5)
    >>> 0
    Explanation:
    calories[0] + calories[1] > upper so 1 point is gained.
    lower <= calories[1] + calories[2] <= upper so no change in points.
    calories[2] + calories[3] < lower so 1 point is lost.
    """
def canMakePaliQueries(s: str, queries: List[List[int]]) -> List[bool]:
    """
    You are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may rearrange the substring s[lefti...righti] for each query and then choose up to ki of them to replace with any lowercase English letter.
    If the substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false.
    Return a boolean array answer where answer[i] is the result of the ith query queries[i].
    Note that each letter is counted individually for replacement, so if, for example s[lefti...righti] = "aaa", and ki = 2, we can only replace two of the letters. Also, note that no query modifies the initial string s.
    
    Example :
    
    >>> canMakePaliQueries(s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]])
    >>> [true,false,false,true,true]
    Explanation:
    queries[0]: substring = "d", is palidrome.
    queries[1]: substring = "bc", is not palidrome.
    queries[2]: substring = "abcd", is not palidrome after replacing only 1 character.
    queries[3]: substring = "abcd", could be changed to "abba" which is palidrome. Also this can be changed to "baab" first rearrange it "bacd" then replace "cd" with "ab".
    queries[4]: substring = "abcda", could be changed to "abcba" which is palidrome.
    
    Example 2:
    
    >>> canMakePaliQueries(s = "lyb", queries = [[0,1,0],[2,2,1]])
    >>> [false,true]
    """
def findNumOfValidWords(words: List[str], puzzles: List[str]) -> List[int]:
    """
    With respect to a given puzzle string, a word is valid if both the following conditions are satisfied:
    
    word contains the first letter of puzzle.
    For each letter in word, that letter is in puzzle.
    
    For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", and "baggage", while
    invalid words are "beefed" (does not include 'a') and "based" (includes 's' which is not in the puzzle).
    
    
    
    Return an array answer, where answer[i] is the number of words in the given word list words that is valid with respect to the puzzle puzzles[i].
    
    Example 1:
    
    >>> findNumOfValidWords(words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"])
    >>> [1,1,3,2,4,0]
    Explanation:
    1 valid word for "aboveyz" : "aaaa"
    1 valid word for "abrodyz" : "aaaa"
    3 valid words for "abslute" : "aaaa", "asas", "able"
    2 valid words for "absoryz" : "aaaa", "asas"
    4 valid words for "actresz" : "aaaa", "asas", "actt", "access"
    There are no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'.
    
    Example 2:
    
    >>> findNumOfValidWords(words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"])
    >>> [0,1,3,2,0]
    """
def countLetters(s: str) -> int:
    """
    Given a string s, return the number of substrings that have only one distinct letter.
    
    Example 1:
    
    >>> countLetters(s = "aaaba")
    >>> 8
    Explanation: The substrings with one distinct letter are "aaa", "aa", "a", "b".
    "aaa" occurs 1 time.
    "aa" occurs 2 times.
    "a" occurs 4 times.
    "b" occurs 1 time.
    So the answer is 1 + 2 + 4 + 1 = 8.
    
    Example 2:
    
    >>> countLetters(s = "aaaaaaaaaa")
    >>> 55
    """
def beforeAndAfterPuzzles(phrases: List[str]) -> List[str]:
    """
    Given a list of phrases, generate a list of Before and After puzzles.
    A phrase is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase.
    Before and After puzzles are phrases that are formed by merging two phrases where the last word of the first phrase is the same as the first word of the second phrase.
    Return the Before and After puzzles that can be formed by every two phrases phrases[i] and phrases[j] where i != j. Note that the order of matching two phrases matters, we want to consider both orders.
    You should return a list of distinct strings sorted lexicographically.
    
    Example 1:
    
    >>> beforeAndAfterPuzzles(phrases = ["writing code","code rocks"])
    >>> ["writing code rocks"]
    
    Example 2:
    
                      "a quick bite to eat",
                      "a chip off the old block",
                      "chocolate bar",
                      "mission impossible",
                      "a man on a mission",
                      "block party",
                      "eat my words",
                      "bar of soap"]
    >>> beforeAndAfterPuzzles(phrases = ["mission statement",)
    >>> ["a chip off the old block party",
             "a man on a mission impossible",
             "a man on a mission statement",
             "a quick bite to eat my words",
             "chocolate bar of soap"]
    
    Example 3:
    
    >>> beforeAndAfterPuzzles(phrases = ["a","b","a"])
    >>> ["a"]
    """