number
int64
1
1M
question
stringlengths
153
4.6k
2,710
class Solution: def minOperations(self, n: int) -> int: """ You are given a positive integer n, you can do the following operation any number of times: Add or subtract a power of 2 from n. Return the minimum number of operations to make n equal to 0. A number x is power of 2 if x == 2i where i >= 0. Example 1: Input: n = 39 Output: 3 Explanation: We can do the following operations: - Add 20 = 1 to n, so now n = 40. - Subtract 23 = 8 from n, so now n = 32. - Subtract 25 = 32 from n, so now n = 0. It can be shown that 3 is the minimum number of operations we need to make n equal to 0. Example 2: Input: n = 54 Output: 3 Explanation: We can do the following operations: - Add 21 = 2 to n, so now n = 56. - Add 23 = 8 to n, so now n = 64. - Subtract 26 = 64 from n, so now n = 0. So the minimum number of operations is 3. """ # Medium
2,711
class Solution: def minimumTime(self, grid: List[List[int]]) -> int: """ You are given a m x n matrix grid consisting of non-negative integers where grid[row][col] represents the minimum time required to be able to visit the cell (row, col), which means you can visit the cell (row, col) only when the time you visit it is greater than or equal to grid[row][col]. You are standing in the top-left cell of the matrix in the 0th second, and you must move to any adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second. Return the minimum time required in which you can visit the bottom-right cell of the matrix. If you cannot visit the bottom-right cell, then return -1. Example 1: Input: grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]] Output: 7 Explanation: One of the paths that we can take is the following: - at t = 0, we are on the cell (0,0). - at t = 1, we move to the cell (0,1). It is possible because grid[0][1] <= 1. - at t = 2, we move to the cell (1,1). It is possible because grid[1][1] <= 2. - at t = 3, we move to the cell (1,2). It is possible because grid[1][2] <= 3. - at t = 4, we move to the cell (1,1). It is possible because grid[1][1] <= 4. - at t = 5, we move to the cell (1,2). It is possible because grid[1][2] <= 5. - at t = 6, we move to the cell (1,3). It is possible because grid[1][3] <= 6. - at t = 7, we move to the cell (2,3). It is possible because grid[1][3] <= 7. The final time is 7. It can be shown that it is the minimum time possible. Example 2: Input: grid = [[0,2,4],[3,2,1],[1,0,4]] Output: -1 Explanation: There is no path from the top left to the bottom-right cell. """ # Hard
2,712
class Solution: def maxNumOfMarkedIndices(self, nums: List[int]) -> int: """ You are given a 0-indexed integer array nums. Initially, all of the indices are unmarked. You are allowed to make this operation any number of times: Pick two different unmarked indices i and j such that 2 * nums[i] <= nums[j], then mark i and j. Return the maximum possible number of marked indices in nums using the above operation any number of times. Example 1: Input: nums = [3,5,2,4] Output: 2 Explanation: In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] <= nums[1]. Then mark index 2 and 1. It can be shown that there's no other valid operation so the answer is 2. Example 2: Input: nums = [9,2,5,4] Output: 4 Explanation: In the first operation: pick i = 3 and j = 0, the operation is allowed because 2 * nums[3] <= nums[0]. Then mark index 3 and 0. In the second operation: pick i = 1 and j = 2, the operation is allowed because 2 * nums[1] <= nums[2]. Then mark index 1 and 2. Since there is no other operation, the answer is 4. Example 3: Input: nums = [7,6,8] Output: 0 Explanation: There is no valid operation to do, so the answer is 0. """ # Medium
2,713
class Solution: def divisibilityArray(self, word: str, m: int) -> List[int]: """ You are given a 0-indexed string word of length n consisting of digits, and a positive integer m. The divisibility array div of word is an integer array of length n such that: div[i] = 1 if the numeric value of word[0,...,i] is divisible by m, or div[i] = 0 otherwise. Return the divisibility array of word. Example 1: Input: word = "998244353", m = 3 Output: [1,1,0,0,0,1,1,0,0] Explanation: There are only 4 prefixes that are divisible by 3: "9", "99", "998244", and "9982443". Example 2: Input: word = "1010", m = 10 Output: [0,1,0,1] Explanation: There are only 2 prefixes that are divisible by 10: "10", and "1010". """ # Medium
2,714
class Solution: def leftRigthDifference(self, nums: List[int]) -> List[int]: """ Given a 0-indexed integer array nums, find a 0-indexed integer array answer where: answer.length == nums.length. answer[i] = |leftSum[i] - rightSum[i]|. Where: leftSum[i] is the sum of elements to the left of the index i in the array nums. If there is no such element, leftSum[i] = 0. rightSum[i] is the sum of elements to the right of the index i in the array nums. If there is no such element, rightSum[i] = 0. Return the array answer. Example 1: Input: nums = [10,4,8,3] Output: [15,1,11,22] Explanation: The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0]. The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22]. Example 2: Input: nums = [1] Output: [0] Explanation: The array leftSum is [0] and the array rightSum is [0]. The array answer is [|0 - 0|] = [0]. """ # Easy
100,092
class Solution: def fraction(self, cont: List[int]) -> List[int]: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,093
class Solution: def domino(self, n: int, m: int, broken: List[List[int]]) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Hard
100,094
class Solution: def bonus(self, n: int, leadership: List[List[int]], operations: List[List[int]]) -> List[int]: """ English description is not available for the problem. Please switch to Chinese. """ # Hard
100,096
class Solution: def robot(self, command: str, obstacles: List[List[int]], x: int, y: int) -> bool: """ English description is not available. Please switch to Chinese. """ # Medium
100,107
class Solution: def game(self, guess: List[int], answer: List[int]) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,158
class Solution: def isUnique(self, astr: str) -> bool: """ Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? Example 1: Input: s = "leetcode" Output: false Example 2: Input: s = "abc" Output: true Note: 0 <= len(s) <= 100 """ # Easy
100,159
class Solution: def CheckPermutation(self, s1: str, s2: str) -> bool: """ Given two strings,write a method to decide if one is a permutation of the other. Example 1: Input: s1 = "abc", s2 = "bca" Output: true Example 2: Input: s1 = "abc", s2 = "bad" Output: false Note: 0 <= len(s1) <= 100 0 <= len(s2) <= 100 """ # Easy
100,160
class Solution: def replaceSpaces(self, S: str, length: int) -> str: """ Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters,and that you are given the "true" length of the string. (Note: If implementing in Java,please use a character array so that you can perform this operation in place.) Example 1: Input: "Mr John Smith ", 13 Output: "Mr%20John%20Smith" Example 2: Input: " ", 5 Output: "%20%20%20%20%20" Note: 0 <= S.length <= 500000 """ # Easy
100,161
class Solution: def compressString(self, S: str) -> str: """ Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z). Example 1: Input: "aabcccccaaa" Output: "a2b1c5a3" Example 2: Input: "abbccd" Output: "abbccd" Explanation: The compressed string is "a1b2c2d1", which is longer than the original string. Note: 0 <= S.length <= 50000 """ # Easy
100,162
class Solution: def isFlipedString(self, s1: str, s2: str) -> bool: """ Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 (e.g.,"waterbottle" is a rotation of"erbottlewat"). Can you use only one call to the method that checks if one word is a substring of another? Example 1: Input: s1 = "waterbottle", s2 = "erbottlewat" Output: True Example 2: Input: s1 = "aa", s2 = "aba" Output: False Note: 0 <= s1.length, s2.length <= 100000 """ # Easy
100,163
class Solution: def removeDuplicateNodes(self, head: ListNode) -> ListNode: """ Write code to remove duplicates from an unsorted linked list. Example1: Input: [1, 2, 3, 3, 2, 1] Output: [1, 2, 3] Example2: Input: [1, 1, 1, 1, 2] Output: [1, 2] Note: The length of the list is within the range[0, 20000]. The values of the list elements are within the range [0, 20000]. Follow Up: How would you solve this problem if a temporary buffer is not allowed? """ # Easy
100,164
class Solution: def isPalindrome(self, head: ListNode) -> bool: """ Implement a function to check if a linked list is a palindrome. Example 1: Input: 1->2 Output: false Example 2: Input: 1->2->2->1 Output: true Follow up: Could you do it in O(n) time and O(1) space? """ # Easy
100,167
class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: """ Given two (singly) linked lists, determine if the two lists intersect. Return the inter­ secting node. Note that the intersection is defined based on reference, not value. That is, if the kth node of the first linked list is the exact same node (by reference) as the jth node of the second linked list, then they are intersecting. Example 1: Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 Output: Reference of the node with value = 8 Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. Example 2: Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 Output: Reference of the node with value = 2 Input Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [0,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. Example 3: Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 Output: null Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. Notes: If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Your code should preferably run in O(n) time and use only O(1) memory. """ # Easy
100,168
class Solution: def detectCycle(self, head: ListNode) -> ListNode: """ Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop. Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list. Example 1: Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Example 2: Input: head = [1,2], pos = 0 Output: tail connects to node index 0 Example 3: Input: head = [1], pos = -1 Output: no cycle Follow Up: Can you solve it without using additional space? """ # Medium
100,169
class MinStack: def __init__(self): """ initialize your data structure here. How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time. Example: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> return -3. minStack.pop(); minStack.top(); --> return 0. minStack.getMin(); --> return -2. """ # Easy
100,170
class MyQueue: def __init__(self): """ Initialize your data structure here. Implement a MyQueue class which implements a queue using two stacks. Example: MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // return 1 queue.pop(); // return 1 queue.empty(); // return false Notes: You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). """ # Easy
100,171
class Solution: def findWhetherExistsPath(self, n: int, graph: List[List[int]], start: int, target: int) -> bool: """ Given a directed graph, design an algorithm to find out whether there is a route between two nodes. Example1: Input: n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2 Output: true Example2: Input: n = 5, graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]], start = 0, target = 4 Output true Note: 0 <= n <= 100000 All node numbers are within the range [0, n]. There might be self cycles and duplicated edges. """ # Medium
100,172
class TripleInOne: def __init__(self, stackSize: int): def push(self, stackNum: int, value: int) -> None: def pop(self, stackNum: int) -> int: def peek(self, stackNum: int) -> int: def isEmpty(self, stackNum: int) -> bool: """ Describe how you could use a single array to implement three stacks. You should implement push(stackNum, value)、pop(stackNum)、isEmpty(stackNum)、peek(stackNum) methods. stackNum is the index of the stack. value is the value that pushed to the stack. The constructor requires a stackSize parameter, which represents the size of each stack. Example1: Input: ["TripleInOne", "push", "push", "pop", "pop", "pop", "isEmpty"] [[1], [0, 1], [0, 2], [0], [0], [0], [0]] Output: [null, null, null, 1, -1, -1, true] Explanation: When the stack is empty, `pop, peek` return -1. When the stack is full, `push` does nothing. Example2: Input: ["TripleInOne", "push", "push", "push", "pop", "pop", "pop", "peek"] [[2], [0, 1], [0, 2], [0, 3], [0], [0], [0], [0]] Output: [null, null, null, null, 2, 1, -1, -1] """ # Easy
100,173
class SortedStack: def __init__(self): def push(self, val: int) -> None: def pop(self) -> None: def peek(self) -> int: def isEmpty(self) -> bool: """ Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push, pop, peek, and isEmpty. When the stack is empty, peek should return -1. Example1: Input: ["SortedStack", "push", "push", "peek", "pop", "peek"] [[], [1], [2], [], [], []] Output: [null,null,null,1,null,2] Example2: Input: ["SortedStack", "pop", "pop", "push", "pop", "isEmpty"] [[], [], [], [1], [], []] Output: [null,null,null,null,null,true] Note: The total number of elements in the stack is within the range [0, 5000]. """ # Medium
100,174
class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: """ Given a sorted (increasing order) array with unique integer elements, write an algo­rithm to create a binary search tree with minimal height. Example: Given sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5],which represents the following tree: 0 / \ -3 9 / / -10 5 """ # Easy
100,175
class Solution: def listOfDepth(self, tree: TreeNode) -> List[ListNode]: """ Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists). Return a array containing all the linked lists. Example: Input: [1,2,3,4,5,null,7,8] 1 / \ 2 3 / \ \ 4 5 7 / 8 Output: [[1],[2,3],[4,5,7],[8]] """ # Medium
100,176
class Solution: def isBalanced(self, root: TreeNode) -> bool: """ Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one. Example 1: Given tree [3,9,20,null,null,15,7] 3 / \ 9 20 / \ 15 7 return true. Example 2: Given [1,2,2,3,3,null,null,4,4] 1 / \ 2 2 / \ 3 3 / \ 4 4 return false. """ # Easy
100,177
class Solution: def isValidBST(self, root: TreeNode) -> bool: """ Implement a function to check if a binary tree is a binary search tree. Example 1: Input: 2 / \ 1 3 Output: true Example 2: Input: 5 / \ 1 4 / \ 3 6 Output: false Explanation: Input: [5,1,4,null,null,3,6]. the value of root node is 5, but its right child has value 4. """ # Medium
100,178
class Solution: def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode: """ Write an algorithm to find the "next" node (i.e., in-order successor) of a given node in a binary search tree. Return null if there's no "next" node for the given node. Example 1: Input: root = [2,1,3], p = 1 2 / \ 1 3 Output: 2 Example 2: Input: root = [5,3,6,2,4,null,null,1], p = 6 5 / \ 3 6 / \ 2 4 / 1 Output: null """ # Medium
100,179
class Solution: def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode: """ Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree. For example, Given the following tree: root = [3,5,1,6,2,0,8,null,null,7,4] 3 / \ 5 1 / \ / \ 6 2 0 8 / \ 7 4 Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Input: 3 Explanation: The first common ancestor of node 5 and node 1 is node 3. Example 2: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The first common ancestor of node 5 and node 4 is node 5. Notes: All node values are pairwise distinct. p, q are different node and both can be found in the given tree. """ # Medium
100,180
class Solution: def insertBits(self, N: int, M: int, i: int, j: int) -> int: """ You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. That is, if M = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because M could not fully fit between bit 3 and bit 2. Example1: Input: N = 10000000000, M = 10011, i = 2, j = 6 Output: N = 10001001100 Example2: Input: N = 0, M = 11111, i = 0, j = 4 Output: N = 11111 """ # Easy
100,181
class Solution: def convertInteger(self, A: int, B: int) -> int: """ Write a function to determine the number of bits you would need to flip to convert integer A to integer B. Example1: Input: A = 29 (0b11101), B = 15 (0b01111) Output: 2 Example2: Input: A = 1,B = 2 Output: 2 Note: -2147483648 <= A, B <= 2147483647 """ # Easy
100,182
class Solution: def exchangeBits(self, num: int) -> int: """ Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on). Example1: Input: num = 2(0b10) Output 1 (0b01) Example2: Input: num = 3 Output: 3 Note: 0 <= num <= 2^30 - 1 The result integer fits into 32-bit integer. """ # Easy
100,183
class Solution: def findClosedNumbers(self, num: int) -> List[int]: """ Given a positive integer, print the next smallest and the next largest number that have the same number of 1 bits in their binary representation. Example1: Input: num = 2 (0b10) Output: [4, 1] ([0b100, 0b1]) Example2: Input: num = 1 Output: [2, -1] Note: 1 <= num <= 2147483647 If there is no next smallest or next largest number, output -1. """ # Medium
100,184
class Solution: def canPermutePalindrome(self, s: str) -> bool: """ Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words. Example1: Input: "tactcoa" Output: true(permutations: "tacocat"、"atcocta", etc.) """ # Easy
100,185
class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. Given an image represented by an N x N matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place? Example 1: Given matrix = [ [1,2,3], [4,5,6], [7,8,9] ], Rotate the matrix in place. It becomes: [ [7,4,1], [8,5,2], [9,6,3] ] Example 2: Given matrix = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ], Rotate the matrix in place. It becomes: [ [15,13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7,10,11] ] """ # Medium
100,186
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0. Example 1: Input: [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ] Example 2: Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ] """ # Medium
100,187
class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node. Example: Input: the node c from the linked list a->b->c->d->e->f Output: nothing is returned, but the new linked list looks like a->b->d->e->f """ # Easy
100,188
class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: """ You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. Example: Input: (7 -> 1 -> 6) + (5 -> 9 -> 2). That is, 617 + 295. Output: 2 -> 1 -> 9. That is, 912. Follow Up: Suppose the digits are stored in forward order. Repeat the above problem. Example: Input: (6 -> 1 -> 7) + (2 -> 9 -> 5). That is, 617 + 295. Output: 9 -> 1 -> 2. That is, 912. """ # Medium
100,195
class StackOfPlates: def __init__(self, cap: int): def push(self, val: int) -> None: def pop(self) -> int: def popAt(self, index: int) -> int: """ Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of several stacks and should create a new stack once the previous one exceeds capacity. SetOfStacks.push() and SetOfStacks.pop() should behave identically to a single stack (that is, pop() should return the same values as it would if there were just a single stack). Follow Up: Implement a function popAt(int index) which performs a pop operation on a specific sub-stack. You should delete the sub-stack when it becomes empty. pop, popAt should return -1 when there's no element to pop. Example1: Input: ["StackOfPlates", "push", "push", "popAt", "pop", "pop"] [[1], [1], [2], [1], [], []] Output: [null, null, null, 2, 1, -1] Explanation: Example2: Input: ["StackOfPlates", "push", "push", "push", "popAt", "popAt", "popAt"] [[2], [1], [2], [3], [0], [0], [0]] Output: [null, null, null, null, 2, 1, 3] """ # Medium
100,196
class Solution: def drawLine(self, length: int, w: int, x1: int, x2: int, y: int) -> List[int]: """ A monochrome screen is stored as a single array of int, allowing 32 consecutive pixels to be stored in one int. The screen has width w, where w is divisible by 32 (that is, no byte will be split across rows). The height of the screen, of course, can be derived from the length of the array and the width. Implement a function that draws a horizontal line from (x1, y) to (x2, y). Given the length of the array, the width of the array (in bit), start position x1 (in bit) of the line, end position x2 (in bit) of the line and the row number y of the line, return the array after drawing. Example1: Input: length = 1, w = 32, x1 = 30, x2 = 31, y = 0 Output: [3] Explanation: After drawing a line from (30, 0) to (31, 0), the screen becomes [0b000000000000000000000000000000011]. Example2: Input: length = 3, w = 96, x1 = 0, x2 = 95, y = 0 Output: [-1, -1, -1] """ # Medium
100,197
class Solution: def waysToStep(self, n: int) -> int: """ A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. The result may be large, so return it modulo 1000000007. Example1: Input: n = 3 Output: 4 Example2: Input: n = 5 Output: 13 Note: 1 <= n <= 1000000 """ # Easy
100,198
class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: """ Write a method to return all subsets of a set. The elements in a set are pairwise distinct. Note: The result set should not contain duplicated subsets. Example: Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] """ # Medium
100,199
class Solution: def multiply(self, A: int, B: int) -> int: """ Write a recursive function to multiply two positive integers without using the * operator. You can use addition, subtraction, and bit shifting, but you should minimize the number of those operations. Example 1: Input: A = 1, B = 10 Output: 10 Example 2: Input: A = 3, B = 4 Output: 12 Note: The result will not overflow. """ # Medium
100,200
class Solution: def generateParenthesis(self, n: int) -> List[str]: """ Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n pairs of parentheses. Note: The result set should not contain duplicated subsets. For example, given n = 3, the result should be: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] """ # Medium
100,201
class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: """ Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color, fill in the surrounding area until the color changes from the original color. Example1: Input: image = [[1,1,1],[1,1,0],[1,0,1]] sr = 1, sc = 1, newColor = 2 Output: [[2,2,2],[2,2,0],[2,0,1]] Explanation: From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected by a path of the same color as the starting pixel are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel. Note: The length of image and image[0] will be in the range [1, 50]. The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length. The value of each color in image[i][j] and newColor will be an integer in [0, 65535]. """ # Easy
100,202
class Solution: def pileBox(self, box: List[List[int]]) -> int: """ You have a stack of n boxes, with widths wi, depths di, and heights hi. The boxes cannot be rotated and can only be stacked on top of one another if each box in the stack is strictly larger than the box above it in width, height, and depth. Implement a method to compute the height of the tallest possible stack. The height of a stack is the sum of the heights of each box. The input use [wi, di, hi] to represents each box. Example1: Input: box = [[1, 1, 1], [2, 2, 2], [3, 3, 3]] Output: 6 Example2: Input: box = [[1, 1, 1], [2, 3, 4], [2, 6, 7], [3, 4, 5]] Output: 10 Note: box.length <= 3000 """ # Hard
100,203
class Solution: def printBin(self, num: float) -> str: """ Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR". Example1: Input: 0.625 Output: "0.101" Example2: Input: 0.1 Output: "ERROR" Note: 0.1 cannot be represented accurately in binary. Note: This two charaters "0." should be counted into 32 characters. The number of decimal places for num is at most 6 digits """ # Medium
100,228
class AnimalShelf: def __init__(self): def enqueue(self, animal: List[int]) -> None: def dequeueAny(self) -> List[int]: def dequeueDog(self) -> List[int]: def dequeueCat(self) -> List[int]: """ An animal shelter, which holds only dogs and cats, operates on a strictly"first in, first out" basis. People must adopt either the"oldest" (based on arrival time) of all animals at the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot select which specific animal they would like. Create the data structures to maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog, and dequeueCat. You may use the built-in Linked list data structure. enqueue method has a animal parameter, animal[0] represents the number of the animal, animal[1] represents the type of the animal, 0 for cat and 1 for dog. dequeue* method returns [animal number, animal type], if there's no animal that can be adopted, return [-1, -1]. Example1: Input: ["AnimalShelf", "enqueue", "enqueue", "dequeueCat", "dequeueDog", "dequeueAny"] [[], [[0, 0]], [[1, 0]], [], [], []] Output: [null,null,null,[0,0],[-1,-1],[1,0]] Example2: Input: ["AnimalShelf", "enqueue", "enqueue", "enqueue", "dequeueDog", "dequeueCat", "dequeueAny"] [[], [[0, 0]], [[1, 0]], [[2, 1]], [], [], []] Output: [null,null,null,null,[2,1],[0,0],[1,0]] Note: The number of animals in the shelter will not exceed 20000. """ # Easy
100,229
class Solution: def checkSubTree(self, t1: TreeNode, t2: TreeNode) -> bool: """ T1 and T2 are two very large binary trees. Create an algorithm to determine if T2 is a subtree of T1. A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical. Note: This problem is slightly different from the original problem. Example1: Input: t1 = [1, 2, 3], t2 = [2] Output: true Example2: Input: t1 = [1, null, 2, 4], t2 = [3, 2] Output: false Note: The node numbers of both tree are in [0, 20000]. """ # Medium
100,230
class Solution: def reverseBits(self, num: int) -> int: """ You have an integer and you can flip exactly one bit from a 0 to a 1. Write code to find the length of the longest sequence of 1s you could create. Example 1: Input: num = 1775(110111011112) Output: 8 Example 2: Input: num = 7(01112) Output: 4 """ # Easy
100,231
class Solution: def waysToChange(self, n: int) -> int: """ Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent), write code to calculate the number of ways of representing n cents. (The result may be large, so you should return it modulo 1000000007) Example1: Input: n = 5 Output: 2 Explanation: There are two ways: 5=5 5=1+1+1+1+1 Example2: Input: n = 10 Output: 4 Explanation: There are four ways: 10=10 10=5+5 10=5+1+1+1+1+1 10=1+1+1+1+1+1+1+1+1+1 Notes: You can assume: 0 <= n <= 1000000 """ # Medium
100,232
class Solution: def search(self, arr: List[int], target: int) -> int: """ Given a sorted array of n integers that has been rotated an unknown number of times, write code to find an element in the array. You may assume that the array was originally sorted in increasing order. If there are more than one target elements in the array, return the smallest index. Example1: Input: arr = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], target = 5 Output: 8 (the index of 5 in the array) Example2: Input: arr = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], target = 11 Output: -1 (not found) Note: 1 <= arr.length <= 1000000 """ # Medium
100,233
class Solution: def solveNQueens(self, n: int) -> List[List[str]]: """ Write an algorithm to print all ways of arranging n queens on an n x n chess board so that none of them share the same row, column, or diagonal. In this case, "diagonal" means all diagonals, not just the two that bisect the board. Notes: This problem is a generalization of the original one in the book. Example: Input: 4 Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] Explanation: 4 queens has following two solutions [ [".Q..", // solution 1 "...Q", "Q...", "..Q."], ["..Q.", // solution 2 "Q...", "...Q", ".Q.."] ] """ # Hard
100,240
class Solution: def findMagicIndex(self, nums: List[int]) -> int: """ A magic index in an array A[0...n-1] is defined to be an index such that A[i] = i. Given a sorted array of integers, write a method to find a magic index, if one exists, in array A. If not, return -1. If there are more than one magic index, return the smallest one. Example1: Input: nums = [0, 2, 3, 4, 5] Output: 0 Example2: Input: nums = [1, 1, 1] Output: 1 Note: 1 <= nums.length <= 1000000 This problem is the follow-up of the original problem in the book, i.e. the values are not distinct. """ # Easy
100,241
class Solution: def permutation(self, S: str) -> List[str]: """ Write a method to compute all permutations of a string of unique characters. Example1: Input: S = "qwe" Output: ["qwe", "qew", "wqe", "weq", "ewq", "eqw"] Example2: Input: S = "ab" Output: ["ab", "ba"] Note: All charaters are English letters. 1 <= S.length <= 9 """ # Medium
100,242
class Solution: def findString(self, words: List[str], s: str) -> int: """ Given a sorted array of strings that is interspersed with empty strings, write a method to find the location of a given string. Example1: Input: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ta" Output: -1 Explanation: Return -1 if s is not in words. Example2: Input: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ball" Output: 4 Note: 1 <= words.length <= 1000000 """ # Easy
100,258
class Solution: def swapNumbers(self, numbers: List[int]) -> List[int]: """ Write a function to swap a number in place (that is, without temporary variables). Example: Input: numbers = [1,2] Output: [2,1] Note: numbers.length == 2 -2147483647 <= numbers[i] <= 2147483647 """ # Medium
100,259
class WordsFrequency: def __init__(self, book: List[str]): def get(self, word: str) -> int: """ Design a method to find the frequency of occurrences of any given word in a book. What if we were running this algorithm multiple times? You should implement following methods: WordsFrequency(book) constructor, parameter is a array of strings, representing the book. get(word) get the frequency of word in the book. Example: WordsFrequency wordsFrequency = new WordsFrequency({"i", "have", "an", "apple", "he", "have", "a", "pen"}); wordsFrequency.get("you"); //returns 0,"you" is not in the book wordsFrequency.get("have"); //returns 2,"have" occurs twice in the book wordsFrequency.get("an"); //returns 1 wordsFrequency.get("apple"); //returns 1 wordsFrequency.get("pen"); //returns 1 Note: There are only lowercase letters in book[i]. 1 <= book.length <= 100000 1 <= book[i].length <= 10 get function will not be called more than 100000 times. """ # Medium
100,260
class Solution: def intersection(self, start1: List[int], end1: List[int], start2: List[int], end2: List[int]) -> List[float]: """ Given two straight line segments (represented as a start point and an end point), compute the point of intersection, if any. If there's no intersection, return an empty array. The absolute error should not exceed 10^-6. If there are more than one intersections, return the one with smallest X axis value. If there are more than one intersections that have same X axis value, return the one with smallest Y axis value. Example 1: Input: line1 = {0, 0}, {1, 0} line2 = {1, 1}, {0, -1} Output: {0.5, 0} Example 2: Input: line1 = {0, 0}, {3, 3} line2 = {1, 1}, {2, 2} Output: {1, 1} Example 3: Input: line1 = {0, 0}, {1, 1} line2 = {1, 0}, {2, 1} Output: {} (no intersection) Note: The absolute value of coordinate value will not exceed 2^7. All coordinates are valid 2D coordinates. """ # Hard
100,261
class Solution: def tictactoe(self, board: List[str]) -> str: """ Design an algorithm to figure out if someone has won a game of tic-tac-toe. Input is a string array of size N x N, including characters " ", "X" and "O", where " " represents a empty grid. The rules of tic-tac-toe are as follows: Players place characters into an empty grid(" ") in turn. The first player always place character "O", and the second one place "X". Players are only allowed to place characters in empty grid. Replacing a character is not allowed. If there is any row, column or diagonal filled with N same characters, the game ends. The player who place the last charater wins. When there is no empty grid, the game ends. If the game ends, players cannot place any character further. If there is any winner, return the character that the winner used. If there's a draw, return "Draw". If the game doesn't end and there is no winner, return "Pending". Example 1: Input: board = ["O X"," XO","X O"] Output: "X" Example 2: Input: board = ["OOX","XXO","OXO"] Output: "Draw" Explanation: no player wins and no empty grid left Example 3: Input: board = ["OOX","XXO","OX "] Output: "Pending" Explanation: no player wins but there is still a empty grid Note: 1 <= board.length == board[i].length <= 100 Input follows the rules. """ # Medium
100,262
class Solution: def smallestDifference(self, a: List[int], b: List[int]) -> int: """ Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference. Example: Input: {1, 3, 15, 11, 2}, {23, 127, 235, 19, 8} Output: 3, the pair (11, 8) Note: 1 <= a.length, b.length <= 100000 -2147483648 <= a[i], b[i] <= 2147483647 The result is in the range [0, 2147483647] """ # Medium
100,273
class CQueue: def __init__(self): def appendTail(self, value: int) -> None: def deleteHead(self) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,274
class Solution: def fib(self, n: int) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,275
class Solution: def findRepeatNumber(self, nums: List[int]) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,276
class Solution: def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool: """ English description is not available for the problem. Please switch to Chinese. """ # Medium
100,277
class Solution: def numWays(self, n: int) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,278
class Solution: def minArray(self, numbers: List[int]) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,279
class Solution: def exist(self, board: List[List[str]], word: str) -> bool: """ English description is not available for the problem. Please switch to Chinese. """ # Medium
100,280
class Solution: def replaceSpace(self, s: str) -> str: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,281
class Solution: def movingCount(self, m: int, n: int, k: int) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Medium
100,282
class Solution: def reversePrint(self, head: ListNode) -> List[int]: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,283
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: """ English description is not available for the problem. Please switch to Chinese. """ # Medium
100,284
class Solution: def cuttingRope(self, n: int) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Medium
100,285
class Solution: def cuttingRope(self, n: int) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Medium
100,286
class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,287
class Solution: def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool: """ English description is not available for the problem. Please switch to Chinese. """ # Medium
100,288
class Solution: def mirrorTree(self, root: TreeNode) -> TreeNode: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,289
class Solution: def isSymmetric(self, root: TreeNode) -> bool: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,290
class Solution: def isNumber(self, s: str) -> bool: """ English description is not available for the problem. Please switch to Chinese. """ # Medium
100,291
class Solution: def exchange(self, nums: List[int]) -> List[int]: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,292
class Solution: def hammingWeight(self, n: int) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,293
class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,294
class Solution: def getKthFromEnd(self, head: ListNode, k: int) -> ListNode: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,295
class Solution: def myPow(self, x: float, n: int) -> float: """ English description is not available for the problem. Please switch to Chinese. """ # Medium
100,296
class Solution: def printNumbers(self, n: int) -> List[int]: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,297
class Solution: def isMatch(self, s: str, p: str) -> bool: """ English description is not available for the problem. Please switch to Chinese. """ # Hard
100,298
class Solution: def reverseList(self, head: ListNode) -> ListNode: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,299
class Solution: def deleteNode(self, head: ListNode, val: int) -> ListNode: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,300
""" class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random English description is not available for the problem. Please switch to Chinese. """ # Medium
100,301
class Solution: def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,302
class MinStack: def __init__(self): """ initialize your data structure here. English description is not available for the problem. Please switch to Chinese. """ # Easy
100,303
class MedianFinder: def __init__(self): """ initialize your data structure here. English description is not available for the problem. Please switch to Chinese. """ # Hard
100,304
class Solution: def maxSubArray(self, nums: List[int]) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Easy
100,305
""" class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right English description is not available for the problem. Please switch to Chinese. """ # Medium
100,306
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: """ English description is not available for the problem. Please switch to Chinese. """ # Medium
100,307
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str English description is not available for the problem. Please switch to Chinese. """ # Hard
100,308
class Solution: def permutation(self, s: str) -> List[str]: """ English description is not available for the problem. Please switch to Chinese. """ # Medium
100,309
class Solution: def countDigitOne(self, n: int) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Hard
100,310
class Solution: def majorityElement(self, nums: List[int]) -> int: """ English description is not available for the problem. Please switch to Chinese. """ # Easy