task_id stringlengths 3 79 | prompt stringlengths 255 3.9k |
|---|---|
k-similar-strings | def kSimilarity(s1: str, s2: str) -> int:
"""
Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.
Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.
... |
score-of-parentheses | def scoreOfParentheses(s: str) -> int:
"""
Given a balanced parentheses string s, return the score of the string.
The score of a balanced parentheses string is based on the following rule:
"()" has score 1.
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 ... |
minimum-cost-to-hire-k-workers | def mincostToHireWorkers(quality: List[int], wage: List[int], k: int) -> float:
"""
There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker.
We want to hire exactly k workers to fo... |
mirror-reflection | def mirrorReflection(p: int, q: int) -> int:
"""
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.
The square room has walls of length p and a laser ray from the southwest corner... |
buddy-strings | def buddyStrings(s: str, goal: str) -> bool:
"""
Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.
Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and ... |
lemonade-change | def lemonadeChange(bills: List[int]) -> bool:
"""
At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the co... |
score-after-flipping-matrix | def matrixScore(grid: List[List[int]]) -> int:
"""
You are given an m x n binary matrix grid.
A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).
Every row of the matrix is interpreted as a binary number, and th... |
shortest-subarray-with-sum-at-least-k | def shortestSubarray(nums: List[int], k: int) -> int:
"""
Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.
A subarray is a contiguous part of an array.
Example 1:
>>> sho... |
shortest-path-to-get-all-keys | def shortestPathAllKeys(grid: List[str]) -> int:
"""
You are given an m x n grid grid where:
'.' is an empty cell.
'#' is a wall.
'@' is the starting point.
Lowercase letters represent keys.
Uppercase letters represent locks.
You start at the starting point and one move consist... |
smallest-subtree-with-all-the-deepest-nodes | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def subtreeWithAllDeepest(root: Optional[TreeNode]) -> Optional[TreeNode]:
"""
Given the root of a binary tree, the depth of each node is the s... |
prime-palindrome | def primePalindrome(n: int) -> int:
"""
Given an integer n, return the smallest prime palindrome greater than or equal to n.
An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number.
For example, 2, 3, 5, 7, 11, and 13 are all primes.
An integer i... |
transpose-matrix | def transpose(matrix: List[List[int]]) -> List[List[int]]:
"""
Given a 2D integer array matrix, return the transpose of matrix.
The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
Example 1:
>>> transpose(matrix = [[1,... |
binary-gap | def binaryGap(n: int) -> int:
"""
Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.
Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between tw... |
reordered-power-of-2 | def reorderedPowerOf2(n: int) -> bool:
"""
You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true if and only if we can do this so that the resulting number is a power of two.
Example 1:
>>> reorder... |
advantage-shuffle | def advantageCount(nums1: List[int], nums2: List[int]) -> List[int]:
"""
You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i].
Return any permutation of nums1 that maximizes its advanta... |
minimum-number-of-refueling-stops | def minRefuelStops(target: int, startFuel: int, stations: List[List[int]]) -> int:
"""
A car travels from a starting position to a destination which is target miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = ... |
leaf-similar-trees | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def leafSimilar(root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
"""
Consider all the leaves of a binary tree, from left to right... |
length-of-longest-fibonacci-subsequence | def lenLongestFibSubseq(arr: List[int]) -> int:
"""
A sequence x1, x2, ..., xn is Fibonacci-like if:
n >= 3
xi + xi+1 == xi+2 for all i + 2 <= n
Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr... |
walking-robot-simulation | def robotSim(commands: List[int], obstacles: List[List[int]]) -> int:
"""
A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot receives an array of integers commands, which represents a sequence of moves that it needs to execute. There are only three possible types of instructions the ... |
koko-eating-bananas | def minEatingSpeed(piles: List[int], h: int) -> int:
"""
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.
Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eat... |
middle-of-the-linked-list | # class ListNode:
# def __init__(val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(head: Optional[ListNode]) -> Optional[ListNode]:
"""
Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes... |
stone-game | def stoneGame(piles: List[int]) -> bool:
"""
Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
The objective of the game is to end with the most stones. The total number of stones across all th... |
nth-magical-number | def nthMagicalNumber(n: int, a: int, b: int) -> int:
"""
A positive integer is magical if it is divisible by either a or b.
Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
>>> nthMagicalNumber(n =... |
profitable-schemes | def profitableSchemes(n: int, minProfit: int, group: List[int], profit: List[int]) -> int:
"""
There is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member... |
decoded-string-at-index | def decodeAtIndex(s: str, k: int) -> str:
"""
You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:
If the character read is a letter, that letter is written onto the tape.
If the character read is a ... |
boats-to-save-people | def numRescueBoats(people: List[int], limit: int) -> int:
"""
You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight ... |
reachable-nodes-in-subdivided-graph | def reachableNodes(edges: List[List[int]], maxMoves: int, n: int) -> int:
"""
You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.
The graph... |
projection-area-of-3d-shapes | def projectionArea(grid: List[List[int]]) -> int:
"""
You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j).
We view the projection of these cubes onto the ... |
uncommon-words-from-two-sentences | def uncommonFromSentences(s1: str, s2: str) -> List[str]:
"""
A sentence is a string of single-space separated words where each word consists only of lowercase letters.
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Given two sentences s... |
spiral-matrix-iii | def spiralMatrixIII(rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
"""
You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.
You will walk in a c... |
possible-bipartition | def possibleBipartition(n: int, dislikes: List[List[int]]) -> bool:
"""
We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.
Given the integer n and the array dislikes where dislikes[i] ... |
super-egg-drop | def superEggDrop(k: int, n: int) -> int:
"""
You are given k identical eggs and you have access to a building with n floors labeled from 1 to n.
You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will ... |
fair-candy-swap | def fairCandySwap(aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
"""
Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of ca... |
construct-binary-tree-from-preorder-and-postorder-traversal | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructFromPrePost(preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
"""
Given two integer arrays, preorder and postorder... |
find-and-replace-pattern | def findAndReplacePattern(words: List[str], pattern: str) -> List[str]:
"""
Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.
A word matches the pattern if there exists a permutation of letters p so that after replacing ... |
sum-of-subsequence-widths | def sumSubseqWidths(nums: List[int]) -> int:
"""
The width of a sequence is the difference between the maximum and minimum elements in the sequence.
Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 1... |
surface-area-of-3d-shapes | def surfaceArea(grid: List[List[int]]) -> int:
"""
You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j).
After placing these cubes, you have decided to glue any directly adjacent cubes to each other, form... |
groups-of-special-equivalent-strings | def numSpecialEquivGroups(words: List[str]) -> int:
"""
You are given an array of strings of the same length words.
In one move, you can swap any two even indexed characters or any two odd indexed characters of a string words[i].
Two strings words[i] and words[j] are special-equivalent if after any numb... |
monotonic-array | def isMonotonic(nums: List[int]) -> bool:
"""
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].
Given an integer array n... |
increasing-order-search-tree | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def increasingBST(root: Optional[TreeNode]) -> Optional[TreeNode]:
"""
Given the root of a binary search tree, rearrange the tree in in-order s... |
bitwise-ors-of-subarrays | def subarrayBitwiseORs(arr: List[int]) -> int:
"""
Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr.
The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer.
A s... |
orderly-queue | def orderlyQueue(s: str, k: int) -> str:
"""
You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string.
Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.
Example 1... |
numbers-at-most-n-given-digit-set | def atMostNGivenDigitSet(digits: List[str], n: int) -> int:
"""
Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'.
Return the n... |
valid-permutations-for-di-sequence | def numPermsDISequence(s: str) -> int:
"""
You are given a string s of length n where s[i] is either:
'D' means decreasing, or
'I' means increasing.
A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i:
If s[... |
fruit-into-baskets | def totalFruit(fruits: List[int]) -> int:
"""
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.
You want to collect as much fruit as possible. However, the... |
sort-array-by-parity | def sortArrayByParity(nums: List[int]) -> List[int]:
"""
Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
Return any array that satisfies this condition.
Example 1:
>>> sortArrayByParity(nums = [3,1,2,4])
>>> [2,4,3... |
super-palindromes | def superpalindromesInRange(left: str, right: str) -> int:
"""
Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclus... |
sum-of-subarray-minimums | def sumSubarrayMins(arr: List[int]) -> int:
"""
Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.
Example 1:
>>> sumSubarrayMins(arr = [3,1,2,4])
>>> 17
Explan... |
smallest-range-i | def smallestRangeI(nums: List[int], k: int) -> int:
"""
You are given an integer array nums and an integer k.
In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for ... |
snakes-and-ladders | def snakesAndLadders(board: List[List[int]]) -> int:
"""
You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.
You start on square 1 of the board. In ... |
smallest-range-ii | def smallestRangeII(nums: List[int], k: int) -> int:
"""
You are given an integer array nums and an integer k.
For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k.
The score of nums is the difference between the maximum and minimum elements in nums.
Re... |
sort-an-array | def sortArray(nums: List[int]) -> List[int]:
"""
Given an array of integers nums, sort the array in ascending order and return it.
You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.
Example 1:
>>> s... |
cat-and-mouse | def catMouseGame(graph: List[List[int]]) -> int:
"""
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.
The mouse starts at node 1 and goes first, the cat start... |
x-of-a-kind-in-a-deck-of-cards | def hasGroupsSizeX(deck: List[int]) -> bool:
"""
You are given an integer array deck where deck[i] represents the number written on the ith card.
Partition the cards into one or more groups such that:
Each group has exactly x cards where x > 1, and
All the cards in one group have the same integ... |
partition-array-into-disjoint-intervals | def partitionDisjoint(nums: List[int]) -> int:
"""
Given an integer array nums, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
... |
word-subsets | def wordSubsets(words1: List[str], words2: List[str]) -> List[str]:
"""
You are given two string arrays words1 and words2.
A string b is a subset of string a if every letter in b occurs in a including multiplicity.
For example, "wrr" is a subset of "warrior" but is not a subset of "world".
... |
reverse-only-letters | def reverseOnlyLetters(s: str) -> str:
"""
Given a string s, reverse the string according to the following rules:
All the characters that are not English letters remain in the same position.
All the English letters (lowercase or uppercase) should be reversed.
Return s after reversing it.
... |
maximum-sum-circular-subarray | def maxSubarraySumCircular(nums: List[int]) -> int:
"""
Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.
A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) ... |
number-of-music-playlists | def numMusicPlaylists(n: int, goal: int, k: int) -> int:
"""
Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:
Every song is played at least once.
A song can only be play... |
minimum-add-to-make-parentheses-valid | def minAddToMakeValid(s: str) -> int:
"""
A parentheses string is valid if and only if:
It is the empty string,
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
You are given a parentheses string s... |
sort-array-by-parity-ii | def sortArrayByParityII(nums: List[int]) -> List[int]:
"""
Given an array of integers nums, half of the integers in nums are odd, and the other half are even.
Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.
Return any answer array that satisfies this co... |
3sum-with-multiplicity | def threeSumMulti(arr: List[int], target: int) -> int:
"""
Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target.
As the answer can be very large, return it modulo 109 + 7.
Example 1:
>>> threeSumMu... |
minimize-malware-spread | def minMalwareSpread(graph: List[List[int]], initial: List[int]) -> int:
"""
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.
Some nodes initial are initially infected by malware. Whenever two nod... |
long-pressed-name | def isLongPressedName(name: str, typed: str) -> bool:
"""
Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.
You examine the typed characters of the keyboard. Return True if it is possible tha... |
flip-string-to-monotone-increasing | def minFlipsMonoIncr(s: str) -> int:
"""
A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none).
You are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0.
Return the minimum number ... |
three-equal-parts | def threeEqualParts(arr: List[int]) -> List[int]:
"""
You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value.
If it is possible, return any [i, j] with i + 1 < j, such that:
arr[0], a... |
minimize-malware-spread-ii | def minMalwareSpread(graph: List[List[int]], initial: List[int]) -> int:
"""
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.
Some nodes initial are initially infected by malware. Whenever two nod... |
unique-email-addresses | def numUniqueEmails(emails: List[str]) -> int:
"""
Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'.
For example, in "alice@leetcode.com", "alice" is the local name, and "leetcode.com" is the... |
binary-subarrays-with-sum | def numSubarraysWithSum(nums: List[int], goal: int) -> int:
"""
Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.
A subarray is a contiguous part of the array.
Example 1:
>>> numSubarraysWithSum(nums = [1,0,1,0,1], goal = 2)
>>> 4
... |
minimum-falling-path-sum | def minFallingPathSum(matrix: List[List[int]]) -> int:
"""
Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.
A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right.... |
beautiful-array | def beautifulArray(n: int) -> List[int]:
"""
An array nums of length n is beautiful if:
nums is a permutation of the integers in the range [1, n].
For every 0 <= i < j < n, there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j].
Given the integer n, return any beautiful ... |
shortest-bridge | def shortestBridge(grid: List[List[int]]) -> int:
"""
You are given an n x n binary matrix grid where 1 represents land and 0 represents water.
An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid.
You may change 0's to 1's to connec... |
knight-dialer | def knightDialer(n: int) -> int:
"""
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagram:
A chess ... |
stamping-the-sequence | def movesToStamp(stamp: str, target: str) -> List[int]:
"""
You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'.
In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp.
Fo... |
reorder-data-in-log-files | def reorderLogFiles(logs: List[str]) -> List[str]:
"""
You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.
There are two types of logs:
Letter-logs: All words (except the identifier) consist of lowercase English letters.
Digit-l... |
range-sum-of-bst | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rangeSumBST(root: Optional[TreeNode], low: int, high: int) -> int:
"""
Given the root node of a binary search tree and two integers low and... |
minimum-area-rectangle | def minAreaRect(points: List[List[int]]) -> int:
"""
You are given an array of points in the X-Y plane points where points[i] = [xi, yi].
Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0.
Example 1... |
distinct-subsequences-ii | def distinctSubseqII(s: str) -> int:
"""
Given a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 109 + 7.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characte... |
valid-mountain-array | def validMountainArray(arr: List[int]) -> bool:
"""
Given an array of integers arr, return true if and only if it is a valid mountain array.
Recall that arr is a mountain array if and only if:
arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... |
di-string-match | def diStringMatch(s: str) -> List[int]:
"""
A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:
s[i] == 'I' if perm[i] < perm[i + 1], and
s[i] == 'D' if perm[i] > perm[i + 1].
Given a string s, reconstruct the per... |
find-the-shortest-superstring | def shortestSuperstring(words: List[str]) -> str:
"""
Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them.
You may assume that no string in words is a substring of anothe... |
delete-columns-to-make-sorted | def minDeletionSize(strs: List[str]) -> int:
"""
You are given an array of n strings strs, all of the same length.
The strings can be arranged such that there is one on each line, making a grid.
For example, strs = ["abc", "bce", "cae"] can be arranged as follows:
abc
bce
cae
... |
minimum-increment-to-make-array-unique | def minIncrementForUnique(nums: List[int]) -> int:
"""
You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1.
Return the minimum number of moves to make every value in nums unique.
The test cases are generated so that the answer f... |
validate-stack-sequences | def validateStackSequences(pushed: List[int], popped: List[int]) -> bool:
"""
Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.
Example 1:
... |
most-stones-removed-with-same-row-or-column | def removeStones(stones: List[List[int]]) -> int:
"""
On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.
A stone can be removed if it shares either the same row or the same column as another stone that has not been removed.
Given an arra... |
bag-of-tokens | def bagOfTokensScore(tokens: List[int], power: int) -> int:
"""
You start with an initial power of power, an initial score of 0, and a bag of tokens given as an integer array tokens, where each tokens[i] denotes the value of tokeni.
Your goal is to maximize the total score by strategically playing these tok... |
largest-time-for-given-digits | def largestTimeFromDigits(arr: List[int]) -> str:
"""
Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.
24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the l... |
reveal-cards-in-increasing-order | def deckRevealedIncreasing(deck: List[int]) -> List[int]:
"""
You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i].
You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in on... |
flip-equivalent-binary-trees | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flipEquiv(root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
"""
For a binary tree T, we can define a flip operation as follows... |
largest-component-size-by-common-factor | def largestComponentSize(nums: List[int]) -> int:
"""
You are given an integer array of unique positive integers nums. Consider the following graph:
There are nums.length nodes, labeled nums[0] to nums[nums.length - 1],
There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] ... |
verifying-an-alien-dictionary | def isAlienSorted(words: List[str], order: str) -> bool:
"""
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.
Given a sequence of words written in the alien language, and the or... |
array-of-doubled-pairs | def canReorderDoubled(arr: List[int]) -> bool:
"""
Given an integer array of even length arr, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise.
Example 1:
>>> canReorderDoubled(arr = [3,1,3,6])
>>> fa... |
delete-columns-to-make-sorted-ii | def minDeletionSize(strs: List[str]) -> int:
"""
You are given an array of n strings strs, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, the... |
tallest-billboard | def tallestBillboard(rods: List[int]) -> int:
"""
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of rods that can be welded together. For example, if y... |
prison-cells-after-n-days | def prisonAfterNDays(cells: List[int], n: int) -> List[int]:
"""
There are 8 prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
If a cell has two adjacent neighbors that are both occupied or bo... |
check-completeness-of-a-binary-tree | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isCompleteTree(root: Optional[TreeNode]) -> bool:
"""
Given the root of a binary tree, determine if it is a complete binary tree.
In a ... |
regions-cut-by-slashes | def regionsBySlashes(grid: List[str]) -> int:
"""
An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '. These characters divide the square into contiguous regions.
Given the grid grid represented as a string array, return the number of regions.
No... |
delete-columns-to-make-sorted-iii | def minDeletionSize(strs: List[str]) -> int:
"""
You are given an array of n strings strs, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, the... |
n-repeated-element-in-size-2n-array | def repeatedNTimes(nums: List[int]) -> int:
"""
You are given an integer array nums with the following properties:
nums.length == 2 * n.
nums contains n + 1 unique elements.
Exactly one element of nums is repeated n times.
Return the element that is repeated n times.
Example 1... |
maximum-width-ramp | def maxWidthRamp(nums: List[int]) -> int:
"""
A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i.
Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0.
Example 1:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.