task_id stringlengths 3 79 | prompt stringlengths 255 3.9k |
|---|---|
intersection-of-three-sorted-arrays | def arraysIntersection(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
"""
Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays.
Example 1:
>>> arraysIntersection(arr1 =... |
two-sum-bsts | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def twoSumBSTs(root1: Optional[TreeNode], root2: Optional[TreeNode], target: int) -> bool:
"""
Given the roots of two binary search trees, root... |
stepping-numbers | def countSteppingNumbers(low: int, high: int) -> List[int]:
"""
A stepping number is an integer such that all of its adjacent digits have an absolute difference of exactly 1.
For example, 321 is a stepping number while 421 is not.
Given two integers low and high, return a sorted list of all th... |
valid-palindrome-iii | def isValidPalindrome(s: str, k: int) -> bool:
"""
Given a string s and an integer k, return true if s is a k-palindrome.
A string is k-palindrome if it can be transformed into a palindrome by removing at most k characters from it.
Example 1:
>>> isValidPalindrome(s = "abcdeca", k = 2)
... |
minimum-cost-to-move-chips-to-the-same-position | def minCostToMoveChips(position: List[int]) -> int:
"""
We have n chips, where the position of the ith chip is position[i].
We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to:
position[i] + 2 or position[i] - 2 with cost =... |
longest-arithmetic-subsequence-of-given-difference | def longestSubsequence(arr: List[int], difference: int) -> int:
"""
Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.
A subsequence... |
path-with-maximum-gold | def getMaximumGold(grid: List[List[int]]) -> int:
"""
In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.
Return the maximum amount of gold you can collect under the conditions:
Every time you are located in a cell... |
count-vowels-permutation | def countVowelPermutation(n: int) -> int:
"""
Given an integer n, your task is to count how many strings of length n can be formed under the following rules:
Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u')
Each vowel 'a' may only be followed by an 'e'.
Each vowel 'e' may only be ... |
split-a-string-in-balanced-strings | def balancedStringSplit(s: str) -> int:
"""
Balanced strings are those that have an equal quantity of 'L' and 'R' characters.
Given a balanced string s, split it into some number of substrings such that:
Each substring is balanced.
Return the maximum number of balanced strings you can obta... |
queens-that-can-attack-the-king | def queensAttacktheKing(queens: List[List[int]], king: List[int]) -> List[List[int]]:
"""
On a 0-indexed 8 x 8 chessboard, there can be multiple black queens and one white king.
You are given a 2D integer array queens where queens[i] = [xQueeni, yQueeni] represents the position of the ith black queen on the... |
dice-roll-simulation | def dieSimulator(n: int, rollMax: List[int]) -> int:
"""
A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.
Given an array of integers rollMax and an integ... |
maximum-equal-frequency | def maxEqualFreq(nums: List[int]) -> int:
"""
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.
... |
airplane-seat-assignment-probability | def nthPersonGetsNthSeat(n: int) -> float:
"""
n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
Take their own seat if it is still available, and
Pick other seats randomly when th... |
missing-number-in-arithmetic-progression | def missingNumber(arr: List[int]) -> int:
"""
In some array arr, the values were in arithmetic progression: the values arr[i + 1] - arr[i] are all equal for every 0 <= i < arr.length - 1.
A value from arr was removed that was not the first or last value in the array.
Given arr, return the removed value.... |
meeting-scheduler | def minAvailableDuration(slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]:
"""
Given the availability time slots arrays slots1 and slots2 of two people and a meeting duration duration, return the earliest time slot that works for both of them and is of duration duration.
If ther... |
toss-strange-coins | def probabilityOfHeads(prob: List[float], target: int) -> float:
"""
You have some coins. The i-th coin has a probability prob[i] of facing heads when tossed.
Return the probability that the number of coins facing heads equals target if you toss every coin exactly once.
Example 1:
>>> probabil... |
divide-chocolate | def maximizeSweetness(sweetness: List[int], k: int) -> int:
"""
You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness given by the array sweetness.
You want to share the chocolate with your k friends so you start cutting the chocolate bar into k + 1 pieces using k cuts, e... |
check-if-it-is-a-straight-line | def checkStraightLine(coordinates: List[List[int]]) -> bool:
"""
You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
Example 1:
>>> checkStraightLine(coordinates = ... |
remove-sub-folders-from-the-filesystem | def removeSubfolders(folder: List[str]) -> List[str]:
"""
Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order.
If a folder[i] is located within another folder[j], it is called a sub-folder of it. A sub-folder of folder[j]... |
replace-the-substring-for-balanced-string | def balancedString(s: str) -> int:
"""
You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'.
A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string.
Return the minimum length of the substring that... |
maximum-profit-in-job-scheduling | def jobScheduling(startTime: List[int], endTime: List[int], profit: List[int]) -> int:
"""
We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].
You're given the startTime, endTime and profit arrays, return the maximum profit you can take s... |
circular-permutation-in-binary-representation | def circularPermutation(n: int, start: int) -> List[int]:
"""
Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that :\r
\r
\r
p[0] = start\r
p[i] and p[i+1] differ by only one bit in their binary representation.\r
p[0] and p[2^n -1] must also... |
maximum-length-of-a-concatenated-string-with-unique-characters | def maxLength(arr: List[str]) -> int:
"""
You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.
Return the maximum possible length of s.
A subsequence is an array that can be derived from another array by deleting some or no ... |
tiling-a-rectangle-with-the-fewest-squares | def tilingRectangle(n: int, m: int) -> int:
"""
Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle.
Example 1:
>>> tilingRectangle(n = 2, m = 3)
>>> 3
Explanation: 3 squares are necessary to cover the rectangle.
2 (squar... |
web-crawler-multithreaded | # This is HtmlParser's API interface.
# You should not implement it, or speculate about its implementation
# """
#class HtmlParser(object):
# def getUrls(url):
# """
# :type url: str
# :rtype List[str]
# """
class Solution:
def crawl(startUrl: str, htmlParser: 'HtmlParser') -> List[s... |
array-transformation | def transformArray(arr: List[int]) -> List[int]:
"""
Given an initial array arr, every day you produce a new array using the array of the previous day.
On the i-th day, you do the following operations on the array of day i-1 to produce the array of day i:
If an element is smaller than both its left... |
tree-diameter | def treeDiameter(edges: List[List[int]]) -> int:
"""
The diameter of a tree is the number of edges in the longest path in that tree.
There is an undirected tree of n nodes labeled from 0 to n - 1. You are given a 2D array edges where edges.length == n - 1 and edges[i] = [ai, bi] indicates that there is an u... |
palindrome-removal | def minimumMoves(arr: List[int]) -> int:
"""
You are given an integer array arr.
In one move, you can select a palindromic subarray arr[i], arr[i + 1], ..., arr[j] where i <= j, and remove that subarray from the given array. Note that after removing a subarray, the elements on the left and on the right of t... |
minimum-swaps-to-make-strings-equal | def minimumSwap(s1: str, s2: str) -> int:
"""
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return th... |
count-number-of-nice-subarrays | def numberOfSubarrays(nums: List[int], k: int) -> int:
"""
Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
Example 1:
>>> numberOfSubarrays(nums = [1,1,2,1,1], k = 3)
>>> 2
... |
minimum-remove-to-make-valid-parentheses | def minRemoveToMakeValid(s: str) -> str:
"""
Given a string s of '(' , ')' and lowercase English characters.
Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses st... |
check-if-it-is-a-good-array | def isGoodArray(nums: List[int]) -> bool:
"""
Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand.
... |
cells-with-odd-values-in-a-matrix | def oddCells(m: int, n: int, indices: List[List[int]]) -> int:
"""
There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix.
For each location indices[i], do b... |
reconstruct-a-2-row-binary-matrix | def reconstructMatrix(upper: int, lower: int, colsum: List[int]) -> List[List[int]]:
"""
Given the following details of a matrix with n columns and 2 rows :
The matrix is a binary matrix, which means each element in the matrix can be 0 or 1.
The sum of elements of the 0-th(upper) row is given as up... |
number-of-closed-islands | def closedIsland(grid: List[List[int]]) -> int:
"""
Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.
Return the number of closed islands.
Exam... |
maximum-score-words-formed-by-letters | def maxScoreWords(words: List[str], letters: List[str], score: List[int]) -> int:
"""
Given a list of words, list of single letters (might be repeating) and score of every character.
Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more ti... |
encode-number | def encode(num: int) -> str:
"""
Given a non-negative integer num, Return its encoding string.\r
\r
The encoding is done by converting the integer to a string using a secret function that you should deduce from the following table:\r
\r
\r
\r
\r
Example 1:\r
\r
\r
>>> en... |
smallest-common-region | def findSmallestRegion(regions: List[List[str]], region1: str, region2: str) -> str:
"""
You are given some lists of regions where the first region of each list includes all other regions in that list.
Naturally, if a region x contains another region y then x is bigger than y. Also, by definition, a region ... |
synonymous-sentences | def generateSentences(synonyms: List[List[str]], text: str) -> List[str]:
"""
You are given a list of equivalent string pairs synonyms where synonyms[i] = [si, ti] indicates that si and ti are equivalent strings. You are also given a sentence text.
Return all possible synonymous sentences sorted lexicograph... |
handshakes-that-dont-cross | def numberOfWays(numPeople: int) -> int:
"""
You are given an even number of people numPeople that stand around a circle and each person shakes hands with someone else so that there are numPeople / 2 handshakes total.
Return the number of ways these handshakes could occur such that none of the handshakes cr... |
shift-2d-grid | def shiftGrid(grid: List[List[int]], k: int) -> List[List[int]]:
"""
Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.
In one shift operation:
Element at grid[i][j] moves to grid[i][j + 1].
Element at grid[i][n - 1] moves to grid[i + 1][0].
Element at grid[... |
greatest-sum-divisible-by-three | def maxSumDivThree(nums: List[int]) -> int:
"""
Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.
Example 1:
>>> maxSumDivThree(nums = [3,6,5,1,8])
>>> 18
Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (ma... |
minimum-moves-to-move-a-box-to-their-target-location | def minPushBox(grid: List[List[str]]) -> int:
"""
A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.
The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box.
Your task is to move the box '... |
minimum-time-visiting-all-points | def minTimeToVisitAllPoints(points: List[List[int]]) -> int:
"""
On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.
You can move according to these rules:
In 1 second, you can eith... |
count-servers-that-communicate | def countServers(grid: List[List[int]]) -> int:
"""
You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
... |
search-suggestions-system | def suggestedProducts(products: List[str], searchWord: str) -> List[List[str]]:
"""
You are given an array of strings products and a string searchWord.
Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common p... |
number-of-ways-to-stay-in-the-same-place-after-some-steps | def numWays(steps: int, arrLen: int) -> int:
"""
You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).
Given two integers s... |
hexspeak | def toHexspeak(num: str) -> str:
"""
A decimal number can be converted to its Hexspeak representation by first converting it to an uppercase hexadecimal string, then replacing all occurrences of the digit '0' with the letter 'O', and the digit '1' with the letter 'I'. Such a representation is valid if and only ... |
remove-interval | def removeInterval(intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]:
"""
A set of real numbers can be represented as the union of several disjoint intervals, where each interval is in the form [a, b). A real number x is in the set if one of its intervals [a, b) contains x (i.e. a <= x < b)... |
delete-tree-nodes | def deleteTreeNodes(nodes: int, parent: List[int], value: List[int]) -> int:
"""
A tree rooted at node 0 is given as follows:
The number of nodes is nodes;
The value of the ith node is value[i];
The parent of the ith node is parent[i].
Remove every subtree whose sum of values of nodes ... |
find-winner-on-a-tic-tac-toe-game | def tictactoe(moves: List[List[int]]) -> str:
"""
Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:
Players take turns placing characters into empty squares ' '.
The first player A always places 'X' characters, while the second player B always places 'O' ch... |
number-of-burgers-with-no-waste-of-ingredients | def numOfBurgers(tomatoSlices: int, cheeseSlices: int) -> List[int]:
"""
Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows:
Jumbo Burger: 4 tomato slices and 1 cheese slice.
Small Burger: 2 Tomato slices and 1 cheese slice.
Return [total_... |
count-square-submatrices-with-all-ones | def countSquares(matrix: List[List[int]]) -> int:
"""
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Example 1:
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
>>> countSquares(matrix =)
>>> 15
Explanation:
There are 10 squar... |
palindrome-partitioning-iii | def palindromePartition(s: str, k: int) -> int:
"""
You are given a string s containing lowercase letters and an integer k. You need to :
First, change some characters of s to other lowercase English letters.
Then divide s into k non-empty disjoint substrings such that each substring is a palindrom... |
subtract-the-product-and-sum-of-digits-of-an-integer | def subtractProductAndSum(n: int) -> int:
"""
Given an integer number n, return the difference between the product of its digits and the sum of its digits.
Example 1:
>>> subtractProductAndSum(n = 234)
>>> 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3... |
group-the-people-given-the-group-size-they-belong-to | def groupThePeople(groupSizes: List[int]) -> List[List[int]]:
"""
There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.
You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For ex... |
find-the-smallest-divisor-given-a-threshold | def smallestDivisor(nums: List[int], threshold: int) -> int:
"""
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to... |
minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix | def minFlips(mat: List[List[int]]) -> int:
"""
Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge.
Return the minimum number of step... |
element-appearing-more-than-25-in-sorted-array | def findSpecialInteger(arr: List[int]) -> int:
"""
Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
Example 1:
>>> findSpecialInteger(arr = [1,2,2,6,6,6,6,7,10])
>>> 6
Examp... |
remove-covered-intervals | def removeCoveredIntervals(intervals: List[List[int]]) -> int:
"""
Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.
The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b ... |
minimum-falling-path-sum-ii | def minFallingPathSum(grid: List[List[int]]) -> int:
"""
Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts.
A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in th... |
convert-binary-number-in-a-linked-list-to-integer | # class ListNode:
# def __init__(val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def getDecimalValue(head: Optional[ListNode]) -> int:
"""
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The ... |
sequential-digits | def sequentialDigits(low: int, high: int) -> List[int]:
"""
An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
Example 1:
>>> seque... |
maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | def maxSideLength(mat: List[List[int]], threshold: int) -> int:
"""
Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.
Example 1:
>>> maxSideLength(mat = [[1,1,3,2... |
shortest-path-in-a-grid-with-obstacles-elimination | def shortestPath(grid: List[List[int]], k: int) -> int:
"""
You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.
Return the minimum number of steps to walk from the upper left corner (0, 0... |
find-numbers-with-even-number-of-digits | def findNumbers(nums: List[int]) -> int:
"""
Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
>>> findNumbers(nums = [12,345,2,6,7896])
>>> 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (o... |
divide-array-in-sets-of-k-consecutive-numbers | def isPossibleDivide(nums: List[int], k: int) -> bool:
"""
Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers.
Return true if it is possible. Otherwise, return false.
Example 1:
>>> isPossibleDivide... |
maximum-number-of-occurrences-of-a-substring | def maxFreq(s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
"""
Given a string s, return the maximum number of occurrences of any substring under the following rules:
The number of unique characters in the substring must be less than or equal to maxLetters.
The substring size must be b... |
maximum-candies-you-can-get-from-boxes | def maxCandies(status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:
"""
You have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and containedBoxes where:
status[i] is 1 if the ith box is open ... |
replace-elements-with-greatest-element-on-right-side | def replaceElements(arr: List[int]) -> List[int]:
"""
Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.
After doing so, return the array.
Example 1:
>>> replaceElements(arr = [17,18,5,4,6... |
sum-of-mutated-array-closest-to-target | def findBestValue(arr: List[int], target: int) -> int:
"""
Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) t... |
number-of-paths-with-max-score | def pathsWithMaxScore(board: List[str]) -> List[int]:
"""
You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S'.\r
\r
You need to reach the top left square marked with the character 'E'. The rest of the squares are labeled... |
deepest-leaves-sum | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def deepestLeavesSum(root: Optional[TreeNode]) -> int:
"""
Given the root of a binary tree, return the sum of values of its deepest leaves.
... |
find-n-unique-integers-sum-up-to-zero | def sumZero(n: int) -> List[int]:
"""
Given an integer n, return any array containing n unique integers such that they add up to 0.
Example 1:
>>> sumZero(n = 5)
>>> [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].
Example 2:
>... |
all-elements-in-two-binary-search-trees | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getAllElements(root1: Optional[TreeNode], root2: Optional[TreeNode]) -> List[int]:
"""
Given two binary search trees root1 and root2, retur... |
jump-game-iii | def canReach(arr: List[int], start: int) -> bool:
"""
Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach any index with value 0.
Notice that you can not jump outside ... |
verbal-arithmetic-puzzle | def isSolvable(words: List[str], result: str) -> bool:
"""
Given an equation, represented by words on the left side and the result on the right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
No two characters can ma... |
decrypt-string-from-alphabet-to-integer-mapping | def freqAlphabets(s: str) -> str:
"""
You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows:
Characters ('a' to 'i') are represented by ('1' to '9') respectively.
Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.
... |
xor-queries-of-a-subarray | def xorQueries(arr: List[int], queries: List[List[int]]) -> List[int]:
"""
You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti].
For each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR .... |
get-watched-videos-by-your-friends | def watchedVideosByFriends(watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:
"""
There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and ... |
minimum-insertion-steps-to-make-a-string-palindrome | def minInsertions(s: str) -> int:
"""
Given a string s. In one step you can insert any character at any index of the string.
Return the minimum number of steps to make s palindrome.
A Palindrome String is one that reads the same backward as well as forward.
Example 1:
>>> minInsertions... |
decompress-run-length-encoded-list | def decompressRLElist(nums: List[int]) -> List[int]:
"""
We are given a list nums of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val con... |
matrix-block-sum | def matrixBlockSum(mat: List[List[int]], k: int) -> List[List[int]]:
"""
Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:
i - k <= r <= i + k,
j - k <= c <= j + k, and
(r, c) is a valid position in the matrix.
... |
sum-of-nodes-with-even-valued-grandparent | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumEvenGrandparent(root: Optional[TreeNode]) -> int:
"""
Given the root of a binary tree, return the sum of values of nodes with an even-va... |
distinct-echo-substrings | def distinctEchoSubstrings(text: str) -> int:
"""
Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).
Example 1:
>>> distinctEchoSubstrings(text = "abcabcabc")
... |
convert-integer-to-the-sum-of-two-no-zero-integers | def getNoZeroIntegers(n: int) -> List[int]:
"""
No-Zero integer is a positive integer that does not contain any 0 in its decimal representation.
Given an integer n, return a list of two integers [a, b] where:
a and b are No-Zero integers.
a + b = n
The test cases are generated so that ... |
minimum-flips-to-make-a-or-b-equal-to-c | def minFlips(a: int, b: int, c: int) -> int:
"""
Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).\r
Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.... |
number-of-operations-to-make-network-connected | def makeConnected(n: int, connections: List[List[int]]) -> int:
"""
There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or... |
minimum-distance-to-type-a-word-using-two-fingers | def minimumDistance(word: str) -> int:
"""
You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate.
For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is locate... |
print-words-vertically | def printVertically(s: str) -> List[str]:
"""
Given a string s. Return all the words vertically in the same order in which they appear in s.\r
Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).\r
Each word would be put on only one column a... |
delete-leaves-with-a-given-value | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def removeLeafNodes(root: Optional[TreeNode], target: int) -> Optional[TreeNode]:
"""
Given a binary tree root and an integer target, delete al... |
minimum-number-of-taps-to-open-to-water-a-garden | def minTaps(n: int, ranges: List[int]) -> int:
"""
There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e., the length of the garden is n).
There are n + 1 taps located at points [0, 1, ..., n] in the garden.
Given an integer n and an integer arra... |
break-a-palindrome | def breakPalindrome(palindrome: str) -> str:
"""
Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.
Return the resulti... |
sort-the-matrix-diagonally | def diagonalSort(mat: List[List[int]]) -> List[List[int]]:
"""
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], whe... |
reverse-subarray-to-maximize-array-value | def maxValueAfterReverse(nums: List[int]) -> int:
"""
You are given an integer array nums. The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1.
You are allowed to select any subarray of the given array and reverse it. You can perform this operation only ... |
rank-transform-of-an-array | def arrayRankTransform(arr: List[int]) -> List[int]:
"""
Given an array of integers arr, replace each element with its rank.
The rank represents how large the element is. The rank has the following rules:
Rank is an integer starting from 1.
The larger the element, the larger the rank. If two el... |
remove-palindromic-subsequences | def removePalindromeSub(s: str) -> int:
"""
You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.
Return the minimum number of steps to make the given string empty.
A string is a subsequence of a given string if it is generat... |
filter-restaurants-by-vegan-friendly-price-and-distance | def filterRestaurants(restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
"""
Given the array restaurants where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters.
The veganFriendly filter w... |
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance | def findTheCity(n: int, edges: List[List[int]], distanceThreshold: int) -> int:
"""
There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.
Retu... |
minimum-difficulty-of-a-job-schedule | def minDifficulty(jobDifficulty: List[int], d: int) -> int:
"""
You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i).
You have to finish at least one task every day. The difficulty of a job schedule is the sum of d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.