number
int64 1
1M
| question
stringlengths 153
4.6k
|
---|---|
100,311 |
class Solution:
def levelOrder(self, root: TreeNode) -> List[int]:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,312 |
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,313 |
class Solution:
def findNthDigit(self, n: int) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,314 |
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,315 |
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,316 |
class Solution:
def firstUniqChar(self, s: str) -> str:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,317 |
class Solution:
def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,318 |
class Solution:
def reversePairs(self, nums: List[int]) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Hard
|
100,319 |
class Solution:
def maxDepth(self, root: TreeNode) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,320 |
class Solution:
def singleNumbers(self, nums: List[int]) -> List[int]:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,321 |
class Solution:
def singleNumber(self, nums: List[int]) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,322 |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,323 |
class Solution:
def minNumber(self, nums: List[int]) -> str:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,324 |
class Solution:
def findContinuousSequence(self, target: int) -> List[List[int]]:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,325 |
class Solution:
def translateNum(self, num: int) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,326 |
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,327 |
class Solution:
def maxValue(self, grid: List[List[int]]) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,328 |
class Solution:
def reverseWords(self, s: str) -> str:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,329 |
class Solution:
def search(self, nums: List[int], target: int) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,330 |
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,331 |
class Solution:
def missingNumber(self, nums: List[int]) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,332 |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,333 |
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,334 |
class Solution:
def nthUglyNumber(self, n: int) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,335 |
class Solution:
def add(self, a: int, b: int) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,336 |
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Hard
|
100,337 |
class MaxQueue:
def __init__(self):
def max_value(self) -> int:
def push_back(self, value: int) -> None:
def pop_front(self) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,338 |
class Solution:
def constructArr(self, a: List[int]) -> List[int]:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,339 |
class Solution:
def dicesProbability(self, n: int) -> List[float]:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,340 |
class Solution:
def strToInt(self, str: str) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,341 |
class Solution:
def isStraight(self, nums: List[int]) -> bool:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,342 |
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,343 |
class Solution:
def lastRemaining(self, n: int, m: int) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,344 |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,345 |
class Solution:
def sumNums(self, n: int) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
100,346 |
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,347 |
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
100,348 |
class Solution:
def permutation(self, S: str) -> List[str]:
"""
Write a method to compute all permutations of a string whose characters are not necessarily unique. The list of permutations should not have duplicates.
Example1:
Input: S = "qqe"
Output: ["eqq","qeq","qqe"]
Example2:
Input: S = "ab"
Output: ["ab", "ba"]
Note:
All characters are English letters.
1 <= S.length <= 9
"""
# Medium
|
100,349 |
class Solution:
def maximum(self, a: int, b: int) -> int:
"""
Write a method that finds the maximum of two numbers. You should not use if-else or any other comparison operator.
Example:
Input: a = 1, b = 2
Output: 2
"""
# Easy
|
100,350 |
class Operations:
def __init__(self):
def minus(self, a: int, b: int) -> int:
def multiply(self, a: int, b: int) -> int:
def divide(self, a: int, b: int) -> int:
"""
Write methods to implement the multiply, subtract, and divide operations for integers. The results of all of these are integers. Use only the add operator.
You should implement following methods:
Operations() constructor
minus(a, b) Subtraction, returns a - b
multiply(a, b) Multiplication, returns a * b
divide(a, b) Division, returns a / b
Example:
Operations operations = new Operations();
operations.minus(1, 2); //returns -1
operations.multiply(3, 4); //returns 12
operations.divide(5, -2); //returns -2
Note:
You can assume inputs are always valid, that is, e.g., denominator will not be 0 in division.
The number of calls will not exceed 1000.
"""
# Medium
|
100,351 |
class Solution:
def maxAliveYear(self, birth: List[int], death: List[int]) -> int:
"""
Given a list of people with their birth and death years, implement a method to compute the year with the most number of people alive. You may assume that all people were born between 1900 and 2000 (inclusive). If a person was alive during any portion of that year, they should be included in that year's count. For example, Person (birth= 1908, death= 1909) is included in the counts for both 1908 and 1909.
If there are more than one years that have the most number of people alive, return the smallest one.
Example:
Input:
birth = [1900, 1901, 1950]
death = [1948, 1951, 2000]
Output: 1901
Note:
0 < birth.length == death.length <= 10000
birth[i] <= death[i]
"""
# Medium
|
100,352 |
class Solution:
def divingBoard(self, shorter: int, longer: int, k: int) -> List[int]:
"""
You are building a diving board by placing a bunch of planks of wood end-to-end. There are two types of planks, one of length shorter and one of length longer. You must use exactly K planks of wood. Write a method to generate all possible lengths for the diving board.
return all lengths in non-decreasing order.
Example:
Input:
shorter = 1
longer = 2
k = 3
Output: {3,4,5,6}
Note:
0 < shorter <= longer
0 <= k <= 100000
"""
# Easy
|
100,353 |
class Solution:
def cutSquares(self, square1: List[int], square2: List[int]) -> List[float]:
"""
Given two squares on a two-dimensional plane, find a line that would cut these two squares in half. Assume that the top and the bottom sides of the square run parallel to the x-axis.
Each square consists of three values, the coordinate of bottom left corner [X,Y] = [square[0],square[1]], and the side length of the square square[2]. The line will intersect to the two squares in four points. Return the coordinates of two intersection points [X1,Y1] and [X2,Y2] that the forming segment covers the other two intersection points in format of {X1,Y1,X2,Y2}. If X1 != X2, there should be X1 < X2, otherwise there should be Y1 <= Y2.
If there are more than one line that can cut these two squares in half, return the one that has biggest slope (slope of a line parallel to the y-axis is considered as infinity).
Example:
Input:
square1 = {-1, -1, 2}
square2 = {0, -1, 2}
Output: {-1,0,2,0}
Explanation: y = 0 is the line that can cut these two squares in half.
Note:
square.length == 3
square[2] > 0
"""
# Medium
|
100,354 |
class Solution:
def bestLine(self, points: List[List[int]]) -> List[int]:
"""
Given a two-dimensional graph with points on it, find a line which passes the most number of points.
Assume all the points that passed by the line are stored in list S sorted by their number. You need to return [S[0], S[1]], that is , two points that have smallest number. If there are more than one line that passes the most number of points, choose the one that has the smallest S[0]. If there are more that one line that has the same S[0], choose the one that has smallest S[1].
Example:
Input: [[0,0],[1,1],[1,0],[2,0]]
Output: [0,2]
Explanation: The numbers of points passed by the line are [0,2,3].
Note:
2 <= len(Points) <= 300
len(Points[i]) = 2
"""
# Medium
|
100,355 |
class Solution:
def masterMind(self, solution: str, guess: str) -> List[int]:
"""
The Game of Master Mind is played as follows:
The computer has four slots, and each slot will contain a ball that is red (R). yellow (Y). green (G) or blue (B). For example, the computer might have RGGB (Slot #1 is red, Slots #2 and #3 are green, Slot #4 is blue).
You, the user, are trying to guess the solution. You might, for example, guess YRGB.
When you guess the correct color for the correct slot, you get a "hit:' If you guess a color that exists but is in the wrong slot, you get a "pseudo-hit:' Note that a slot that is a hit can never count as a pseudo-hit.
For example, if the actual solution is RGBY and you guess GGRR, you have one hit and one pseudo-hit. Write a method that, given a guess and a solution, returns the number of hits and pseudo-hits.
Given a sequence of colors solution, and a guess, write a method that return the number of hits and pseudo-hit answer, where answer[0] is the number of hits and answer[1] is the number of pseudo-hit.
Example:
Input: solution="RGBY",guess="GGRR"
Output: [1,1]
Explanation: hit once, pseudo-hit once.
Note:
len(solution) = len(guess) = 4
There are only "R","G","B","Y" in solution and guess.
"""
# Easy
|
100,356 |
class Solution:
def subSort(self, array: List[int]) -> List[int]:
"""
Given an array of integers, write a method to find indices m and n such that if you sorted elements m through n, the entire array would be sorted. Minimize n - m (that is, find the smallest such sequence).
Return [m,n]. If there are no such m and n (e.g. the array is already sorted), return [-1, -1].
Example:
Input: [1,2,4,7,10,11,7,12,6,7,16,18,19]
Output: [3,9]
Note:
0 <= len(array) <= 1000000
"""
# Medium
|
1,000,003 |
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
"""
You are given an array of integers (both positive and negative). Find the contiguous sequence with the largest sum. Return the sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum 6.
Follow Up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
"""
# Easy
|
1,000,004 |
class Solution:
def patternMatching(self, pattern: str, value: str) -> bool:
"""
You are given two strings, pattern and value. The pattern string consists of just the letters a and b, describing a pattern within a string. For example, the string catcatgocatgo matches the pattern aabab (where cat is a and go is b). It also matches patterns like a, ab, and b. Write a method to determine if value matches pattern. a and b cannot be the same string.
Example 1:
Input: pattern = "abba", value = "dogcatcatdog"
Output: true
Example 2:
Input: pattern = "abba", value = "dogcatcatfish"
Output: false
Example 3:
Input: pattern = "aaaa", value = "dogcatcatdog"
Output: false
Example 4:
Input: pattern = "abba", value = "dogdogdogdog"
Output: true
Explanation: "a"="dogdog",b="",vice versa.
Note:
0 <= len(pattern) <= 1000
0 <= len(value) <= 1000
pattern only contains "a" and "b", value only contains lowercase letters.
"""
# Medium
|
1,000,005 |
class Solution:
def pondSizes(self, land: List[List[int]]) -> List[int]:
"""
You have an integer matrix representing a plot of land, where the value at that location represents the height above sea level. A value of zero indicates water. A pond is a region of water connected vertically, horizontally, or diagonally. The size of the pond is the total number of connected water cells. Write a method to compute the sizes of all ponds in the matrix.
Example:
Input:
[
[0,2,1,0],
[0,1,0,1],
[1,1,0,1],
[0,1,0,1]
]
Output: [1,2,4]
Note:
0 < len(land) <= 1000
0 < len(land[i]) <= 1000
"""
# Medium
|
1,000,006 |
class Solution:
def oneEditAway(self, first: str, second: str) -> bool:
"""
There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away.
Example 1:
Input:
first = "pale"
second = "ple"
Output: True
Example 2:
Input:
first = "pales"
second = "pal"
Output: False
"""
# Medium
|
1,000,007 |
class Solution:
def kthToLast(self, head: ListNode, k: int) -> int:
"""
Implement an algorithm to find the kth to last element of a singly linked list. Return the value of the element.
Note: This problem is slightly different from the original one in the book.
Example:
Input: 1->2->3->4->5 和 k = 2
Output: 4
Note:
k is always valid.
"""
# Easy
|
1,000,008 |
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
"""
Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions.
Example:
Input: head = 3->5->8->5->10->2->1, x = 5
Output: 3->1->2->10->5->5->8
"""
# Medium
|
1,000,009 |
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
"""
You are given a binary tree in which each node contains an integer value (which might be positive or negative). Design an algorithm to count the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
Example:
Given the following tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Output:
3
Explanation: Paths that have sum 22 are: [5,4,11,2], [5,8,4,5], [4,11,7]
Note:
node number <= 10000
"""
# Medium
|
1,000,010 |
class Solution:
def BSTSequences(self, root: TreeNode) -> List[List[int]]:
"""
A binary search tree was created by traversing through an array from left to right and inserting each element. Given a binary search tree with distinct elements, print all possible arrays that could have led to this tree.
Example:
Given the following tree:
2
/ \
1 3
Output:
[
[2,1,3],
[2,3,1]
]
"""
# Hard
|
1,000,011 |
class Solution:
def pathWithObstacles(self, obstacleGrid: List[List[int]]) -> List[List[int]]:
"""
Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right.
"off limits" and empty grid are represented by 1 and 0 respectively.
Return a valid path, consisting of row number and column number of grids in the path.
Example 1:
Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: [[0,0],[0,1],[0,2],[1,2],[2,2]]
Note:
r, c <= 100
"""
# Medium
|
1,000,012 |
class Solution:
def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:
"""
Do not return anything, modify A in-place instead.
You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.
Initially the number of elements in A and B are m and n respectively.
Example:
Input:
A = [1,2,3,0,0,0], m = 3
B = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Note:
A.length == n + m
"""
# Easy
|
1,000,013 |
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
In an array of integers, a "peak" is an element which is greater than or equal to the adjacent integers and a "valley" is an element which is less than or equal to the adjacent integers. For example, in the array {5, 8, 4, 2, 3, 4, 6}, {8, 6} are peaks and {5, 2} are valleys. Given an array of integers, sort the array into an alternating sequence of peaks and valleys.
Example:
Input: [5, 3, 1, 2, 3]
Output: [5, 1, 3, 2, 3]
Note:
nums.length <= 10000
"""
# Medium
|
1,000,015 |
class Solution:
def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
"""
Do not return anything, modify C in-place instead.
In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints:
(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto another tower.
(3) A disk cannot be placed on top of a smaller disk.
Write a program to move the disks from the first tower to the last using stacks.
Example1:
Input: A = [2, 1, 0], B = [], C = []
Output: C = [2, 1, 0]
Example2:
Input: A = [1, 0], B = [], C = []
Output: C = [1, 0]
Note:
A.length <= 14
"""
# Easy
|
1,000,016 |
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
"""
Given an M x N matrix in which each row and each column is sorted in ascending order, write a method to find an element.
Example:
Given matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false.
"""
# Medium
|
1,000,017 |
class Solution:
def trailingZeroes(self, n: int) -> int:
"""
Write an algorithm which computes the number of trailing zeros in n factorial.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Note: Your solution should be in logarithmic time complexity.
"""
# Easy
|
1,000,018 |
class Solution:
def numberToWords(self, num: int) -> str:
"""
Given any integer, print an English phrase that describes the integer (e.g., "One Thousand Two Hundred Thirty Four").
Example 1:
Input: 123
Output: "One Hundred Twenty Three"
Example 2:
Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Example 4:
Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
"""
# Hard
|
1,000,019 |
class Solution:
def convertBiNode(self, root: TreeNode) -> TreeNode:
"""
The data structure TreeNode is used for binary tree, but it can also used to represent a single linked list (where left is null, and right is the next node in the list). Implement a method to convert a binary search tree (implemented with TreeNode) into a single linked list. The values should be kept in order and the operation should be performed in place (that is, on the original data structure).
Return the head node of the linked list after converting.
Note: This problem is slightly different from the original one in the book.
Example:
Input: [4,2,5,1,3,null,6,0]
Output: [0,null,1,null,2,null,3,null,4,null,5,null,6]
Note:
The number of nodes will not exceed 100000.
"""
# Easy
|
1,000,020 |
class Solution:
def respace(self, dictionary: List[str], sentence: str) -> int:
"""
Oh, no! You have accidentally removed all spaces, punctuation, and capitalization in a lengthy document. A sentence like "I reset the computer. It still didn't boot!" became "iresetthecomputeritstilldidntboot''. You'll deal with the punctuation and capitalization later; right now you need to re-insert the spaces. Most of the words are in a dictionary but a few are not. Given a dictionary (a list of strings) and the document (a string), design an algorithm to unconcatenate the document in a way that minimizes the number of unrecognized characters. Return the number of unrecognized characters.
Note: This problem is slightly different from the original one in the book.
Example:
Input:
dictionary = ["looked","just","like","her","brother"]
sentence = "jesslookedjustliketimherbrother"
Output: 7
Explanation: After unconcatenating, we got "jess looked just like tim her brother", which containing 7 unrecognized characters.
Note:
0 <= len(sentence) <= 1000
The total number of characters in dictionary is less than or equal to 150000.
There are only lowercase letters in dictionary and sentence.
"""
# Medium
|
1,000,021 |
class Solution:
def smallestK(self, arr: List[int], k: int) -> List[int]:
"""
Design an algorithm to find the smallest K numbers in an array.
Example:
Input: arr = [1,3,5,7,2,4,6,8], k = 4
Output: [1,2,3,4]
Note:
0 <= len(arr) <= 100000
0 <= k <= min(100000, len(arr))
"""
# Medium
|
1,000,022 |
class Solution:
def longestWord(self, words: List[str]) -> str:
"""
Given a list of words, write a program to find the longest word made of other words in the list. If there are more than one answer, return the one that has smallest lexicographic order. If no answer, return an empty string.
Example:
Input: ["cat","banana","dog","nana","walk","walker","dogwalker"]
Output: "dogwalker"
Explanation: "dogwalker" can be made of "dog" and "walker".
Note:
0 <= len(words) <= 200
1 <= len(words[i]) <= 100
"""
# Medium
|
1,000,023 |
class Solution:
def massage(self, nums: List[int]) -> int:
"""
A popular masseuse receives a sequence of back-to-back appointment requests and is debating which ones to accept. She needs a break between appointments and therefore she cannot accept any adjacent requests. Given a sequence of back-to-back appoint ment requests, find the optimal (highest total booked minutes) set the masseuse can honor. Return the number of minutes.
Note: This problem is slightly different from the original one in the book.
Example 1:
Input: [1,2,3,1]
Output: 4
Explanation: Accept request 1 and 3, total minutes = 1 + 3 = 4
Example 2:
Input: [2,7,9,3,1]
Output: 12
Explanation: Accept request 1, 3 and 5, total minutes = 2 + 9 + 1 = 12
Example 3:
Input: [2,1,4,5,3,1,1,3]
Output: 12
Explanation: Accept request 1, 3, 5 and 8, total minutes = 2 + 4 + 3 + 3 = 12
"""
# Easy
|
1,000,024 |
class Solution:
def multiSearch(self, big: str, smalls: List[str]) -> List[List[int]]:
"""
Given a string band an array of smaller strings T, design a method to search b for each small string in T. Output positions of all strings in smalls that appear in big, where positions[i] is all positions of smalls[i].
Example:
Input:
big = "mississippi"
smalls = ["is","ppi","hi","sis","i","ssippi"]
Output: [[1,4],[8],[],[3],[1,4,7,10],[5]]
Note:
0 <= len(big) <= 1000
0 <= len(smalls[i]) <= 1000
The total number of characters in smalls will not exceed 100000.
No duplicated strings in smalls.
All characters are lowercase letters.
"""
# Medium
|
1,000,025 |
class Solution:
def add(self, a: int, b: int) -> int:
"""
Write a function that adds two numbers. You should not use + or any arithmetic operators.
Example:
Input: a = 1, b = 1
Output: 2
Note:
a and b may be 0 or negative.
The result fits in 32-bit integer.
"""
# Easy
|
1,000,026 |
class LRUCache:
def __init__(self, capacity: int):
def get(self, key: int) -> int:
def put(self, key: int, value: int) -> None:
"""
Design and build a "least recently used" cache, which evicts the least recently used item. The cache should map from keys to values (allowing you to insert and retrieve a value associated with a particular key) and be initialized with a max size. When it is full, it should evict the least recently used item.
You should implement following operations: get and put.
Get a value by key: get(key) - If key is in the cache, return the value, otherwise return -1.
Write a key-value pair to the cache: put(key, value) - If the key is not in the cache, then write its value to the cache. Evict the least recently used item before writing if necessary.
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
"""
# Medium
|
1,000,027 |
class Solution:
def calculate(self, s: str) -> int:
"""
Given an arithmetic equation consisting of positive integers, +, -, * and / (no parentheses), compute the result.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
Example 1:
Input: "3+2*2"
Output: 7
Example 2:
Input: " 3/2 "
Output: 1
Example 3:
Input: " 3+5 / 2 "
Output: 5
Note:
You may assume that the given expression is always valid.
Do not use the eval built-in library function.
"""
# Medium
|
1,000,028 |
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
Numbers are randomly generated and passed to a method. Write a program to find and maintain the median value as new values are generated.
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
For example,
[2,3,4], the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
Example:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
"""
# Hard
|
1,000,029 |
class Solution:
def trap(self, height: List[int]) -> int:
"""
Imagine a histogram (bar graph). Design an algorithm to compute the volume of water it could hold if someone poured water across the top. You can assume that each histogram bar has width 1.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
"""
# Hard
|
1,000,030 |
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[str]:
"""
Given two words of equal length that are in a dictionary, write a method to transform one word into another word by changing only one letter at a time. The new word you get in each step must be in the dictionary.
Write code to return a possible transforming sequence. If there is more than one sequence, return any of them.
Example 1:
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output:
["hit","hot","dot","lot","log","cog"]
Example 2:
Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: []
Explanation: endWord "cog" is not in the dictionary, so there's no possible transforming sequence.
"""
# Medium
|
1,000,031 |
class Solution:
def countEval(self, s: str, result: int) -> int:
"""
Given a boolean expression consisting of the symbols 0 (false), 1 (true), & (AND), | (OR), and ^ (XOR), and a desired boolean result value result, implement a function to count the number of ways of parenthesizing the expression such that it evaluates to result.
Example 1:
Input: s = "1^0|0|1", result = 0
Output: 2
Explanation: Two possible parenthesizing ways are:
1^(0|(0|1))
1^((0|0)|1)
Example 2:
Input: s = "0&0&0&1^1|0", result = 1
Output: 10
Note:
There are no more than 19 operators in s.
"""
# Medium
|
1,000,032 |
class Solution:
def missingNumber(self, nums: List[int]) -> int:
"""
An array contains all the integers from 0 to n, except for one number which is missing. Write code to find the missing integer. Can you do it in O(n) time?
Note: This problem is slightly different from the original one the book.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
"""
# Easy
|
1,000,033 |
class Solution:
def findLongestSubarray(self, array: List[str]) -> List[str]:
"""
Given an array filled with letters and numbers, find the longest subarray with an equal number of letters and numbers.
Return the subarray. If there are more than one answer, return the one which has the smallest index of its left endpoint. If there is no answer, return an empty arrary.
Example 1:
Input: ["A","1","B","C","D","2","3","4","E","5","F","G","6","7","H","I","J","K","L","M"]
Output: ["A","1","B","C","D","2","3","4","E","5","F","G","6","7"]
Example 2:
Input: ["A","A"]
Output: []
Note:
array.length <= 100000
"""
# Medium
|
1,000,034 |
class Solution:
def numberOf2sInRange(self, n: int) -> int:
"""
Write a method to count the number of 2s that appear in all the numbers between 0 and n (inclusive).
Example:
Input: 25
Output: 9
Explanation: (2, 12, 20, 21, 22, 23, 24, 25)(Note that 22 counts for two 2s.)
Note:
n <= 10^9
"""
# Hard
|
1,000,035 |
class Solution:
def trulyMostPopular(self, names: List[str], synonyms: List[str]) -> List[str]:
"""
Each year, the government releases a list of the 10000 most common baby names and their frequencies (the number of babies with that name). The only problem with this is that some names have multiple spellings. For example,"John" and ''Jon" are essentially the same name but would be listed separately in the list. Given two lists, one of names/frequencies and the other of pairs of equivalent names, write an algorithm to print a new list of the true frequency of each name. Note that if John and Jon are synonyms, and Jon and Johnny are synonyms, then John and Johnny are synonyms. (It is both transitive and symmetric.) In the final list, choose the name that are lexicographically smallest as the "real" name.
Example:
Input: names = ["John(15)","Jon(12)","Chris(13)","Kris(4)","Christopher(19)"], synonyms = ["(Jon,John)","(John,Johnny)","(Chris,Kris)","(Chris,Christopher)"]
Output: ["John(27)","Chris(36)"]
Note:
names.length <= 100000
"""
# Medium
|
1,000,036 |
class Solution:
def bestSeqAtIndex(self, height: List[int], weight: List[int]) -> int:
"""
A circus is designing a tower routine consisting of people standing atop one another's shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter than the person below him or her. Given the heights and weights of each person in the circus, write a method to compute the largest possible number of people in such a tower.
Example:
Input: height = [65,70,56,75,60,68] weight = [100,150,90,190,95,110]
Output: 6
Explanation: The longest tower is length 6 and includes from top to bottom: (56,90), (60,95), (65,100), (68,110), (70,150), (75,190)
Note:
height.length == weight.length <= 10000
"""
# Medium
|
1,000,037 |
class Solution:
def getKthMagicNumber(self, k: int) -> int:
"""
Design an algorithm to find the kth number such that the only prime factors are 3, 5, and 7. Note that 3, 5, and 7 do not have to be factors, but it should not have any other prime factors. For example, the first several multiples would be (in order) 1, 3, 5, 7, 9, 15, 21.
Example 1:
Input: k = 5
Output: 9
"""
# Medium
|
1,000,038 |
class Solution:
def majorityElement(self, nums: List[int]) -> int:
"""
A majority element is an element that makes up more than half of the items in an array. Given a integers array, find the majority element. If there is no majority element, return -1. Do this in O(N) time and O(1) space.
Example 1:
Input: [1,2,5,9,5,9,5,5,5]
Output: 5
Example 2:
Input: [3,2]
Output: -1
Example 3:
Input: [2,2,1,1,1,2,2]
Output: 2
"""
# Easy
|
1,000,039 |
class Solution:
def findClosest(self, words: List[str], word1: str, word2: str) -> int:
"""
You have a large text file containing words. Given any two different words, find the shortest distance (in terms of number of words) between them in the file. If the operation will be repeated many times for the same file (but different pairs of words), can you optimize your solution?
Example:
Input: words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student"
Output: 1
Note:
words.length <= 100000
"""
# Medium
|
1,000,040 |
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""
Write a method to sort an array of strings so that all the anagrams are in the same group.
Note: This problem is slightly different from the original one the book.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Notes:
All inputs will be in lowercase.
The order of your output does not matter.
"""
# Medium
|
1,000,041 |
class StreamRank:
def __init__(self):
def track(self, x: int) -> None:
def getRankOfNumber(self, x: int) -> int:
"""
Imagine you are reading in a stream of integers. Periodically, you wish to be able to look up the rank of a number x (the number of values less than or equal to x). lmplement the data structures and algorithms to support these operations. That is, implement the method track (int x), which is called when each number is generated, and the method getRankOfNumber(int x), which returns the number of values less than or equal to x.
Note: This problem is slightly different from the original one in the book.
Example:
Input:
["StreamRank", "getRankOfNumber", "track", "getRankOfNumber"]
[[], [1], [0], [0]]
Output:
[null,0,null,1]
Note:
x <= 50000
The number of calls of both track and getRankOfNumber methods are less than or equal to 2000.
"""
# Medium
|
1,000,042 |
class Solution:
def pairSums(self, nums: List[int], target: int) -> List[List[int]]:
"""
Design an algorithm to find all pairs of integers within an array which sum to a specified value.
Example 1:
Input: nums = [5,6,5], target = 11
Output: [[5,6]]
Example 2:
Input: nums = [5,6,5,6], target = 11
Output: [[5,6],[5,6]]
Note:
nums.length <= 100000
"""
# Medium
|
1,000,043 |
class Solution:
def shortestSeq(self, big: List[int], small: List[int]) -> List[int]:
"""
You are given two arrays, one shorter (with all distinct elements) and one longer. Find the shortest subarray in the longer array that contains all the elements in the shorter array. The items can appear in any order.
Return the indexes of the leftmost and the rightmost elements of the array. If there are more than one answer, return the one that has the smallest left index. If there is no answer, return an empty array.
Example 1:
Input:
big = [7,5,9,0,2,1,3,5,7,9,1,1,5,8,8,9,7]
small = [1,5,9]
Output: [7,10]
Example 2:
Input:
big = [1,2,3]
small = [4]
Output: []
Note:
big.length <= 100000
1 <= small.length <= 100000
"""
# Medium
|
1,000,044 |
class Solution:
def missingTwo(self, nums: List[int]) -> List[int]:
"""
You are given an array with all the numbers from 1 to N appearing exactly once, except for two number that is missing. How can you find the missing number in O(N) time and 0(1) space?
You can return the missing numbers in any order.
Example 1:
Input: [1]
Output: [2,3]
Example 2:
Input: [2,3]
Output: [1,4]
Note:
nums.length <= 30000
"""
# Hard
|
1,000,045 |
class Solution:
def findSquare(self, matrix: List[List[int]]) -> List[int]:
"""
Imagine you have a square matrix, where each cell (pixel) is either black or white Design an algorithm to find the maximum subsquare such that all four borders are filled with black pixels.
Return an array [r, c, size], where r, c are the row number and the column number of the subsquare's upper left corner respectively, and size is the side length of the subsquare. If there are more than one answers, return the one that has smallest r. If there are more than one answers that have the same r, return the one that has smallest c. If there's no answer, return an empty array.
Example 1:
Input:
[
[1,0,1],
[0,0,1],
[0,0,1]
]
Output: [1,0,2]
Explanation: 0 represents black, and 1 represents white, bold elements in the input is the answer.
Example 2:
Input:
[
[0,1,1],
[1,0,1],
[1,1,0]
]
Output: [0,0,1]
Note:
matrix.length == matrix[0].length <= 200
"""
# Medium
|
1,000,046 |
class Solution:
def getMaxMatrix(self, matrix: List[List[int]]) -> List[int]:
"""
Given an NxM matrix of positive and negative integers, write code to find the submatrix with the largest possible sum.
Return an array [r1, c1, r2, c2], where r1, c1 are the row number and the column number of the submatrix's upper left corner respectively, and r2, c2 are the row number of and the column number of lower right corner. If there are more than one answers, return any one of them.
Note: This problem is slightly different from the original one in the book.
Example:
Input:
[
[-1,0],
[0,-1]
]
Output: [0,1,0,1]
Note:
1 <= matrix.length, matrix[0].length <= 200
"""
# Hard
|
1,000,047 |
class Solution:
def getValidT9Words(self, num: str, words: List[str]) -> List[str]:
"""
On old cell phones, users typed on a numeric keypad and the phone would provide a list of words that matched these numbers. Each digit mapped to a set of 0 - 4 letters. Implement an algorithm to return a list of matching words, given a sequence of digits. You are provided a list of valid words. The mapping is shown in the diagram below:
Example 1:
Input: num = "8733", words = ["tree", "used"]
Output: ["tree", "used"]
Example 2:
Input: num = "2", words = ["a", "b", "c", "d"]
Output: ["a", "b", "c"]
Note:
num.length <= 1000
words.length <= 500
words[i].length == num.length
There are no number 0 and 1 in num.
"""
# Medium
|
1,000,048 |
class Solution:
def findSwapValues(self, array1: List[int], array2: List[int]) -> List[int]:
"""
Given two arrays of integers, find a pair of values (one value from each array) that you can swap to give the two arrays the same sum.
Return an array, where the first element is the element in the first array that will be swapped, and the second element is another one in the second array. If there are more than one answers, return any one of them. If there is no answer, return an empty array.
Example:
Input: array1 = [4, 1, 2, 1, 1, 2], array2 = [3, 6, 3, 3]
Output: [1, 3]
Example:
Input: array1 = [1, 2, 3], array2 = [4, 5, 6]
Output: []
Note:
1 <= array1.length, array2.length <= 100000
"""
# Medium
|
1,000,049 |
class Solution:
def maxRectangle(self, words: List[str]) -> List[str]:
"""
Given a list of millions of words, design an algorithm to create the largest possible rectangle of letters such that every row forms a word (reading left to right) and every column forms a word (reading top to bottom). The words need not be chosen consecutively from the list but all rows must be the same length and all columns must be the same height.
If there are more than one answer, return any one of them. A word can be used more than once.
Example 1:
Input: ["this", "real", "hard", "trh", "hea", "iar", "sld"]
Output:
[
"this",
"real",
"hard"
]
Example 2:
Input: ["aa"]
Output: ["aa","aa"]
Notes:
words.length <= 1000
words[i].length <= 100
It's guaranteed that all the words are randomly generated.
"""
# Hard
|
1,000,050 |
class Solution:
def printKMoves(self, K: int) -> List[str]:
"""
An ant is sitting on an infinite grid of white and black squares. It initially faces right. All squares are white initially.
At each step, it does the following:
(1) At a white square, flip the color of the square, turn 90 degrees right (clockwise), and move forward one unit.
(2) At a black square, flip the color of the square, turn 90 degrees left (counter-clockwise), and move forward one unit.
Write a program to simulate the first K moves that the ant makes and print the final board as a grid.
The grid should be represented as an array of strings, where each element represents one row in the grid. The black square is represented as 'X', and the white square is represented as '_', the square which is occupied by the ant is represented as 'L', 'U', 'R', 'D', which means the left, up, right and down orientations respectively. You only need to return the minimum matrix that is able to contain all squares that are passed through by the ant.
Example 1:
Input: 0
Output: ["R"]
Example 2:
Input: 2
Output:
[
"_X",
"LX"
]
Example 3:
Input: 5
Output:
[
"_U",
"X_",
"XX"
]
Note:
K <= 100000
"""
# Medium
|
1,000,051 |
class Solution:
def computeSimilarities(self, docs: List[List[int]]) -> List[str]:
"""
The similarity of two documents (each with distinct words) is defined to be the size of the intersection divided by the size of the union. For example, if the documents consist of integers, the similarity of {1, 5, 3} and {1, 7, 2, 3} is 0.4, because the intersection has size 2 and the union has size 5. We have a long list of documents (with distinct values and each with an associated ID) where the similarity is believed to be "sparse". That is, any two arbitrarily selected documents are very likely to have similarity 0. Design an algorithm that returns a list of pairs of document IDs and the associated similarity.
Input is a 2D array docs, where docs[i] is the document with id i. Return an array of strings, where each string represents a pair of documents with similarity greater than 0. The string should be formatted as {id1},{id2}: {similarity}, where id1 is the smaller id in the two documents, and similarity is the similarity rounded to four decimal places. You can return the array in any order.
Example:
Input:
[
[14, 15, 100, 9, 3],
[32, 1, 9, 3, 5],
[15, 29, 2, 6, 8, 7],
[7, 10]
]
Output:
[
"0,1: 0.2500",
"0,2: 0.1000",
"2,3: 0.1429"
]
Note:
docs.length <= 500
docs[i].length <= 500
The number of document pairs with similarity greater than 0 will not exceed 1000.
"""
# Hard
|
1,000,228 |
class Solution:
def divide(self, a: int, b: int) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
1,000,229 |
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
1,000,230 |
class Solution:
def countBits(self, n: int) -> List[int]:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
1,000,231 |
class Solution:
def addBinary(self, a: str, b: str) -> str:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Easy
|
1,000,232 |
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
1,000,233 |
class Solution:
def singleNumber(self, nums: List[int]) -> int:
"""
English description is not available for the problem. Please switch to Chinese.
"""
# Medium
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.