task_id
stringlengths
3
79
prompt
stringlengths
255
3.9k
number-of-corner-rectangles
def countCornerRectangles(grid: List[List[int]]) -> int: """ Given an m x n integer matrix grid where each entry is only 0 or 1, return the number of corner rectangles. A corner rectangle is four distinct 1's on the grid that forms an axis-aligned rectangle. Note that only the corners need to have the value...
ip-to-cidr
def ipToCIDR(ip: str, n: int) -> List[str]: """ An IP address is a formatted 32-bit unsigned integer where each group of 8 bits is printed as a decimal number and the dot character '.' splits the groups. For example, the binary number 00001111 10001000 11111111 01101011 (spaces added for clarity) forma...
open-the-lock
def openLock(deadends: List[str], target: str) -> int: """ You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists ...
cracking-the-safe
def crackSafe(n: int, k: int) -> str: """ There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1]. The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered ...
reach-a-number
def reachNumber(target: int) -> int: """ You are standing at position 0 on an infinite number line. There is a destination at position target. You can make some number of moves numMoves so that: On each move, you can either go left or right. During the ith move (starting from i == 1 to i == num...
pour-water
def pourWater(heights: List[int], volume: int, k: int) -> List[int]: """ You are given an elevation map represents as an integer array heights where heights[i] representing the height of the terrain at index i. The width at each index is 1. You are also given two integers volume and k. volume units of water wil...
pyramid-transition-matrix
def pyramidTransition(bottom: str, allowed: List[str]) -> bool: """ You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top. To make the pyramid aesthetically pleasin...
set-intersection-size-at-least-two
def intersectionSizeTwo(intervals: List[List[int]]) -> int: """ You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents all the integers from starti to endi inclusively. A containing set is an array nums where each interval from intervals has at least two integers in nums. ...
bold-words-in-string
def boldWords(words: List[str], s: str) -> str: """ Given an array of keywords words and a string s, make all appearances of all keywords words[i] in s bold. Any letters between and tags become bold. Return s after adding the bold tags. The returned string should use the least number of tags possible, and...
find-anagram-mappings
def anagramMappings(nums1: List[int], nums2: List[int]) -> List[int]: """ You are given two integer arrays nums1 and nums2 where nums2 is an anagram of nums1. Both arrays may contain duplicates. Return an index mapping array mapping from nums1 to nums2 where mapping[i] = j means the ith element in nums1 app...
special-binary-string
def makeLargestSpecial(s: str) -> str: """ Special binary strings are binary strings with the following two properties: The number of 0's is equal to the number of 1's. Every prefix of the binary string has at least as many 1's as 0's. You are given a special binary string s. A move co...
prime-number-of-set-bits-in-binary-representation
def countPrimeSetBits(left: int, right: int) -> int: """ Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation. Recall that the number of set bits an integer has is the number of 1's present when w...
partition-labels
def partitionLabels(s: str) -> List[int]: """ You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. For example, the string "ababcc" can be partitioned into ["abab", "cc"], but partitions such as ["aba", "bcc"] or ["ab", "ab", "...
largest-plus-sign
def orderOfLargestPlusSign(n: int, mines: List[List[int]]) -> int: """ You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0. ...
couples-holding-hands
def minSwapsCouples(row: List[int]) -> int: """ There are n couples sitting in 2n seats arranged in a row and want to hold hands. The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple bei...
toeplitz-matrix
def isToeplitzMatrix(matrix: List[List[int]]) -> bool: """ Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. Example 1: >>> isToeplitzMatrix(matrix = [[1,2,...
reorganize-string
def reorganizeString(s: str) -> str: """ Given a string s, rearrange the characters of s so that any two adjacent characters are not the same. Return any possible rearrangement of s or return "" if not possible. Example 1: >>> reorganizeString(s = "aab") >>> "aba" Example 2: >>> reo...
max-chunks-to-make-sorted-ii
def maxChunksToSorted(arr: List[int]) -> int: """ You are given an integer array arr. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort ...
max-chunks-to-make-sorted
def maxChunksToSorted(arr: List[int]) -> int: """ You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1]. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should eq...
basic-calculator-iv
def basicCalculatorIV(expression: str, evalvars: List[str], evalints: List[int]) -> List[str]: """ Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expressi...
jewels-and-stones
def numJewelsInStones(jewels: str, stones: str) -> int: """ You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels. Lette...
basic-calculator-iii
def calculate(s: str) -> int: """ Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, '+', '-', '*', '/' operators, and open '(' and closing parentheses ')'. The integer division should truncate toward zero. You may assume that ...
sliding-puzzle
def slidingPuzzle(board: List[List[int]]) -> int: """ On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1,2,3],...
minimize-max-distance-to-gas-station
def minmaxGasDist(stations: List[int], k: int) -> float: """ You are given an integer array stations that represents the positions of the gas stations on the x-axis. You are also given an integer k. You should add k new gas stations. You can add the stations anywhere on the x-axis, and not necessarily on an...
global-and-local-inversions
def isIdealPermutation(nums: List[int]) -> bool: """ You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1]. The number of global inversions is the number of the different pairs (i, j) where: 0 <= i < j < n nums[i] > nums[j] ...
swap-adjacent-in-lr-string
def canTransform(start: str, result: str) -> bool: """ In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string result, return...
swim-in-rising-water
def swimInWater(grid: List[List[int]]) -> int: """ You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j). The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent ...
k-th-symbol-in-grammar
def kthGrammar(n: int, k: int) -> int: """ We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. For example, for n = 3, the 1st row is 0, the 2nd...
reaching-points
def reachingPoints(sx: int, sy: int, tx: int, ty: int) -> bool: """ Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise. The allowed operation on some point (x, y) is to convert it to either (x,...
rabbits-in-forest
def numRabbits(answers: List[int]) -> int: """ There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have the same color as you?" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit. Given the array answers, return the mi...
transform-to-chessboard
def movesToChessboard(board: List[List[int]]) -> int: """ You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other. Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, retur...
minimum-distance-between-bst-nodes
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minDiffInBST(root: Optional[TreeNode]) -> int: """ Given the root of a Binary Search Tree (BST), return the minimum difference between the ...
letter-case-permutation
def letterCasePermutation(s: str) -> List[str]: """ Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. Return the output in any order. Example 1: >>> letterCasePermutati...
is-graph-bipartite
def isBipartite(graph: List[List[int]]) -> bool: """ There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge betw...
k-th-smallest-prime-fraction
def kthSmallestPrimeFraction(arr: List[int], k: int) -> List[int]: """ You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k. For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j]...
cheapest-flights-within-k-stops
def findCheapestPrice(n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: """ There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. You ar...
rotated-digits
def rotatedDigits(n: int) -> int: """ An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone. A number is valid if each digit remains a digit after rotation. For example:...
escape-the-ghosts
def escapeGhosts(ghosts: List[List[int]], target: List[int]) -> bool: """ You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [xtarget, ytarget] that you are trying to get to. There are several ghosts on the map with th...
domino-and-tromino-tiling
def numTilings(n: int) -> int: """ You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes. Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7. In a tiling, every square must b...
custom-sort-string
def customSortString(order: str, s: str) -> str: """ You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously. Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs befor...
number-of-matching-subsequences
def numMatchingSubseq(s: str, words: List[str]) -> int: """ Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the r...
preimage-size-of-factorial-zeroes-function
def preimageSizeFZF(k: int) -> int: """ Let f(x) be the number of zeroes at the end of x!. Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1. For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end. Given an i...
valid-tic-tac-toe-state
def validTicTacToe(board: List[str]) -> bool: """ Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' charact...
number-of-subarrays-with-bounded-maximum
def numSubarrayBoundedMax(nums: List[int], left: int, right: int) -> int: """ Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right]. The test cases are g...
rotate-string
def rotateString(s: str, goal: str) -> bool: """ Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s. A shift on s consists of moving the leftmost character of s to the rightmost position. For example, if s = "abcde", then it will be "bcdea" a...
all-paths-from-source-to-target
def allPathsSourceTarget(graph: List[List[int]]) -> List[List[int]]: """ Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order. The graph is given as follows: graph[i] is a list of all nodes you can visit from ...
smallest-rotation-with-highest-score
def bestRotation(nums: List[int]) -> int: """ You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. Afterward, any entries that are less than or equal to their index are worth one ...
champagne-tower
def champagneTower(poured: int, query_row: int, query_glass: int) -> float: """ We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.  Each glass holds one cup of champagne.\r \r Then, some champagne is poured into the first glass at...
similar-rgb-color
def similarRGB(color: str) -> str: """ The red-green-blue color "#AABBCC" can be written as "#ABC" in shorthand. For example, "#15c" is shorthand for the color "#1155cc". The similarity between the two colors "#ABCDEF" and "#UVWXYZ" is -(AB - UV)2 - (CD - WX)2 - (EF - YZ)2. Given a string ...
minimum-swaps-to-make-sequences-increasing
def minSwap(nums1: List[int], nums2: List[int]) -> int: """ You are given two integer arrays of the same length nums1 and nums2. In one operation, you are allowed to swap nums1[i] with nums2[i]. For example, if nums1 = [1,2,3,8], and nums2 = [5,6,7,4], you can swap the element at i = 3 to obtain nums1 ...
find-eventual-safe-states
def eventualSafeNodes(graph: List[List[int]]) -> List[int]: """ There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each...
bricks-falling-when-hit
def hitBricks(grid: List[List[int]], hits: List[List[int]]) -> List[int]: """ You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if: It is directly connected to the top of the grid, or At least one other brick in its four adjacent ...
unique-morse-code-words
def uniqueMorseRepresentations(words: List[str]) -> int: """ International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: 'a' maps to ".-", 'b' maps to "-...", 'c' maps to "-.-.", and so on. For convenience, the full table...
split-array-with-same-average
def splitArraySameAverage(nums: List[int]) -> bool: """ You are given an integer array nums. You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B). Return true if it is possible to achieve that and false otherwise. Note ...
number-of-lines-to-write-string
def numberOfLines(widths: List[int], s: str) -> List[int]: """ You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on. You are trying to wr...
max-increase-to-keep-city-skyline
def maxIncreaseKeepingSkyline(grid: List[List[int]]) -> int: """ There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the bl...
soup-servings
def soupServings(n: int) -> float: """ There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. There are four kinds of operations: Serve 100 ml of soup A and 0 ml of soup B, Serve 75 ml of soup A and 25 ml of soup B, Serve 50 ml of soup A and 50 ml of soup ...
expressive-words
def expressiveWords(s: str, words: List[str]) -> int: """ Sometimes people repeat letters to represent extra feeling. For example: "hello" -> "heeellooo" "hi" -> "hiiii" In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo". ...
chalkboard-xor-game
def xorGame(nums: List[int]) -> bool: """ You are given an array of integers nums represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboa...
subdomain-visit-count
def subdomainVisits(cpdomains: List[str]) -> List[str]: """ A website domain "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com" and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we w...
largest-triangle-area
def largestTriangleArea(points: List[List[int]]) -> float: """ Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted. Example 1: ...
largest-sum-of-averages
def largestSumOfAverages(nums: List[int], k: int) -> float: """ You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray. Note that the partition must use every integer ...
binary-tree-pruning
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pruneTree(root: Optional[TreeNode]) -> Optional[TreeNode]: """ Given the root of a binary tree, return the same tree where every subtree (o...
bus-routes
def numBusesToDestination(routes: List[List[int]], source: int, target: int) -> int: """ You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever. For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 ->...
ambiguous-coordinates
def ambiguousCoordinates(s: str) -> List[str]: """ We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces and ended up with the string s. For example, "(1, 3)" becomes s = "(13)" and "(2, 0.5)" becomes s = "(205)". Return a l...
linked-list-components
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def numComponents(head: Optional[ListNode], nums: List[int]) -> int: """ You are given the head of a linked list containing unique integer values and an integer array nums that is a su...
race-car
def racecar(target: int) -> int: """ Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse): When you get an instruction 'A', your car does t...
short-encoding-of-words
def minimumLengthEncoding(words: List[str]) -> int: """ A valid encoding of an array of words is any reference string s and array of indices indices such that: words.length == indices.length The reference string s ends with the '#' character. For each index indices[i], the substring of s starti...
shortest-distance-to-a-character
def shortestToChar(s: str, c: str) -> List[int]: """ Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s. The distance between two indices i and j is a...
card-flipping-game
def flipgame(fronts: List[int], backs: List[int]) -> int: """ You are given two 0-indexed integer arrays fronts and backs of length n, where the ith card has the positive integer fronts[i] printed on the front and backs[i] printed on the back. Initially, each card is placed on a table such that the front number...
binary-trees-with-factors
def numFactoredBinaryTrees(arr: List[int]) -> int: """ Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of t...
goat-latin
def toGoatLatin(sentence: str) -> str: """ You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as fo...
friends-of-appropriate-ages
def numFriendRequests(ages: List[int]) -> int: """ There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person. A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true: age[y] <= 0....
most-profit-assigning-work
def maxProfitAssignment(difficulty: List[int], profit: List[int], worker: List[int]) -> int: """ You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and worker[j] is the abilit...
making-a-large-island
def largestIsland(grid: List[List[int]]) -> int: """ You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1. Return the size of the largest island in grid after applying this operation. An island is a 4-directionally connected group of 1s. Example 1: ...
count-unique-characters-of-all-substrings-of-a-given-string
def uniqueLetterString(s: str) -> int: """ Let's define a function countUniqueChars(s) that returns the number of unique characters in s. For example, calling countUniqueChars(s) if s = "LEETCODE" then "L", "T", "C", "O", "D" are the unique characters since they appear only once in s, therefore countUn...
consecutive-numbers-sum
def consecutiveNumbersSum(n: int) -> int: """ Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers. Example 1: >>> consecutiveNumbersSum(n = 5) >>> 2 Explanation: 5 = 2 + 3 Example 2: >>> consecutiveNumbersSum(n = 9...
positions-of-large-groups
def largeGroupPositions(s: str) -> List[List[int]]: """ In a string s of lowercase letters, these letters form consecutive groups of the same character. For example, a string like s = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z", and "yy". A group is identified by an interval [start, end], where s...
masking-personal-information
def maskPII(s: str) -> str: """ You are given a personal information string s, representing either an email address or a phone number. Return the masked personal information using the below rules. Email address: An email address is: A name consisting of uppercase and lowercase English letters, ...
flipping-an-image
def flipAndInvertImage(image: List[List[int]]) -> List[List[int]]: """ Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. For example, flipping [1,1,0] horizonta...
find-and-replace-in-string
def findReplaceString(s: str, indices: List[int], sources: List[str], targets: List[str]) -> str: """ You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k. ...
sum-of-distances-in-tree
def sumOfDistancesInTree(n: int, edges: List[List[int]]) -> List[int]: """ There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree...
image-overlap
def largestOverlap(img1: List[List[int]], img2: List[List[int]]) -> int: """ You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values. We translate one image however we choose by sliding all the 1 bits left, right, up, and/or...
rectangle-overlap
def isRectangleOverlap(rec1: List[int], rec2: List[int]) -> bool: """ An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and ...
new-21-game
def new21Game(n: int, k: int, maxPts: int) -> float: """ Alice plays the following game, loosely based on the card game "21". Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxP...
push-dominoes
def pushDominoes(dominoes: str) -> str: """ There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on ...
similar-string-groups
def numSimilarGroups(strs: List[str]) -> int: """ Two strings, X and Y, are considered similar if either they are identical or we can make them equivalent by swapping at most two letters (in distinct positions) within the string X. For example, "tars" and "rats" are similar (swapping at positions 0 and 2), ...
magic-squares-in-grid
def numMagicSquaresInside(grid: List[List[int]]) -> int: """ A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum. Given a row x col grid of integers, how many 3 x 3 magic square subgrids are there? Note: while...
keys-and-rooms
def canVisitAllRooms(rooms: List[List[int]]) -> bool: """ There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys ...
split-array-into-fibonacci-sequence
def splitIntoFibonacci(num: str) -> List[int]: """ You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like sequence [123, 456, 579]. Formally, a Fibonacci-like sequence is a list f of non-negative integers such that: 0 <= f[i] < 231, (that is, each integer f...
backspace-string-compare
def backspaceCompare(s: str, t: str) -> bool: """ Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character. Note that after backspacing an empty text, the text will continue empty. Example 1: >>> backspaceCompare(...
longest-mountain-in-array
def longestMountain(arr: List[int]) -> int: """ You may recall that an array arr is a mountain array if and only if: arr.length >= 3 There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[...
hand-of-straights
def isNStraightHand(hand: List[int], groupSize: int) -> bool: """ Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards. Given an integer array hand where hand[i] is the value written on the ith ca...
shortest-path-visiting-all-nodes
def shortestPathLength(graph: List[List[int]]) -> int: """ You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node. You m...
shifting-letters
def shiftingLetters(s: str, shifts: List[int]) -> str: """ You are given a string s of lowercase English letters and an integer array shifts of the same length. Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a'). For example, shift('a') = 'b', s...
maximize-distance-to-closest-person
def maxDistToClosest(seats: List[int]) -> int: """ You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed). There is at least one empty seat, and at least one person sitting. Ale...
rectangle-area-ii
def rectangleArea(rectangles: List[List[int]]) -> int: """ You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner. Calcu...
loud-and-rich
def loudAndRich(richer: List[List[int]], quiet: List[int]) -> List[int]: """ There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness. You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money th...
peak-index-in-a-mountain-array
def peakIndexInMountainArray(arr: List[int]) -> int: """ You are given an integer mountain array arr of length n where the values increase to a peak element and then decrease. Return the index of the peak element. Your task is to solve it in O(log(n)) time complexity. Example 1: >>> pe...
car-fleet
def carFleet(target: int, position: List[int], speed: List[int]) -> int: """ There are n cars at given miles away from the starting mile 0, traveling to reach the mile target. You are given two integer array position and speed, both of length n, where position[i] is the starting mile of the ith car and spee...