task_id
stringlengths
3
79
prompt
stringlengths
255
3.93k
strange-printer-ii
from typing import List def isPrintable(targetGrid: List[List[int]]) -> bool: """ There is a strange printer with the following two special requirements: On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectang...
rearrange-spaces-between-words
def reorderSpaces(text: str) -> str: """ You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word. Rearrange the spaces so that t...
split-a-string-into-the-max-number-of-unique-substrings
def maxUniqueSplit(s: str) -> int: """ Given a string s, return the maximum number of unique substrings that the given string can be split into. You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the subs...
maximum-non-negative-product-in-a-matrix
from typing import List def maxProductPath(grid: List[List[int]]) -> int: """ You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and en...
minimum-cost-to-connect-two-groups-of-points
from typing import List def connectTwoGroups(cost: List[List[int]]) -> int: """ You are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2. The cost of the connection between any two points are given in an size1 x size2 matrix where cost[...
crawler-log-folder
from typing import List def minOperations(logs: List[str]) -> int: """ The Leetcode file system keeps a log each time some user performs a change folder operation. The operations are described below: "../" : Move to the parent folder of the current folder. (If you are already in the main folder, re...
maximum-profit-of-operating-a-centennial-wheel
from typing import List def minOperationsMaxProfit(customers: List[int], boardingCost: int, runningCost: int) -> int: """ You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs ...
maximum-number-of-achievable-transfer-requests
from typing import List def maximumRequests(n: int, requests: List[List[int]]) -> int: """ We have n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array requests where request...
find-nearest-right-node-in-binary-tree
from typing import Optional class TreeNode: def __init__(val=0, left=None, right=None): self.val = val self.left = left self.right = right def findNearestRightNode(root: TreeNode, u: TreeNode) -> Optional[TreeNode]: """ Given the root of a binary tree and a node u in the tree, return the nea...
alert-using-same-key-card-three-or-more-times-in-a-one-hour-period
from typing import List def alertNames(keyName: List[str], keyTime: List[str]) -> List[str]: """ LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any work...
find-valid-matrix-given-row-and-column-sums
from typing import List def restoreMatrix(rowSum: List[int], colSum: List[int]) -> List[List[int]]: """ You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In othe...
find-servers-that-handled-most-number-of-requests
from typing import List def busiestServers(k: int, arrival: List[int], load: List[int]) -> List[int]: """ You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. T...
special-array-with-x-elements-greater-than-or-equal-x
from typing import List def specialArray(nums: List[int]) -> int: """ You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x. Notice that x does not have to be an element in...
even-odd-tree
from typing import Optional class TreeNode: def __init__(val=0, left=None, right=None): self.val = val self.left = left self.right = right def isEvenOddTree(root: Optional[TreeNode]) -> bool: """ A binary tree is named Even-Odd if it meets the following conditions: The root of the binary tr...
maximum-number-of-visible-points
from typing import List def visiblePoints(points: List[List[int]], angle: int, location: List[int]) -> int: """ You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane. Initially, you are fac...
minimum-one-bit-operations-to-make-integers-zero
def minimumOneBitOperations(n: int) -> int: """ Given an integer n, you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 ...
maximum-nesting-depth-of-the-parentheses
def maxDepth(s: str) -> int: """ Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses. Example 1: >>> maxDepth(s = "(1+(2*3)+((8)/4))+1") >>> 3 Explanation: Digit 8 is inside of 3 nested parentheses in the ...
maximal-network-rank
from typing import List def maximalNetworkRank(n: int, roads: List[List[int]]) -> int: """ There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi. The network rank of two differe...
split-two-strings-to-make-palindrome
def checkPalindromeFormation(a: str, b: str) -> bool: """ You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b =...
count-subtrees-with-max-distance-between-cities
from typing import List def countSubgraphsForEachDiameter(n: int, edges: List[List[int]]) -> List[int]: """ There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between ea...
mean-of-array-after-removing-some-elements
from typing import List def trimMean(arr: List[int]) -> float: """ Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements. Answers within 10-5 of the actual answer will be considered accepted. Example 1: >>> t...
coordinate-with-maximum-network-quality
from typing import List def bestCoordinate(towers: List[List[int]], radius: int) -> List[int]: """ You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y p...
number-of-sets-of-k-non-overlapping-line-segments
def numberOfSets(n: int, k: int) -> int: """ Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates....
largest-substring-between-two-equal-characters
def maxLengthBetweenEqualCharacters(s: str) -> int: """ Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. A substring is a contiguous sequence of characters within a string. Example 1: ...
lexicographically-smallest-string-after-applying-operations
def findLexSmallestString(s: str, a: int, b: int) -> str: """ You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b. You can apply either of the following two operations any number of times and in any order on s: Add a to all odd indices of s (0-indexed)...
best-team-with-no-conflicts
from typing import List def bestTeamScore(scores: List[int], ages: List[int]) -> int: """ You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team. However, the...
graph-connectivity-with-threshold
from typing import List def areConnected(n: int, threshold: int, queries: List[List[int]]) -> List[bool]: """ We have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some thr...
slowest-key
from typing import List def slowestKey(releaseTimes: List[int], keysPressed: str) -> str: """ A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, ...
arithmetic-subarrays
from typing import List def checkArithmeticSubarrays(nums: List[int], l: List[int], r: List[int]) -> List[bool]: """ A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmeti...
path-with-minimum-effort
from typing import List def minimumEffortPath(heights: List[List[int]]) -> int: """ You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you h...
rank-transform-of-a-matrix
from typing import List def matrixRankTransform(matrix: List[List[int]]) -> List[List[int]]: """ Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col]. The rank is an integer that represents how large an element is compared to other elements. It is calculat...
sort-array-by-increasing-frequency
from typing import List def frequencySort(nums: List[int]) -> List[int]: """ Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order. Return the sorted array. Example 1: ...
widest-vertical-area-between-two-points-containing-no-points
from typing import List def maxWidthOfVerticalArea(points: List[List[int]]) -> int: """ Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along th...
count-substrings-that-differ-by-one-character
def countSubstrings(s: str, t: str) -> int: """ Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that diff...
number-of-ways-to-form-a-target-string-given-a-dictionary
from typing import List def numWays(words: List[str], target: str) -> int: """ You are given a list of strings of the same length words and a string target. Your task is to form target using the given words under the following rules: target should be formed from left to right. To form the ith c...
check-array-formation-through-concatenation
from typing import List def canFormArray(arr: List[int], pieces: List[List[int]]) -> bool: """ You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, y...
count-sorted-vowel-strings
def countVowelStrings(n: int) -> int: """ Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. ...
furthest-building-you-can-reach
from typing import List def furthestBuilding(heights: List[int], bricks: int, ladders: int) -> int: """ You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks o...
kth-smallest-instructions
from typing import List def kthSmallestPath(destination: List[int], k: int) -> str: """ Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination. The instructions are ...
lowest-common-ancestor-of-a-binary-tree-ii
class TreeNode: def __init__(x): self.val = x self.left = None self.right = None def lowestCommonAncestor(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': """ Given the root of a binary tree, return the lowest common ancestor (LCA) of two given nodes, p and q. If either node p...
get-maximum-in-generated-array
def getMaximumGenerated(n: int) -> int: """ You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way: nums[0] = 0 nums[1] = 1 nums[2 * i] = nums[i] when 2 <= 2 * i <= n nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n ...
minimum-deletions-to-make-character-frequencies-unique
def minDeletions(s: str) -> int: """ A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The frequency of a character in a string is the number of times it appea...
sell-diminishing-valued-colored-balls
from typing import List def maxProfit(inventory: List[int], orders: int) -> int: """ You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color y...
create-sorted-array-through-instructions
from typing import List def createSortedArray(instructions: List[int]) -> int: """ Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The ...
defuse-the-bomb
from typing import List def decrypt(code: List[int], k: int) -> List[int]: """ You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k. To decrypt the code, you must replace every number. All the numbers are replaced simul...
minimum-deletions-to-make-string-balanced
def minimumDeletions(s: str) -> int: """ You are given a string s consisting only of characters 'a' and 'b'​​​​. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of ...
minimum-jumps-to-reach-home
from typing import List def minimumJumps(forbidden: List[int], a: int, b: int, x: int) -> int: """ A certain bug's home is on the x-axis at position x. Help them get there from position 0. The bug jumps according to the following rules: It can jump exactly a positions forward (to the right). It...
distribute-repeating-integers
from typing import List def canDistribute(nums: List[int], quantity: List[int]) -> bool: """ You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the it...
determine-if-two-strings-are-close
def closeStrings(word1: str, word2: str) -> bool: """ Two strings are considered close if you can attain one from the other using the following operations: Operation 1: Swap any two existing characters. For example, abcde -> aecdb Operation 2: Transform every occurrence of o...
minimum-operations-to-reduce-x-to-zero
from typing import List def minOperations(nums: List[int], x: int) -> int: """ You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future opera...
maximize-grid-happiness
def getMaxGridHappiness(m: int, n: int, introvertsCount: int, extrovertsCount: int) -> int: """ You are given four integers, m, n, introvertsCount, and extrovertsCount. You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount ...
check-if-two-string-arrays-are-equivalent
from typing import List def arrayStringsAreEqual(word1: List[str], word2: List[str]) -> bool: """ Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the s...
smallest-string-with-a-given-numeric-value
def getSmallestString(n: int, k: int) -> str: """ The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on. The numeric value of a string consisting of lowercase char...
ways-to-make-a-fair-array
from typing import List def waysToMakeFair(nums: List[int]) -> int: """ You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal. For example, if nums = [6,1,7,4,1]: Choosing to remov...
minimum-initial-energy-to-finish-tasks
from typing import List def minimumEffort(tasks: List[List[int]]) -> int: """ You are given an array tasks where tasks[i] = [actuali, minimumi]: actuali is the actual amount of energy you spend to finish the ith task. minimumi is the minimum amount of energy you require to begin the ith task. ...
maximum-repeating-substring
def maxRepeating(sequence: str, word: str) -> int: """ For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's ma...
merge-in-between-linked-lists
class ListNode: def __init__(val=0, next=None): self.val = val self.next = next def mergeInBetween(list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode: """ You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1's nodes from the ath node to the bth node,...
minimum-number-of-removals-to-make-mountain-array
from typing import List def minimumMountainRemovals(nums: 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] ...
richest-customer-wealth
from typing import List def maximumWealth(accounts: List[List[int]]) -> int: """ You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has. A customer's wealth i...
find-the-most-competitive-subsequence
from typing import List def mostCompetitive(nums: List[int], k: int) -> List[int]: """ Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the ar...
minimum-moves-to-make-array-complementary
from typing import List def minMoves(nums: List[int], limit: int) -> int: """ You are given an integer array nums of even length n and an integer limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive. The array nums is complementary if for all indices ...
minimize-deviation-in-array
from typing import List def minimumDeviation(nums: List[int]) -> int: """ You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: If the element is even, divide it by 2. For example, if the array is [...
goal-parser-interpretation
def interpret(command: str) -> str: """ You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings ar...
max-number-of-k-sum-pairs
from typing import List def maxOperations(nums: List[int], k: int) -> int: """ You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the...
concatenation-of-consecutive-binary-numbers
def concatenatedBinary(n: int) -> int: """ Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7. Example 1: >>> concatenatedBinary(n = 1) >>> 1 Explanation: "1" in binary corresponds to t...
minimum-incompatibility
from typing import List def minimumIncompatibility(nums: List[int], k: int) -> int: """ You are given an integer array nums​​​ and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset. A subset's incompatibility is the...
longest-palindromic-subsequence-ii
def longestPalindromeSubseq(s: str) -> int: """ A subsequence of a string s is considered a good palindromic subsequence if: It is a subsequence of s. It is a palindrome (has the same value if reversed). It has an even length. No two consecutive characters are equal, except the two middle o...
count-the-number-of-consistent-strings
from typing import List def countConsistentStrings(allowed: str, words: List[str]) -> int: """ You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed. Return the number of consistent ...
sum-of-absolute-differences-in-a-sorted-array
from typing import List def getSumAbsoluteDifferences(nums: List[int]) -> List[int]: """ You are given an integer array nums sorted in non-decreasing order. Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between num...
stone-game-vi
from typing import List def stoneGameVI(aliceValues: List[int], bobValues: List[int]) -> int: """ Alice and Bob take turns playing a game, with Alice starting first. There are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alic...
delivering-boxes-from-storage-to-ports
from typing import List def boxDelivering(boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int: """ You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry. ...
count-of-matches-in-tournament
def numberOfMatches(n: int) -> int: """ You are given an integer n, the number of teams in a tournament that has strange rules: If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round. If the cur...
partitioning-into-minimum-number-of-deci-binary-numbers
def minPartitions(n: str) -> int: """ A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not. Given a string n that represents a positive decimal integer, return the minimum number of posi...
stone-game-vii
from typing import List def stoneGameVII(stones: List[int]) -> int: """ Alice and Bob take turns playing a game, with Alice starting first. There are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to t...
maximum-height-by-stacking-cuboids
from typing import List def maxHeight(cuboids: List[List[int]]) -> int: """ Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] (0-indexed). Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if widthi <= widthj and lengt...
count-ways-to-distribute-candies
def waysToDistribute(n: int, k: int) -> int: """ There are n unique candies (labeled 1 through n) and k bags. You are asked to distribute all the candies into the bags such that every bag has at least one candy. There can be multiple ways to distribute the candies. Two ways are considered different if the c...
reformat-phone-number
def reformatNumber(number: str) -> str: """ You are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'. You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks...
maximum-erasure-value
from typing import List def maximumUniqueSubarray(nums: List[int]) -> int: """ You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements. Return the maximum score you can get by eras...
jump-game-vi
from typing import List def maxResult(nums: List[int], k: int) -> int: """ You are given a 0-indexed integer array nums and an integer k. You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from ind...
checking-existence-of-edge-length-limited-paths
from typing import List def distanceLimitedPathsExist(n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]: """ An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multi...
number-of-distinct-substrings-in-a-string
def countDistinct(s: str) -> int: """ Given a string s, return the number of distinct substrings of s. A substring of a string is obtained by deleting any number of characters (possibly zero) from the front of the string and any number (possibly zero) from the back of the string. Example 1: ...
number-of-students-unable-to-eat-lunch
from typing import List def countStudents(students: List[int], sandwiches: List[int]) -> int: """ The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. ...
average-waiting-time
from typing import List def averageWaitingTime(customers: List[List[int]]) -> float: """ There is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrivali, timei]: arrivali is the arrival time of the ith customer. The arrival times are sorted in non-decreasing o...
maximum-binary-string-after-change
def maximumBinaryString(binary: str) -> str: """ You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times: Operation 1: If the number contains the substring "00", you can replace it with "10". For example, "0001...
minimum-adjacent-swaps-for-k-consecutive-ones
from typing import List def minMoves(nums: List[int], k: int) -> int: """ You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values. Return the minimum number of moves required so that nums has k consecu...
determine-if-string-halves-are-alike
def halvesAreAlike(s: str) -> bool: """ You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice t...
maximum-number-of-eaten-apples
from typing import List def eatenApples(apples: List[int], days: List[int]) -> int: """ There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot ...
where-will-the-ball-fall
from typing import List def findBall(grid: List[List[int]]) -> List[int]: """ You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the ri...
maximum-xor-with-an-element-from-array
from typing import List def maximizeXor(nums: List[int], queries: List[List[int]]) -> List[int]: """ You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi]. The answer to the ith query is the maximum bitwise XOR value of xi and any el...
largest-subarray-length-k
from typing import List def largestSubarray(nums: List[int], k: int) -> List[int]: """ An array A is larger than some array B if for the first index i where A[i] != B[i], A[i] > B[i]. For example, consider 0-indexing: [1,3,2,4] > [1,2,2,4], since at index 1, 3 > 2. [1,4,4,4] < [2,1,1,1], since ...
maximum-units-on-a-truck
from typing import List def maximumUnits(boxTypes: List[List[int]], truckSize: int) -> int: """ You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: numberOfBoxesi is the number of boxes of type i. ...
count-good-meals
from typing import List def countPairs(deliciousness: List[int]) -> int: """ A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where ...
ways-to-split-array-into-three-subarrays
from typing import List def waysToSplit(nums: List[int]) -> int: """ A split of an integer array is good if: The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right. The sum of the elements in left is less than or equal to the sum of the...
minimum-operations-to-make-a-subsequence
from typing import List def minOperations(target: List[int], arr: List[int]) -> int: """ You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,...
sum-of-special-evenly-spaced-elements-in-array
from typing import List def solve(nums: List[int], queries: List[List[int]]) -> List[int]: """ You are given a 0-indexed integer array nums consisting of n non-negative integers. You are also given an array queries, where queries[i] = [xi, yi]. The answer to the ith query is the sum of all nums[j] where xi ...
calculate-money-in-leetcode-bank
def totalMoney(n: int) -> int: """ Hercy wants to save money for his first car. He puts money in the Leetcode bank every day. He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more ...
maximum-score-from-removing-substrings
def maximumGain(s: str, x: int, y: int) -> int: """ You are given a string s and two integers x and y. You can perform two types of operations any number of times. Remove substring "ab" and gain x points. For example, when removing "ab" from "cabxbae" it becomes "cxbae". Rem...
construct-the-lexicographically-largest-valid-sequence
from typing import List def constructDistancedSequence(n: int) -> List[int]: """ Given an integer n, find a sequence with elements in the range [1, n] that satisfies all of the following: The integer 1 occurs once in the sequence. Each integer between 2 and n occurs twice in the sequence. For e...
number-of-ways-to-reconstruct-a-tree
from typing import List def checkWays(pairs: List[List[int]]) -> int: """ You are given an array pairs, where pairs[i] = [xi, yi], and: There are no duplicates. xi < yi Let ways be the number of rooted trees that satisfy the following conditions: The tree consists of nodes whose v...
decode-xored-array
from typing import List def decode(encoded: List[int], first: int) -> List[int]: """ There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1],...