task_id
stringlengths
3
79
prompt
stringlengths
255
3.9k
palindrome-linked-list
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def isPalindrome(head: Optional[ListNode]) -> bool: """ Given the head of a singly linked list, return true if it is a palindrome or false otherwise. Example 1: >>> __init__(head = [1,2,2,1]) >>> true Example 2: >>> __init__(head = [1,2]) >>> false """
lowest-common-ancestor-of-a-binary-tree
# class TreeNode: # def __init__(x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': """ Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Example 1: >>> __init__(root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1) >>> 3 Explanation: The LCA of nodes 5 and 1 is 3. Example 2: >>> __init__(root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4) >>> 5 Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. Example 3: >>> __init__(root = [1,2], p = 1, q = 2) >>> 1 """
product-of-array-except-self
def productExceptSelf(nums: List[int]) -> List[int]: """ Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation. Example 1: >>> productExceptSelf(nums = [1,2,3,4]) >>> [24,12,8,6] Example 2: >>> productExceptSelf(nums = [-1,1,0,-3,3]) >>> [0,0,9,0,0] """
sliding-window-maximum
def maxSlidingWindow(nums: List[int], k: int) -> List[int]: """ You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. Example 1: >>> maxSlidingWindow(nums = [1,3,-1,-3,5,3,6,7], k = 3) >>> [3,3,5,5,6,7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Example 2: >>> maxSlidingWindow(nums = [1], k = 1) >>> [1] """
search-a-2d-matrix-ii
def searchMatrix(matrix: List[List[int]], target: int) -> bool: """ Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example 1: >>> searchMatrix(matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5) >>> true Example 2: >>> searchMatrix(matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20) >>> false """
different-ways-to-add-parentheses
def diffWaysToCompute(expression: str) -> List[int]: """ Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order. The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104. Example 1: >>> diffWaysToCompute(expression = "2-1-1") >>> [0,2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2 Example 2: >>> diffWaysToCompute(expression = "2*3-4*5") >>> [-34,-14,-10,-10,10] Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 """
valid-anagram
def isAnagram(s: str, t: str) -> bool: """ Given two strings s and t, return true if t is an anagram of s, and false otherwise. Example 1: >>> isAnagram(s = "anagram", t = "nagaram") >>> true Example 2: >>> isAnagram(s = "rat", t = "car") >>> false """
shortest-word-distance
def shortestDistance(wordsDict: List[str], word1: str, word2: str) -> int: """ Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list. Example 1: >>> shortestDistance(wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice") >>> 3 Example 2: >>> shortestDistance(wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding") >>> 1 """
shortest-word-distance-iii
def shortestWordDistance(wordsDict: List[str], word1: str, word2: str) -> int: """ Given an array of strings wordsDict and two strings that already exist in the array word1 and word2, return the shortest distance between the occurrence of these two words in the list. Note that word1 and word2 may be the same. It is guaranteed that they represent two individual words in the list. Example 1: >>> shortestWordDistance(wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding") >>> 1 Example 2: >>> shortestWordDistance(wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes") >>> 3 """
strobogrammatic-number
def isStrobogrammatic(num: str) -> bool: """ Given a string num which represents an integer, return true if num is a strobogrammatic number. A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Example 1: >>> isStrobogrammatic(num = "69") >>> true Example 2: >>> isStrobogrammatic(num = "88") >>> true Example 3: >>> isStrobogrammatic(num = "962") >>> false """
strobogrammatic-number-ii
def findStrobogrammatic(n: int) -> List[str]: """ Given an integer n, return all the strobogrammatic numbers that are of length n. You may return the answer in any order. A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Example 1: >>> findStrobogrammatic(n = 2) >>> ["11","69","88","96"] Example 2: >>> findStrobogrammatic(n = 1) >>> ["0","1","8"] """
strobogrammatic-number-iii
def strobogrammaticInRange(low: str, high: str) -> int: """ Given two strings low and high that represent two integers low and high where low <= high, return the number of strobogrammatic numbers in the range [low, high]. A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Example 1: >>> strobogrammaticInRange(low = "50", high = "100") >>> 3 Example 2: >>> strobogrammaticInRange(low = "0", high = "0") >>> 1 """
group-shifted-strings
def groupStrings(strings: List[str]) -> List[List[str]]: """ Perform the following shift operations on a string: Right shift: Replace every letter with the successive letter of the English alphabet, where 'z' is replaced by 'a'. For example, "abc" can be right-shifted to "bcd" or "xyz" can be right-shifted to "yza". Left shift: Replace every letter with the preceding letter of the English alphabet, where 'a' is replaced by 'z'. For example, "bcd" can be left-shifted to "abc" or "yza" can be left-shifted to "xyz". We can keep shifting the string in both directions to form an endless shifting sequence. For example, shift "abc" to form the sequence: ... <-> "abc" <-> "bcd" <-> ... <-> "xyz" <-> "yza" <-> .... <-> "zab" <-> "abc" <-> ... You are given an array of strings strings, group together all strings[i] that belong to the same shifting sequence. You may return the answer in any order. Example 1: >>> groupStrings(strings = ["abc","bcd","acef","xyz","az","ba","a","z"]) >>> [["acef"],["a","z"],["abc","bcd","xyz"],["az","ba"]] Example 2: >>> groupStrings(strings = ["a"]) >>> [["a"]] """
count-univalue-subtrees
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def countUnivalSubtrees(root: Optional[TreeNode]) -> int: """ Given the root of a binary tree, return the number of uni-value subtrees. A uni-value subtree means all nodes of the subtree have the same value. Example 1: >>> __init__(root = [5,1,5,5,5,null,5]) >>> 4 Example 2: >>> __init__(root = []) >>> 0 Example 3: >>> __init__(root = [5,5,5,5,5,null,5]) >>> 6 """
meeting-rooms
def canAttendMeetings(intervals: List[List[int]]) -> bool: """ Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings. Example 1: >>> canAttendMeetings(intervals = [[0,30],[5,10],[15,20]]) >>> false Example 2: >>> canAttendMeetings(intervals = [[7,10],[2,4]]) >>> true """
meeting-rooms-ii
def minMeetingRooms(intervals: List[List[int]]) -> int: """ Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required. Example 1: >>> minMeetingRooms(intervals = [[0,30],[5,10],[15,20]]) >>> 2 Example 2: >>> minMeetingRooms(intervals = [[7,10],[2,4]]) >>> 1 """
factor-combinations
def getFactors(n: int) -> List[List[int]]: """ Numbers can be regarded as the product of their factors. For example, 8 = 2 x 2 x 2 = 2 x 4. Given an integer n, return all possible combinations of its factors. You may return the answer in any order. Note that the factors should be in the range [2, n - 1]. Example 1: >>> getFactors(n = 1) >>> [] Example 2: >>> getFactors(n = 12) >>> [[2,6],[3,4],[2,2,3]] Example 3: >>> getFactors(n = 37) >>> [] """
verify-preorder-sequence-in-binary-search-tree
def verifyPreorder(preorder: List[int]) -> bool: """ Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree. Example 1: >>> verifyPreorder(preorder = [5,2,1,3,6]) >>> true Example 2: >>> verifyPreorder(preorder = [5,2,6,1,3]) >>> false """
paint-house
def minCost(costs: List[List[int]]) -> int: """ There is a row of n houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of painting each house with a certain color is represented by an n x 3 cost matrix costs. For example, costs[0][0] is the cost of painting house 0 with the color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Return the minimum cost to paint all houses. Example 1: >>> minCost(costs = [[17,2,17],[16,16,5],[14,3,19]]) >>> 10 Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. Minimum cost: 2 + 5 + 3 = 10. Example 2: >>> minCost(costs = [[7,6,2]]) >>> 2 """
binary-tree-paths
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def binaryTreePaths(root: Optional[TreeNode]) -> List[str]: """ Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children. Example 1: >>> __init__(root = [1,2,3,null,5]) >>> ["1->2->5","1->3"] Example 2: >>> __init__(root = [1]) >>> ["1"] """
add-digits
def addDigits(num: int) -> int: """ Given an integer num, repeatedly add all its digits until the result has only one digit, and return it. Example 1: >>> addDigits(num = 38) >>> 2 Explanation: The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it. Example 2: >>> addDigits(num = 0) >>> 0 """
3sum-smaller
def threeSumSmaller(nums: List[int], target: int) -> int: """ Given an array of n integers nums and an integer target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target. Example 1: >>> threeSumSmaller(nums = [-2,0,1,3], target = 2) >>> 2 Explanation: Because there are two triplets which sums are less than 2: [-2,0,1] [-2,0,3] Example 2: >>> threeSumSmaller(nums = [], target = 0) >>> 0 Example 3: >>> threeSumSmaller(nums = [0], target = 0) >>> 0 """
single-number-iii
def singleNumber(nums: List[int]) -> List[int]: """ Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order. You must write an algorithm that runs in linear runtime complexity and uses only constant extra space. Example 1: >>> singleNumber(nums = [1,2,1,3,2,5]) >>> [3,5] Explanation: [5, 3] is also a valid answer. Example 2: >>> singleNumber(nums = [-1,0]) >>> [-1,0] Example 3: >>> singleNumber(nums = [0,1]) >>> [1,0] """
graph-valid-tree
def validTree(n: int, edges: List[List[int]]) -> bool: """ You have a graph of n nodes labeled from 0 to n - 1. You are given an integer n and a list of edges where edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the graph. Return true if the edges of the given graph make up a valid tree, and false otherwise. Example 1: >>> validTree(n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]) >>> true Example 2: >>> validTree(n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]) >>> false """
ugly-number
def isUgly(n: int) -> bool: """ An ugly number is a positive integer which does not have a prime factor other than 2, 3, and 5. Given an integer n, return true if n is an ugly number. Example 1: >>> isUgly(n = 6) >>> true Explanation: 6 = 2 × 3 Example 2: >>> isUgly(n = 1) >>> true Explanation: 1 has no prime factors. Example 3: >>> isUgly(n = 14) >>> false Explanation: 14 is not ugly since it includes the prime factor 7. """
ugly-number-ii
def nthUglyNumber(n: int) -> int: """ An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return the nth ugly number. Example 1: >>> nthUglyNumber(n = 10) >>> 12 Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. Example 2: >>> nthUglyNumber(n = 1) >>> 1 Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. """
paint-house-ii
def minCostII(costs: List[List[int]]) -> int: """ There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of painting each house with a certain color is represented by an n x k cost matrix costs. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Return the minimum cost to paint all houses. Example 1: >>> minCostII(costs = [[1,5,3],[2,9,4]]) >>> 5 Explanation: Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5. Example 2: >>> minCostII(costs = [[1,3],[2,4]]) >>> 5 """
palindrome-permutation
def canPermutePalindrome(s: str) -> bool: """ Given a string s, return true if a permutation of the string could form a palindrome and false otherwise. Example 1: >>> canPermutePalindrome(s = "code") >>> false Example 2: >>> canPermutePalindrome(s = "aab") >>> true Example 3: >>> canPermutePalindrome(s = "carerac") >>> true """
palindrome-permutation-ii
def generatePalindromes(s: str) -> List[str]: """ Given a string s, return all the palindromic permutations (without duplicates) of it. You may return the answer in any order. If s has no palindromic permutation, return an empty list. Example 1: >>> generatePalindromes(s = "aabb") >>> ["abba","baab"] Example 2: >>> generatePalindromes(s = "abc") >>> [] """
missing-number
def missingNumber(nums: List[int]) -> int: """ Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Example 1: >>> missingNumber(nums = [3,0,1]) >>> 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. Example 2: >>> missingNumber(nums = [0,1]) >>> 2 Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. Example 3: >>> missingNumber(nums = [9,6,4,2,3,5,7,0,1]) >>> 8 Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums. """
alien-dictionary
def alienOrder(words: List[str]) -> str: """ There is a new alien language that uses the English alphabet. However, the order of the letters is unknown to you. You are given a list of strings words from the alien language's dictionary. Now it is claimed that the strings in words are sorted lexicographically by the rules of this new language. If this claim is incorrect, and the given arrangement of string in words cannot correspond to any order of letters, return "". Otherwise, return a string of the unique letters in the new alien language sorted in lexicographically increasing order by the new language's rules. If there are multiple solutions, return any of them. Example 1: >>> alienOrder(words = ["wrt","wrf","er","ett","rftt"]) >>> "wertf" Example 2: >>> alienOrder(words = ["z","x"]) >>> "zx" Example 3: >>> alienOrder(words = ["z","x","z"]) >>> "" Explanation: The order is invalid, so return "". """
closest-binary-search-tree-value
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def closestValue(root: Optional[TreeNode], target: float) -> int: """ Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. If there are multiple answers, print the smallest. Example 1: >>> __init__(root = [4,2,5,1,3], target = 3.714286) >>> 4 Example 2: >>> __init__(root = [1], target = 4.428571) >>> 1 """
closest-binary-search-tree-value-ii
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def closestKValues(root: Optional[TreeNode], target: float, k: int) -> List[int]: """ Given the root of a binary search tree, a target value, and an integer k, return the k values in the BST that are closest to the target. You may return the answer in any order. You are guaranteed to have only one unique set of k values in the BST that are closest to the target. Example 1: >>> __init__(root = [4,2,5,1,3], target = 3.714286, k = 2) >>> [4,3] Example 2: >>> __init__(root = [1], target = 0.000000, k = 1) >>> [1] """
integer-to-english-words
def numberToWords(num: int) -> str: """ Convert a non-negative integer num to its English words representation. Example 1: >>> numberToWords(num = 123) >>> "One Hundred Twenty Three" Example 2: >>> numberToWords(num = 12345) >>> "Twelve Thousand Three Hundred Forty Five" Example 3: >>> numberToWords(num = 1234567) >>> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" """
h-index
def hIndex(citations: List[int]) -> int: """ Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher's h-index. According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times. Example 1: >>> hIndex(citations = [3,0,6,1,5]) >>> 3 Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. Example 2: >>> hIndex(citations = [1,3,1]) >>> 1 """
h-index-ii
def hIndex(citations: List[int]) -> int: """ Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in ascending order, return the researcher's h-index. According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times. You must write an algorithm that runs in logarithmic time. Example 1: >>> hIndex(citations = [0,1,3,5,6]) >>> 3 Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. Example 2: >>> hIndex(citations = [1,2,100]) >>> 2 """
paint-fence
def numWays(n: int, k: int) -> int: """ You are painting a fence of n posts with k different colors. You must paint the posts following these rules: Every post must be painted exactly one color. There cannot be three or more consecutive posts with the same color. Given the two integers n and k, return the number of ways you can paint the fence. Example 1: >>> numWays(n = 3, k = 2) >>> 6 Explanation: All the possibilities are shown. Note that painting all the posts red or all the posts green is invalid because there cannot be three posts in a row with the same color. Example 2: >>> numWays(n = 1, k = 1) >>> 1 Example 3: >>> numWays(n = 7, k = 2) >>> 42 """
first-bad-version
# def isBadVersion(version: int) -> bool: class Solution: def firstBadVersion(n: int) -> int: """ You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. Example 1: >>> isBadVersion(n = 5, bad = 4) >>> 4 Explanation: call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version. Example 2: >>> isBadVersion(n = 1, bad = 1) >>> 1 """
perfect-squares
def numSquares(n: int) -> int: """ Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. Example 1: >>> numSquares(n = 12) >>> 3 Explanation: 12 = 4 + 4 + 4. Example 2: >>> numSquares(n = 13) >>> 2 Explanation: 13 = 4 + 9. """
wiggle-sort
def wiggleSort(nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ """ Given an integer array nums, reorder it such that nums[0] <= nums[1] >= nums[2] <= nums[3].... You may assume the input array always has a valid answer. Example 1: >>> wiggleSort(nums = [3,5,2,1,6,4]) >>> [3,5,1,6,2,4] Explanation: [1,6,2,5,3,4] is also accepted. Example 2: >>> wiggleSort(nums = [6,6,5,6,3,8]) >>> [6,6,5,6,3,8] """
expression-add-operators
def addOperators(num: str, target: int) -> List[str]: """ Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value. Note that operands in the returned expressions should not contain leading zeros. Example 1: >>> addOperators(num = "123", target = 6) >>> ["1*2*3","1+2+3"] Explanation: Both "1*2*3" and "1+2+3" evaluate to 6. Example 2: >>> addOperators(num = "232", target = 8) >>> ["2*3+2","2+3*2"] Explanation: Both "2*3+2" and "2+3*2" evaluate to 8. Example 3: >>> addOperators(num = "3456237490", target = 9191) >>> [] Explanation: There are no expressions that can be created from "3456237490" to evaluate to 9191. """
move-zeroes
def moveZeroes(nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ """ Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. Example 1: >>> moveZeroes(nums = [0,1,0,3,12]) >>> [1,3,12,0,0] Example 2: >>> moveZeroes(nums = [0]) >>> [0] """
walls-and-gates
def wallsAndGates(rooms: List[List[int]]) -> None: """ Do not return anything, modify rooms in-place instead. """ """ You are given an m x n grid rooms initialized with these three possible values. -1 A wall or an obstacle. 0 A gate. INF Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF. Example 1: >>> wallsAndGates(rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]) >>> [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]] Example 2: >>> wallsAndGates(rooms = [[-1]]) >>> [[-1]] """
find-the-duplicate-number
def findDuplicate(nums: List[int]) -> int: """ Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and using only constant extra space. Example 1: >>> findDuplicate(nums = [1,3,4,2,2]) >>> 2 Example 2: >>> findDuplicate(nums = [3,1,3,4,2]) >>> 3 Example 3: >>> findDuplicate(nums = [3,3,3,3,3]) >>> 3 """
game-of-life
def gameOfLife(board: List[List[int]]) -> None: """ Do not return anything, modify board in-place instead. """ """ According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): Any live cell with fewer than two live neighbors dies as if caused by under-population. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by over-population. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the m x n grid board. In this process, births and deaths occur simultaneously. Given the current state of the board, update the board to reflect its next state. Note that you do not need to return anything. Example 1: >>> gameOfLife(board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]) >>> [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] Example 2: >>> gameOfLife(board = [[1,1],[1,0]]) >>> [[1,1],[1,1]] """
word-pattern
def wordPattern(pattern: str, s: str) -> bool: """ Given a pattern and a string s, find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s. Specifically: Each letter in pattern maps to exactly one unique word in s. Each unique word in s maps to exactly one letter in pattern. No two letters map to the same word, and no two words map to the same letter. Example 1: >>> wordPattern(pattern = "abba", s = "dog cat cat dog") >>> true Explanation: The bijection can be established as: 'a' maps to "dog". 'b' maps to "cat". Example 2: >>> wordPattern(pattern = "abba", s = "dog cat cat fish") >>> false Example 3: >>> wordPattern(pattern = "aaaa", s = "dog cat cat dog") >>> false """
word-pattern-ii
def wordPatternMatch(pattern: str, s: str) -> bool: """ Given a pattern and a string s, return true if s matches the pattern. A string s matches a pattern if there is some bijective mapping of single characters to non-empty strings such that if each character in pattern is replaced by the string it maps to, then the resulting string is s. A bijective mapping means that no two characters map to the same string, and no character maps to two different strings. Example 1: >>> wordPatternMatch(pattern = "abab", s = "redblueredblue") >>> true Explanation: One possible mapping is as follows: 'a' -> "red" 'b' -> "blue" Example 2: >>> wordPatternMatch(pattern = "aaaa", s = "asdasdasdasd") >>> true Explanation: One possible mapping is as follows: 'a' -> "asd" Example 3: >>> wordPatternMatch(pattern = "aabb", s = "xyzabcxzyabc") >>> false """
nim-game
def canWinNim(n: int) -> bool: """ You are playing the following Nim Game with your friend: Initially, there is a heap of stones on the table. You and your friend will alternate taking turns, and you go first. On each turn, the person whose turn it is will remove 1 to 3 stones from the heap. The one who removes the last stone is the winner. Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false. Example 1: >>> canWinNim(n = 4) >>> false Explanation: These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes, your friend wins. Example 2: >>> canWinNim(n = 1) >>> true Example 3: >>> canWinNim(n = 2) >>> true """
flip-game
def generatePossibleNextMoves(currentState: str) -> List[str]: """ You are playing a Flip Game with your friend. You are given a string currentState that contains only '+' and '-'. You and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move, and therefore the other person will be the winner. Return all possible states of the string currentState after one valid move. You may return the answer in any order. If there is no valid move, return an empty list []. Example 1: >>> generatePossibleNextMoves(currentState = "++++") >>> ["--++","+--+","++--"] Example 2: >>> generatePossibleNextMoves(currentState = "+") >>> [] """
flip-game-ii
def canWin(currentState: str) -> bool: """ You are playing a Flip Game with your friend. You are given a string currentState that contains only '+' and '-'. You and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move, and therefore the other person will be the winner. Return true if the starting player can guarantee a win, and false otherwise. Example 1: >>> canWin(currentState = "++++") >>> true Explanation: The starting player can guarantee a win by flipping the middle "++" to become "+--+". Example 2: >>> canWin(currentState = "+") >>> false """
best-meeting-point
def minTotalDistance(grid: List[List[int]]) -> int: """ Given an m x n binary grid grid where each 1 marks the home of one friend, return the minimal total travel distance. The total travel distance is the sum of the distances between the houses of the friends and the meeting point. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|. Example 1: >>> minTotalDistance(grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]]) >>> 6 Explanation: Given three friends living at (0,0), (0,4), and (2,2). The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal. So return 6. Example 2: >>> minTotalDistance(grid = [[1,1]]) >>> 1 """
binary-tree-longest-consecutive-sequence
# 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 sequence path. A consecutive sequence path is a path where the values increase by one along the path. Note that the path can start at any node in the tree, and you cannot go from a node to its parent in the path. Example 1: >>> __init__(root = [1,null,3,2,4,null,null,null,5]) >>> 3 Explanation: Longest consecutive sequence path is 3-4-5, so return 3. Example 2: >>> __init__(root = [2,null,3,2,null,1]) >>> 2 Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2. """
bulls-and-cows
def getHint(secret: str, guess: str) -> str: """ You are playing the Bulls and Cows game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: The number of "bulls", which are digits in the guess that are in the correct position. The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls. Given the secret number secret and your friend's guess guess, return the hint for your friend's guess. The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits. Example 1: >>> getHint(secret = "1807", guess = "7810") >>> "1A3B" Explanation: Bulls are connected with a '|' and cows are underlined: "1807" | "7810" Example 2: >>> getHint(secret = "1123", guess = "0111") >>> "1A1B" Explanation: Bulls are connected with a '|' and cows are underlined: "1123" "1123" | or | "0111" "0111" Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. """
longest-increasing-subsequence
def lengthOfLIS(nums: List[int]) -> int: """ Given an integer array nums, return the length of the longest strictly increasing subsequence. Example 1: >>> lengthOfLIS(nums = [10,9,2,5,3,7,101,18]) >>> 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Example 2: >>> lengthOfLIS(nums = [0,1,0,3,2,3]) >>> 4 Example 3: >>> lengthOfLIS(nums = [7,7,7,7,7,7,7]) >>> 1 """
smallest-rectangle-enclosing-black-pixels
def minArea(image: List[List[str]], x: int, y: int) -> int: """ You are given an m x n binary matrix image where 0 represents a white pixel and 1 represents a black pixel. The black pixels are connected (i.e., there is only one black region). Pixels are connected horizontally and vertically. Given two integers x and y that represents the location of one of the black pixels, return the area of the smallest (axis-aligned) rectangle that encloses all black pixels. You must write an algorithm with less than O(mn) runtime complexity Example 1: >>> minArea(image = [["0","0","1","0"],["0","1","1","0"],["0","1","0","0"]], x = 0, y = 2) >>> 6 Example 2: >>> minArea(image = [["1"]], x = 0, y = 0) >>> 1 """
number-of-islands-ii
def numIslands2(m: int, n: int, positions: List[List[int]]) -> List[int]: """ You are given an empty 2D binary grid grid of size m x n. The grid represents a map where 0's represent water and 1's represent land. Initially, all the cells of grid are water cells (i.e., all the cells are 0's). We may perform an add land operation which turns the water at position into a land. You are given an array positions where positions[i] = [ri, ci] is the position (ri, ci) at which we should operate the ith operation. Return an array of integers answer where answer[i] is the number of islands after turning the cell (ri, ci) into a land. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: >>> numIslands2(m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]) >>> [1,1,2,3] Explanation: Initially, the 2d grid is filled with water. - Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. We have 1 island. - Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. We still have 1 island. - Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. We have 2 islands. - Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. We have 3 islands. Example 2: >>> numIslands2(m = 1, n = 1, positions = [[0,0]]) >>> [1] """
additive-number
def isAdditiveNumber(num: str) -> bool: """ An additive number is a string whose digits can form an additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return true if it is an additive number or false otherwise. Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid. Example 1: >>> isAdditiveNumber("112358") >>> true Explanation: The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8 Example 2: >>> isAdditiveNumber("199100199") >>> true Explanation: The additive sequence is: 1, 99, 100, 199. 1 + 99 = 100, 99 + 100 = 199 """
best-time-to-buy-and-sell-stock-with-cooldown
def maxProfit(prices: List[int]) -> int: """ You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: >>> maxProfit(prices = [1,2,3,0,2]) >>> 3 Explanation: transactions = [buy, sell, cooldown, buy, sell] Example 2: >>> maxProfit(prices = [1]) >>> 0 """
minimum-height-trees
def findMinHeightTrees(n: int, edges: List[List[int]]) -> List[int]: """ A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))  are called minimum height trees (MHTs). Return a list of all MHTs' root labels. You can return the answer in any order. The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. Example 1: >>> findMinHeightTrees(n = 4, edges = [[1,0],[1,2],[1,3]]) >>> [1] Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT. Example 2: >>> findMinHeightTrees(n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]) >>> [3,4] """
sparse-matrix-multiplication
def multiply(mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: """ Given two sparse matrices mat1 of size m x k and mat2 of size k x n, return the result of mat1 x mat2. You may assume that multiplication is always possible. Example 1: >>> multiply(mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]) >>> [[7,0,0],[-7,0,3]] Example 2: >>> multiply(mat1 = [[0]], mat2 = [[0]]) >>> [[0]] """
burst-balloons
def maxCoins(nums: List[int]) -> int: """ You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons. If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it. Return the maximum coins you can collect by bursting the balloons wisely. Example 1: >>> maxCoins(nums = [3,1,5,8]) >>> 167 Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 Example 2: >>> maxCoins(nums = [1,5]) >>> 10 """
super-ugly-number
def nthSuperUglyNumber(n: int, primes: List[int]) -> int: """ A super ugly number is a positive integer whose prime factors are in the array primes. Given an integer n and an array of integers primes, return the nth super ugly number. The nth super ugly number is guaranteed to fit in a 32-bit signed integer. Example 1: >>> nthSuperUglyNumber(n = 12, primes = [2,7,13,19]) >>> 32 Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19]. Example 2: >>> nthSuperUglyNumber(n = 1, primes = [2,3,5]) >>> 1 Explanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5]. """
binary-tree-vertical-order-traversal
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def verticalOrder(root: Optional[TreeNode]) -> List[List[int]]: """ Given the root of a binary tree, return the vertical order traversal of its nodes' values. (i.e., from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right. Example 1: >>> __init__(root = [3,9,20,null,null,15,7]) >>> [[9],[3,15],[20],[7]] Example 2: >>> __init__(root = [3,9,8,4,0,1,7]) >>> [[4],[9],[3,0,1],[8],[7]] Example 3: >>> __init__(root = [1,2,3,4,10,9,11,null,5,null,null,null,null,null,null,null,6]) >>> [[4],[2,5],[1,10,9,6],[3],[11]] """
count-of-smaller-numbers-after-self
def countSmaller(nums: List[int]) -> List[int]: """ Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i]. Example 1: >>> countSmaller(nums = [5,2,6,1]) >>> [2,1,1,0] Explanation: To the right of 5 there are 2 smaller elements (2 and 1). To the right of 2 there is only 1 smaller element (1). To the right of 6 there is 1 smaller element (1). To the right of 1 there is 0 smaller element. Example 2: >>> countSmaller(nums = [-1]) >>> [0] Example 3: >>> countSmaller(nums = [-1,-1]) >>> [0,0] """
remove-duplicate-letters
def removeDuplicateLetters(s: str) -> str: """ Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Example 1: >>> removeDuplicateLetters(s = "bcabc") >>> "abc" Example 2: >>> removeDuplicateLetters(s = "cbacdcbc") >>> "acdb" """
shortest-distance-from-all-buildings
def shortestDistance(grid: List[List[int]]) -> int: """ You are given an m x n grid grid of values 0, 1, or 2, where: each 0 marks an empty land that you can pass by freely, each 1 marks a building that you cannot pass through, and each 2 marks an obstacle that you cannot pass through. You want to build a house on an empty land that reaches all buildings in the shortest total travel distance. You can only move up, down, left, and right. Return the shortest travel distance for such a house. If it is not possible to build such a house according to the above rules, return -1. The total travel distance is the sum of the distances between the houses of the friends and the meeting point. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|. Example 1: >>> shortestDistance(grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]) >>> 7 Explanation: Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2). The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7. Example 2: >>> shortestDistance(grid = [[1,0]]) >>> 1 Example 3: >>> shortestDistance(grid = [[1]]) >>> -1 """
maximum-product-of-word-lengths
def maxProduct(words: List[str]) -> int: """ Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0. Example 1: >>> maxProduct(words = ["abcw","baz","foo","bar","xtfn","abcdef"]) >>> 16 Explanation: The two words can be "abcw", "xtfn". Example 2: >>> maxProduct(words = ["a","ab","abc","d","cd","bcd","abcd"]) >>> 4 Explanation: The two words can be "ab", "cd". Example 3: >>> maxProduct(words = ["a","aa","aaa","aaaa"]) >>> 0 Explanation: No such pair of words. """
bulb-switcher
def bulbSwitch(n: int) -> int: """ There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Return the number of bulbs that are on after n rounds. Example 1: >>> bulbSwitch(n = 3) >>> 1 Explanation: At first, the three bulbs are [off, off, off]. After the first round, the three bulbs are [on, on, on]. After the second round, the three bulbs are [on, off, on]. After the third round, the three bulbs are [on, off, off]. So you should return 1 because there is only one bulb is on. Example 2: >>> bulbSwitch(n = 0) >>> 0 Example 3: >>> bulbSwitch(n = 1) >>> 1 """
generalized-abbreviation
def generateAbbreviations(word: str) -> List[str]: """ A word's generalized abbreviation can be constructed by taking any number of non-overlapping and non-adjacent substrings and replacing them with their respective lengths. For example, "abcde" can be abbreviated into: "a3e" ("bcd" turned into "3") "1bcd1" ("a" and "e" both turned into "1") "5" ("abcde" turned into "5") "abcde" (no substrings replaced) However, these abbreviations are invalid: "23" ("ab" turned into "2" and "cde" turned into "3") is invalid as the substrings chosen are adjacent. "22de" ("ab" turned into "2" and "bc" turned into "2") is invalid as the substring chosen overlap. Given a string word, return a list of all the possible generalized abbreviations of word. Return the answer in any order. Example 1: >>> generateAbbreviations(word = "word") >>> ["4","3d","2r1","2rd","1o2","1o1d","1or1","1ord","w3","w2d","w1r1","w1rd","wo2","wo1d","wor1","word"] Example 2: >>> generateAbbreviations(word = "a") >>> ["1","a"] """
create-maximum-number
def maxNumber(nums1: List[int], nums2: List[int], k: int) -> List[int]: """ You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k. Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved. Return an array of the k digits representing the answer. Example 1: >>> maxNumber(nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5) >>> [9,8,6,5,3] Example 2: >>> maxNumber(nums1 = [6,7], nums2 = [6,0,4], k = 5) >>> [6,7,6,0,4] Example 3: >>> maxNumber(nums1 = [3,9], nums2 = [8,9], k = 3) >>> [9,8,9] """
coin-change
def coinChange(coins: List[int], amount: int) -> int: """ You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. Example 1: >>> coinChange(coins = [1,2,5], amount = 11) >>> 3 Explanation: 11 = 5 + 5 + 1 Example 2: >>> coinChange(coins = [2], amount = 3) >>> -1 Example 3: >>> coinChange(coins = [1], amount = 0) >>> 0 """
number-of-connected-components-in-an-undirected-graph
def countComponents(n: int, edges: List[List[int]]) -> int: """ You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph. Return the number of connected components in the graph. Example 1: >>> countComponents(n = 5, edges = [[0,1],[1,2],[3,4]]) >>> 2 Example 2: >>> countComponents(n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]) >>> 1 """
wiggle-sort-ii
def wiggleSort(nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ """ Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... You may assume the input array always has a valid answer. Example 1: >>> wiggleSort(nums = [1,5,1,1,6,4]) >>> [1,6,1,5,1,4] Explanation: [1,4,1,5,1,6] is also accepted. Example 2: >>> wiggleSort(nums = [1,3,2,2,3,1]) >>> [2,3,1,3,1,2] """
maximum-size-subarray-sum-equals-k
def maxSubArrayLen(nums: List[int], k: int) -> int: """ Given an integer array nums and an integer k, return the maximum length of a subarray that sums to k. If there is not one, return 0 instead. Example 1: >>> maxSubArrayLen(nums = [1,-1,5,-2,3], k = 3) >>> 4 Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest. Example 2: >>> maxSubArrayLen(nums = [-2,-1,2,1], k = 1) >>> 2 Explanation: The subarray [-1, 2] sums to 1 and is the longest. """
power-of-three
def isPowerOfThree(n: int) -> bool: """ Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x. Example 1: >>> isPowerOfThree(n = 27) >>> true Explanation: 27 = 33 Example 2: >>> isPowerOfThree(n = 0) >>> false Explanation: There is no x where 3x = 0. Example 3: >>> isPowerOfThree(n = -1) >>> false Explanation: There is no x where 3x = (-1). """
count-of-range-sum
def countRangeSum(nums: List[int], lower: int, upper: int) -> int: """ Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j. Example 1: >>> countRangeSum(nums = [-2,5,-1], lower = -2, upper = 2) >>> 3 Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2. Example 2: >>> countRangeSum(nums = [0], lower = 0, upper = 0) >>> 1 """
odd-even-linked-list
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(head: Optional[ListNode]) -> Optional[ListNode]: """ Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in O(1) extra space complexity and O(n) time complexity. Example 1: >>> __init__(head = [1,2,3,4,5]) >>> [1,3,5,2,4] Example 2: >>> __init__(head = [2,1,3,5,6,4,7]) >>> [2,3,6,7,1,5,4] """
longest-increasing-path-in-a-matrix
def longestIncreasingPath(matrix: List[List[int]]) -> int: """ Given an m x n integers matrix, return the length of the longest increasing path in matrix. From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed). Example 1: >>> longestIncreasingPath(matrix = [[9,9,4],[6,6,8],[2,1,1]]) >>> 4 Explanation: The longest increasing path is [1, 2, 6, 9]. Example 2: >>> longestIncreasingPath(matrix = [[3,4,5],[3,2,6],[2,2,1]]) >>> 4 Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed. Example 3: >>> longestIncreasingPath(matrix = [[1]]) >>> 1 """
patching-array
def minPatches(nums: List[int], n: int) -> int: """ Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required. Example 1: >>> minPatches(nums = [1,3], n = 6) >>> 1 Explanation: Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3]. Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. So we only need 1 patch. Example 2: >>> minPatches(nums = [1,5,10], n = 20) >>> 2 Explanation: The two patches can be [2, 4]. Example 3: >>> minPatches(nums = [1,2,2], n = 5) >>> 0 """
verify-preorder-serialization-of-a-binary-tree
def isValidSerialization(preorder: str) -> bool: """ One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'. For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents a null node. Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree. It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer. You may assume that the input format is always valid. For example, it could never contain two consecutive commas, such as "1,,3". Note: You are not allowed to reconstruct the tree. Example 1: >>> isValidSerialization(preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#") >>> true Example 2: >>> isValidSerialization(preorder = "1,#") >>> false Example 3: >>> isValidSerialization(preorder = "9,#,#,1") >>> false """
reconstruct-itinerary
def findItinerary(tickets: List[List[str]]) -> List[str]: """ You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. Example 1: >>> findItinerary(tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]) >>> ["JFK","MUC","LHR","SFO","SJC"] Example 2: >>> findItinerary(tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]) >>> ["JFK","ATL","JFK","SFO","ATL","SFO"] Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order. """
largest-bst-subtree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def largestBSTSubtree(root: Optional[TreeNode]) -> int: """ Given the root of a binary tree, find the largest subtree, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes. A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties: The left subtree values are less than the value of their parent (root) node's value. The right subtree values are greater than the value of their parent (root) node's value. Note: A subtree must include all of its descendants. Example 1: >>> __init__(root = [10,5,15,1,8,null,7]) >>> 3 Explanation: The Largest BST Subtree in this case is the highlighted one. The return value is the subtree's size, which is 3. Example 2: >>> __init__(root = [4,2,7,2,3,5,null,2,null,null,null,null,null,1]) >>> 2 """
increasing-triplet-subsequence
def increasingTriplet(nums: List[int]) -> bool: """ Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false. Example 1: >>> increasingTriplet(nums = [1,2,3,4,5]) >>> true Explanation: Any triplet where i < j < k is valid. Example 2: >>> increasingTriplet(nums = [5,4,3,2,1]) >>> false Explanation: No triplet exists. Example 3: >>> increasingTriplet(nums = [2,1,5,0,4,6]) >>> true Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6. """
self-crossing
def isSelfCrossing(distance: List[int]) -> bool: """ You are given an array of integers distance. You start at the point (0, 0) on an X-Y plane, and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. Return true if your path crosses itself or false if it does not. Example 1: >>> isSelfCrossing(distance = [2,1,1,2]) >>> true Explanation: The path crosses itself at the point (0, 1). Example 2: >>> isSelfCrossing(distance = [1,2,3,4]) >>> false Explanation: The path does not cross itself at any point. Example 3: >>> isSelfCrossing(distance = [1,1,1,2,1]) >>> true Explanation: The path crosses itself at the point (0, 0). """
palindrome-pairs
def palindromePairs(words: List[str]) -> List[List[int]]: """ You are given a 0-indexed array of unique strings words. A palindrome pair is a pair of integers (i, j) such that: 0 <= i, j < words.length, i != j, and words[i] + words[j] (the concatenation of the two strings) is a palindrome. Return an array of all the palindrome pairs of words. You must write an algorithm with O(sum of words[i].length) runtime complexity. Example 1: >>> palindromePairs(words = ["abcd","dcba","lls","s","sssll"]) >>> [[0,1],[1,0],[3,2],[2,4]] Explanation: The palindromes are ["abcddcba","dcbaabcd","slls","llssssll"] Example 2: >>> palindromePairs(words = ["bat","tab","cat"]) >>> [[0,1],[1,0]] Explanation: The palindromes are ["battab","tabbat"] Example 3: >>> palindromePairs(words = ["a",""]) >>> [[0,1],[1,0]] Explanation: The palindromes are ["a","a"] """
house-robber-iii
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rob(root: Optional[TreeNode]) -> int: """ The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root. Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night. Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police. Example 1: >>> __init__(root = [3,2,3,null,3,null,1]) >>> 7 Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. Example 2: >>> __init__(root = [3,4,5,1,3,null,1]) >>> 9 Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9. """
counting-bits
def countBits(n: int) -> List[int]: """ Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. Example 1: >>> countBits(n = 2) >>> [0,1,1] Explanation: 0 --> 0 1 --> 1 2 --> 10 Example 2: >>> countBits(n = 5) >>> [0,1,1,2,1,2] Explanation: 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 """
longest-substring-with-at-most-k-distinct-characters
def lengthOfLongestSubstringKDistinct(s: str, k: int) -> int: """ Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters. Example 1: >>> lengthOfLongestSubstringKDistinct(s = "eceba", k = 2) >>> 3 Explanation: The substring is "ece" with length 3. Example 2: >>> lengthOfLongestSubstringKDistinct(s = "aa", k = 1) >>> 2 Explanation: The substring is "aa" with length 2. """
power-of-four
def isPowerOfFour(n: int) -> bool: """ Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x. Example 1: >>> isPowerOfFour(n = 16) >>> true Example 2: >>> isPowerOfFour(n = 5) >>> false Example 3: >>> isPowerOfFour(n = 1) >>> true """
integer-break
def integerBreak(n: int) -> int: """ Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. Return the maximum product you can get. Example 1: >>> integerBreak(n = 2) >>> 1 Explanation: 2 = 1 + 1, 1 × 1 = 1. Example 2: >>> integerBreak(n = 10) >>> 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. """
reverse-string
def reverseString(s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ """ Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory. Example 1: >>> reverseString(s = ["h","e","l","l","o"]) >>> ["o","l","l","e","h"] Example 2: >>> reverseString(s = ["H","a","n","n","a","h"]) >>> ["h","a","n","n","a","H"] """
reverse-vowels-of-a-string
def reverseVowels(s: str) -> str: """ Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once. Example 1: >>> reverseVowels(s = "IceCreAm") >>> "AceCreIm" Explanation: The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, s becomes "AceCreIm". Example 2: >>> reverseVowels(s = "leetcode") >>> "leotcede" """
top-k-frequent-elements
def topKFrequent(nums: List[int], k: int) -> List[int]: """ Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. Example 1: >>> topKFrequent(nums = [1,1,1,2,2,3], k = 2) >>> [1,2] Example 2: >>> topKFrequent(nums = [1], k = 1) >>> [1] """
intersection-of-two-arrays
def intersection(nums1: List[int], nums2: List[int]) -> List[int]: """ Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order. Example 1: >>> intersection(nums1 = [1,2,2,1], nums2 = [2,2]) >>> [2] Example 2: >>> intersection(nums1 = [4,9,5], nums2 = [9,4,9,8,4]) >>> [9,4] Explanation: [4,9] is also accepted. """
intersection-of-two-arrays-ii
def intersect(nums1: List[int], nums2: List[int]) -> List[int]: """ Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. Example 1: >>> intersect(nums1 = [1,2,2,1], nums2 = [2,2]) >>> [2,2] Example 2: >>> intersect(nums1 = [4,9,5], nums2 = [9,4,9,8,4]) >>> [4,9] Explanation: [9,4] is also accepted. """
android-unlock-patterns
def numberOfPatterns(m: int, n: int) -> int: """ Android devices have a special lock screen with a 3 x 3 grid of dots. Users can set an "unlock pattern" by connecting the dots in a specific sequence, forming a series of joined line segments where each segment's endpoints are two consecutive dots in the sequence. A sequence of k dots is a valid unlock pattern if both of the following are true: All the dots in the sequence are distinct. If the line segment connecting two consecutive dots in the sequence passes through the center of any other dot, the other dot must have previously appeared in the sequence. No jumps through the center non-selected dots are allowed. For example, connecting dots 2 and 9 without dots 5 or 6 appearing beforehand is valid because the line from dot 2 to dot 9 does not pass through the center of either dot 5 or 6. However, connecting dots 1 and 3 without dot 2 appearing beforehand is invalid because the line from dot 1 to dot 3 passes through the center of dot 2. Here are some example valid and invalid unlock patterns: The 1st pattern [4,1,3,6] is invalid because the line connecting dots 1 and 3 pass through dot 2, but dot 2 did not previously appear in the sequence. The 2nd pattern [4,1,9,2] is invalid because the line connecting dots 1 and 9 pass through dot 5, but dot 5 did not previously appear in the sequence. The 3rd pattern [2,4,1,3,6] is valid because it follows the conditions. The line connecting dots 1 and 3 meets the condition because dot 2 previously appeared in the sequence. The 4th pattern [6,5,4,1,9,2] is valid because it follows the conditions. The line connecting dots 1 and 9 meets the condition because dot 5 previously appeared in the sequence. Given two integers m and n, return the number of unique and valid unlock patterns of the Android grid lock screen that consist of at least m keys and at most n keys. Two unlock patterns are considered unique if there is a dot in one sequence that is not in the other, or the order of the dots is different. Example 1: >>> numberOfPatterns(m = 1, n = 1) >>> 9 Example 2: >>> numberOfPatterns(m = 1, n = 2) >>> 65 """
russian-doll-envelopes
def maxEnvelopes(envelopes: List[List[int]]) -> int: """ You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other). Note: You cannot rotate an envelope. Example 1: >>> maxEnvelopes(envelopes = [[5,4],[6,4],[6,7],[2,3]]) >>> 3 Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). Example 2: >>> maxEnvelopes(envelopes = [[1,1],[1,1],[1,1]]) >>> 1 """
line-reflection
def isReflected(points: List[List[int]]) -> bool: """ Given n points on a 2D plane, find if there is such a line parallel to the y-axis that reflects the given points symmetrically. In other words, answer whether or not if there exists a line that after reflecting all points over the given line, the original points' set is the same as the reflected ones. Note that there can be repeated points. Example 1: >>> isReflected(points = [[1,1],[-1,1]]) >>> true Explanation: We can choose the line x = 0. Example 2: >>> isReflected(points = [[1,1],[-1,-1]]) >>> false Explanation: We can't choose a line. """
count-numbers-with-unique-digits
def countNumbersWithUniqueDigits(n: int) -> int: """ Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n. Example 1: >>> countNumbersWithUniqueDigits(n = 2) >>> 91 Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99 Example 2: >>> countNumbersWithUniqueDigits(n = 0) >>> 1 """
rearrange-string-k-distance-apart
def rearrangeString(s: str, k: int) -> str: """ Given a string s and an integer k, rearrange s such that the same characters are at least distance k from each other. If it is not possible to rearrange the string, return an empty string "". Example 1: >>> rearrangeString(s = "aabbcc", k = 3) >>> "abcabc" Explanation: The same letters are at least a distance of 3 from each other. Example 2: >>> rearrangeString(s = "aaabc", k = 3) >>> "" Explanation: It is not possible to rearrange the string. Example 3: >>> rearrangeString(s = "aaadbbcc", k = 2) >>> "abacabcd" Explanation: The same letters are at least a distance of 2 from each other. """