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: ...
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...
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 alg...
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. ...
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...
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 va...
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(wordsD...
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 sam...
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...
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: >>> fi...
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 (loo...
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-shi...
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 u...
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: >>> ca...
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: ...
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 ra...
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: >>> verify...
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 ...
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. ...
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...
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,...
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 linea...
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 grap...
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: >>> isUg...
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 th...
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 ea...
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 ...
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") >>> ["abb...
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,...
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...
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 val...
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, a...
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 Fi...
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 su...
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-in...
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 a...
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...
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...
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: ...
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 opera...
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 co...
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 ...
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...
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." ...
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 uniqu...
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,...
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. ...
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, a...
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 p...
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 calc...
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 sequ...
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 dig...
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 lengt...
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 i...
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 a...
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 s...
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 followin...
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 edg...
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]...
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 ...
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 int...
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...
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 ther...
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") ...
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. ...
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","abcd...
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...
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" turn...
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 th...
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 m...
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: ...
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: ...
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 subarra...
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 ...
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 ...
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 ev...
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-ar...
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...
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 t...
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", t...
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 S...
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]) >>> ...
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 o...
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. ...
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 thi...
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 --> ...
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 ...
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...
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. ...
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. ...
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" ...
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...
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 = [...
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: >>> inters...
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...
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 enve...
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 origina...
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,...
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) ...