task_id
stringlengths
3
79
prompt
stringlengths
255
3.93k
palindrome-linked-list
from typing import Optional class ListNode: def __init__(val=0, next=None): self.val = val self.next = next 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: >>> isPalindrome(head = [1,2...
lowest-common-ancestor-of-a-binary-tree
class TreeNode: def __init__(x): self.val = x self.left = None self.right = None 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...
product-of-array-except-self
from typing import List 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. ...
sliding-window-maximum
from typing import List 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...
search-a-2d-matrix-ii
from typing import List 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. Int...
different-ways-to-add-parentheses
from typing import List 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...
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
from typing import List 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: >>>...
shortest-word-distance-iii
from typing import List 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 ...
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
from typing import List 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). ...
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
from typing import List 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" o...
count-univalue-subtrees
from typing import Optional class TreeNode: def __init__(val=0, left=None, right=None): self.val = val self.left = left self.right = right def countUnivalSubtrees(root: Optional[TreeNode]) -> int: """ Given the root of a binary tree, return the number of uni-value subtrees. A uni-value subtr...
meeting-rooms
from typing import List 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 ...
meeting-rooms-ii
from typing import List 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]]) ...
factor-combinations
from typing import List 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 fac...
verify-preorder-sequence-in-binary-search-tree
from typing import List 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 Exampl...
paint-house
from typing import List 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 ...
binary-tree-paths
from typing import List, Optional class TreeNode: def __init__(val=0, left=None, right=None): self.val = val self.left = left self.right = right 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...
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
from typing import List 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: >>> three...
single-number-iii
from typing import List 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 algo...
graph-valid-tree
from typing import List 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...
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
from typing import List 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. ...
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
from typing import List 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...
missing-number
from typing import List 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 si...
alien-dictionary
from typing import List 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 ...
closest-binary-search-tree-value
from typing import Optional class TreeNode: def __init__(val=0, left=None, right=None): self.val = val self.left = left self.right = right 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 ...
closest-binary-search-tree-value-ii
from typing import List, Optional class TreeNode: def __init__(val=0, left=None, right=None): self.val = val self.left = left self.right = right def closestKValues(root: Optional[TreeNode], target: float, k: int) -> List[int]: """ Given the root of a binary search tree, a target value, and 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
from typing import List 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 t...
h-index-ii
from typing import List 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-inde...
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: 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 a...
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
from typing import List 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. ...
expression-add-operators
from typing import List 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 va...
move-zeroes
from typing import List 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-p...
walls-and-gates
from typing import List 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 ...
find-the-duplicate-number
from typing import List 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 a...
game-of-life
from typing import Any, List 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 Joh...
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
from typing import List 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 ...
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
from typing import List 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. ...
binary-tree-longest-consecutive-sequence
from typing import Optional class TreeNode: def __init__(val=0, left=None, right=None): self.val = val self.left = left self.right = right def longestConsecutive(root: Optional[TreeNode]) -> int: """ Given the root of a binary tree, return the length of the longest consecutive sequence path....
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
from typing import List 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,1...
smallest-rectangle-enclosing-black-pixels
from typing import List 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 ver...
number-of-islands-ii
from typing import List 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'...
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
from typing import List 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 ...
minimum-height-trees
from typing import List 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, a...
sparse-matrix-multiplication
from typing import List 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(...
burst-balloons
from typing import List 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 + ...
super-ugly-number
from typing import List 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 fi...
binary-tree-vertical-order-traversal
from typing import List, Optional class TreeNode: def __init__(val=0, left=None, right=None): self.val = val self.left = left self.right = right def verticalOrder(root: Optional[TreeNode]) -> List[List[int]]: """ Given the root of a binary tree, return the vertical order traversal of its nod...
count-of-smaller-numbers-after-self
from typing import List 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: ...
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
from typing import List 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 canno...
maximum-product-of-word-lengths
from typing import List 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",...
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
from typing import List 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: ...
create-maximum-number
from typing import List 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 <=...
coin-change
from typing import List 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 amo...
number-of-connected-components-in-an-undirected-graph
from typing import List 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....
wiggle-sort-ii
from typing import List 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. ...
maximum-size-subarray-sum-equals-k
from typing import List 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 ...
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
from typing import List 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...
odd-even-linked-list
from typing import Optional class ListNode: def __init__(val=0, next=None): self.val = val self.next = next 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 indic...
longest-increasing-path-in-a-matrix
from typing import List 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...
patching-array
from typing import List 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 requ...
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
from typing import List 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 w...
largest-bst-subtree
from typing import Optional class TreeNode: def __init__(val=0, left=None, right=None): self.val = val self.left = left self.right = right def largestBSTSubtree(root: Optional[TreeNode]) -> int: """ Given the root of a binary tree, find the largest subtree, which is also a Binary Search Tree...
increasing-triplet-subsequence
from typing import Any, List 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...
self-crossing
from typing import List 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 t...
palindrome-pairs
from typing import List 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 st...
house-robber-iii
from typing import Optional class TreeNode: def __init__(val=0, left=None, right=None): self.val = val self.left = left self.right = right 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, ca...
counting-bits
from typing import List 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 --> ...
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
from typing import List 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 ...
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
from typing import List 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: >>...
intersection-of-two-arrays
from typing import List 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(nums...
intersection-of-two-arrays-ii
from typing import List 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. Exampl...
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
from typing import List 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 gre...
line-reflection
from typing import List 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...
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) ...