problem_id
int64
0
5k
question
stringlengths
50
14k
solutions
stringlengths
12
1.21M
input_output
stringlengths
0
23.6M
difficulty
stringclasses
3 values
url
stringlengths
36
108
starter_code
stringlengths
0
1.4k
1,900
Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null. The width of one level is defined as the length between the end-nodes (the leftmost and ri...
["class Solution:\n def widthOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if not root:\n return 0\n s=1\n a=[[root,1]]\n while 1:\n b=[]\n for p in a:\n if p[0].l...
interview
https://leetcode.com/problems/maximum-width-of-binary-tree/
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def widthOfBinaryTree(self, root: TreeNode) -> int:
1,901
In a 2D grid of 0s and 1s, we change at most one 0 to a 1. After, what is the size of the largest island? (An island is a 4-directionally connected group of 1s). Example 1: Input: [[1, 0], [0, 1]] Output: 3 Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3. Example 2: Input: [[1, 1...
["class Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n for i in range(len(grid)):\n grid[i].insert(0, 0)\n grid[i].append(0)\n grid.insert(0, [0 for i in range(len(grid[0]))])\n grid.append([0 fo...
interview
https://leetcode.com/problems/making-a-large-island/
class Solution: def largestIsland(self, grid: List[List[int]]) -> int:
1,902
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: Input: low = 100, high = 300 Output: [123,234] Example 2: Input: low = 1000, high = 13000 Ou...
["class Solution:\n def sequentialDigits(self, low: int, high: int) -> List[int]:\n l=len(str(low))\n f=len(str(high))\n s=len(str(low)[0])\n a=[]\n for i in range(l,f+1):\n while True:\n t=''\n if i+s>10:\n break\n ...
interview
https://leetcode.com/problems/sequential-digits/
class Solution: def sequentialDigits(self, low: int, high: int) -> List[int]:
1,903
You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val. Return the minimum cost to make a...
["class Solution:\n def minCostConnectPoints(self, points: List[List[int]]) -> int:\n n = len(points)\n dist = [float(\\\"inf\\\")] * n\n remain = set()\n for i in range(0,n):\n remain.add(i)\n dist[0] = 0\n remain.discard(0)\n curr = 0\n res = 0\n ...
interview
https://leetcode.com/problems/min-cost-to-connect-all-points/
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int:
1,904
We have a list of points on the plane.  Find the K closest points to the origin (0, 0). (Here, the distance between two points on a plane is the Euclidean distance.) You may return the answer in any order.  The answer is guaranteed to be unique (except for the order that it is in.)   Example 1: Input: points = [[1,3],...
["class Solution:\n def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:\n points.sort(key = lambda x: x[0]*x[0] + x[1]*x[1])\n return points[:K]", "class Solution:\n def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:\n points.sort(key=lambda x:x[0]*x[0...
interview
https://leetcode.com/problems/k-closest-points-to-origin/
class Solution: def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
1,905
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0. If there are multiple solutions, return any subset is fine. Example 1: nums: [1,2,3] Result: [1,2] (of course, [1,3] will also be ok) Example 2: nu...
["from math import sqrt\n class Solution:\n def largestDivisibleSubset(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n nums.sort()\n l, prev = {}, {} # length, previous number(largest divisor in nums)\n max_l, end_number = 0, None...
interview
https://leetcode.com/problems/largest-divisible-subset/
class Solution: def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
1,906
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue. Note: The number of ...
["class Solution:\n def reconstructQueue(self, people):\n \"\"\"\n :type people: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n people.sort(key = lambda x: (-x[0], x[1]))\n queue = []\n for p in people:\n queue.insert(p[1], p)\n retur...
interview
https://leetcode.com/problems/queue-reconstruction-by-height/
class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
1,907
Given two binary trees original and cloned and given a reference to a node target in the original tree. The cloned tree is a copy of the original tree. Return a reference to the same node in the cloned tree. Note that you are not allowed to change any of the two trees or the target node and the answer must be a referen...
["# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n def getnode(root):\n ...
interview
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
1,908
Given a complete binary tree, count the number of nodes. Note: Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the l...
["# Definition for a binary tree node.\n # class TreeNode:\n # def __init__(self, x):\n # self.val = x\n # self.left = None\n # self.right = None\n \n class Solution:\n def countNodes(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n ...
interview
https://leetcode.com/problems/count-complete-tree-nodes/
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def countNodes(self, root: TreeNode) -> int:
1,909
Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid.   Example 1: Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: 9 Example 2: Input: grid = [[1,1,0,0]] Output: 1   Constraints: 1 <= grid.length <= 1...
["class Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n rows = len(grid)\n cols = len(grid[0])\n memo = [[0 for j in range(cols)] for i in range(rows)]\n ans = 0\n \n if grid[0][0] == 1:\n memo[0][0] = (1,1)\n ans = 1\n ...
interview
https://leetcode.com/problems/largest-1-bordered-square/
class Solution: def largest1BorderedSquare(self, grid: List[List[int]]) -> int:
1,910
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. Example: Given this linked list...
["# Definition for singly-linked list.\n # class ListNode:\n # def __init__(self, x):\n # self.val = x\n # self.next = None\n \n class Solution:\n def kth(self, v, k):\n for i in range(k-1):\n if not v:\n return None\n v=v.next\n return v\n...
interview
https://leetcode.com/problems/reverse-nodes-in-k-group/
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
1,911
Sort a linked list in O(n log n) time using constant space complexity. Example 1: Input: 4->2->1->3 Output: 1->2->3->4 Example 2: Input: -1->5->3->4->0 Output: -1->0->3->4->5
["# Definition for singly-linked list.\n # class ListNode:\n # def __init__(self, x):\n # self.val = x\n # self.next = None\n \n class Solution:\n def sortList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n arr = []\n p ...
interview
https://leetcode.com/problems/sort-list/
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def sortList(self, head: ListNode) -> ListNode:
1,912
Given many words, words[i] has weight i. Design a class WordFilter that supports one function, WordFilter.f(String prefix, String suffix). It will return the word with given prefix and suffix with maximum weight. If no word exists, return -1. Examples: Input: WordFilter(["apple"]) WordFilter.f("a", "e") // returns...
["class Solution:\n def nextGreatestLetter(self, letters, target):\n \"\"\"\n :type letters: List[str]\n :type target: str\n :rtype: str\n \"\"\"\n \n if ord(letters[-1]) <= ord(target):\n return letters[0]\n \n li = 0\n ri ...
interview
https://leetcode.com/problems/prefix-and-suffix-search/
class WordFilter: def __init__(self, words: List[str]): def f(self, prefix: str, suffix: str) -> int: # Your WordFilter object will be instantiated and called as such: # obj = WordFilter(words) # param_1 = obj.f(prefix,suffix)
1,913
Given an array A of positive integers (not necessarily distinct), return the lexicographically largest permutation that is smaller than A, that can be made with one swap (A swap exchanges the positions of two numbers A[i] and A[j]).  If it cannot be done, then return the same array.   Example 1: Input: [3,2,1] Output: ...
["class Solution:\n def prevPermOpt1(self, A: List[int]) -> List[int]:\n n = len(A)\n if n == 1: return A\n \n tidx = -1\n for i in range(n-2, -1, -1):\n if A[i] > A[i+1]:\n tidx = i\n break\n \n if tidx < 0: return A\n ...
interview
https://leetcode.com/problems/previous-permutation-with-one-swap/
class Solution: def prevPermOpt1(self, A: List[int]) -> List[int]:
1,914
A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti. Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.  ...
["class Solution:\n def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n dcosts = sorted(costs, key=lambda i: i[0] - i[1])\n n = len(costs) // 2\n acost = sum(c[0] for c in dcosts[:n])\n bcost = sum(c[1] for c in dcosts[n:])\n return acost + bcost", "class Solution:\n de...
interview
https://leetcode.com/problems/two-city-scheduling/
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int:
1,915
You want to form a target string of lowercase letters. At the beginning, your sequence is target.length '?' marks.  You also have a stamp of lowercase letters. On each turn, you may place the stamp over the sequence, and replace every letter in the sequence with the corresponding letter from the stamp.  You can make up...
["'''\n\\\"aabcaca\\\"\n 0123456\n x\n \ndevide conquer\n\u5148\u627e\u5230\u7b2c\u4e00\u4e2astamp\u628astring\u5206\u6210\u5de6\u53f3\u4e24\u90e8\u5206\uff08\u5fc5\u987b\u8981\uff09\uff08On\n\u7136\u540e\u4ece\u957f\u5230\u77ed\u7528stamp\u7684\u5934match\u5de6\u8fb9\u7684\u90e8\u5206\uff0c\u76f4\u5230match\u5230\u67...
interview
https://leetcode.com/problems/stamping-the-sequence/
class Solution: def movesToStamp(self, stamp: str, target: str) -> List[int]:
1,916
Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. Example 1: Input: [1,2,3] ...
["# Definition for a binary tree node.\n # class TreeNode:\n # def __init__(self, x):\n # self.val = x\n # self.left = None\n # self.right = None\n \n class Solution:\n \tdef currentmax(self,root):\n \t\tleftval = 0\n \t\tif root.left != None:\n \t\t\tleftval = self.currentmax(root.left)\n \...
interview
https://leetcode.com/problems/binary-tree-maximum-path-sum/
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxPathSum(self, root: TreeNode) -> int:
1,917
Given a chemical formula (given as a string), return the count of each atom. An atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name. 1 or more digits representing the count of that element may follow if the count is greater than 1. If the count is 1, n...
["class Solution(object):\n loc=0\n lastloc=-1\n f=''\n def getNext(self,formular,locked=False):\n stype=0 # 0:null, 1:numeric, 2/20: Elem, 3: parenthesis\n ret=0\n if self.loc==self.lastloc: return (0,0)\n i=self.loc\n while i <len(formular):\n if sty...
interview
https://leetcode.com/problems/number-of-atoms/
class Solution: def countOfAtoms(self, formula: str) -> str:
1,918
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. Note: If there are multiple valid itineraries, you should return the itinerar...
["from collections import defaultdict\n \n class Solution:\n def findItinerary(self, tickets):\n \"\"\"\n :type tickets: List[List[str]]\n :rtype: List[str]\n \"\"\"\n \n graph = defaultdict(list)\n for from_, to_ in tickets:\n graph[from_].append(...
interview
https://leetcode.com/problems/reconstruct-itinerary/
class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]:
1,919
There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should t...
["class Solution:\n def findOrder(self, numCourses, prerequisites):\n \"\"\"\n :type numCourses: int\n :type prerequisites: List[List[int]]\n :rtype: List[int]\n \"\"\"\n n = numCourses \n graph = {}\n for post, pre in prerequisites:\n if ...
interview
https://leetcode.com/problems/course-schedule-ii/
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
1,920
Create a timebased key-value store class TimeMap, that supports two operations. 1. set(string key, string value, int timestamp) Stores the key and value, along with the given timestamp. 2. get(string key, int timestamp) Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_p...
["class TimeMap:\n\n def __init__(self):\n \\\"\\\"\\\"\n Initialize your data structure here.\n \\\"\\\"\\\"\n self.store = {}\n self.times = {}\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n if key not in self.store: \n self.store[key] = [...
interview
https://leetcode.com/problems/time-based-key-value-store/
class TimeMap: def __init__(self): """ Initialize your data structure here. """ def set(self, key: str, value: str, timestamp: int) -> None: def get(self, key: str, timestamp: int) -> str: # Your TimeMap object will be instantiated and called as such: # obj = TimeMap() # obj.set(key...
1,921
You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity. Implement the DinnerPlates class: DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks. void push(int val) Pushes the given positive intege...
["from heapq import heapify, heappush, heappop \nclass DinnerPlates:\n # index * cap -> access start of stack at index\n # index * cap + (cap - 1) -> access last element of stack at index\n \n def __init__(self, capacity: int):\n self.stack = [] # just one array to simulate all the stac...
interview
https://leetcode.com/problems/dinner-plate-stacks/
class DinnerPlates: def __init__(self, capacity: int): def push(self, val: int) -> None: def pop(self) -> int: def popAtStack(self, index: int) -> int: # Your DinnerPlates object will be instantiated and called as such: # obj = DinnerPlates(capacity) # obj.push(val) # param_2 = obj.pop() # param_3 = ob...
1,922
Given a binary tree, we install cameras on the nodes of the tree.  Each camera at a node can monitor its parent, itself, and its immediate children. Calculate the minimum number of cameras needed to monitor all nodes of the tree.   Example 1: Input: [0,0,null,0,0] Output: 1 Explanation: One camera is enough to monito...
["# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def minCameraCover(self, root: TreeNode) -> int:\n \n def dfs(node):\n if ...
interview
https://leetcode.com/problems/binary-tree-cameras/
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def minCameraCover(self, root: TreeNode) -> int:
1,923
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]. Example: Input: [5,2,6,1] Output: [2,1,1,0] Explanation: To the right of 5 there are 2 smaller elements (2 and 1). To the right ...
["class Solution:\n def countSmaller(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n s = sorted(nums)\n c = []\n for n in nums:\n p = bisect.bisect_left(s, n)\n c.append(p)\n s.pop(p)\n r...
interview
https://leetcode.com/problems/count-of-smaller-numbers-after-self/
class Solution: def countSmaller(self, nums: List[int]) -> List[int]:
1,924
A transaction is possibly invalid if: the amount exceeds $1000, or; if it occurs within (and including) 60 minutes of another transaction with the same name in a different city. Each transaction string transactions[i] consists of comma separated values representing the name, time (in minutes), amount, and city of the...
["class Transaction:\n def __init__(self, name, time, amount, city):\n self.name = name\n self.time = int(time)\n self.amount = int(amount)\n self.city = city\n \n def array(self):\n return f\\\"{self.name},{self.time},{self.amount},{self.city}\\\"\n\nfrom collections imp...
interview
https://leetcode.com/problems/invalid-transactions/
class Solution: def invalidTransactions(self, transactions: List[str]) -> List[str]:
1,925
Return the root node of a binary search tree that matches the given preorder traversal. (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val.  Also recall that a preorder traversal displays th...
["# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def bstFromPreorder(self, preorder: List[int]) -> TreeNode:\n # time O(n); space O(n)\n ...
interview
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
1,926
Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2. Return the two integers in any order.   Example 1: Input: num = 8 Output: [3,3] Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 ...
["import collections\nimport itertools\n\n\ndef prime_factors(n):\n i = 2\n while i * i <= n:\n if n % i == 0:\n n /= i\n yield i\n else:\n i += 1\n\n if n > 1:\n yield n\n\n\ndef prod(iterable):\n result = 1\n for i in iterable:\n result *= i\...
interview
https://leetcode.com/problems/closest-divisors/
class Solution: def closestDivisors(self, num: int) -> List[int]:
1,927
We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collision...
["class Solution:\n def asteroidCollision(self, asteroids):\n \"\"\"\n :type asteroids: List[int]\n :rtype: List[int]\n \"\"\"\n l=len(asteroids)\n if l<2:\n return asteroids\n ans=[]\n stack=[]\n for a in asteroids:\n i...
interview
https://leetcode.com/problems/asteroid-collision/
class Solution: def asteroidCollision(self, asteroids: List[int]) -> List[int]:
1,928
Given a nested list of integers represented as a string, implement a parser to deserialize it. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Note: You may assume that the string is well-formed: String is non-empty. String does not contain white spaces. String con...
["# \"\"\"\n # This is the interface that allows for creating nested lists.\n # You should not implement it, or speculate about its implementation\n # \"\"\"\n #class NestedInteger:\n # def __init__(self, value=None):\n # \"\"\"\n # If value is not specified, initializes an empty list.\n # Other...
interview
https://leetcode.com/problems/mini-parser/
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger: # def __init__(self, value=None): # """ # If value is not specified, initializes an empty list. # Otherwise initializes a single ...
1,929
Implement the StreamChecker class as follows: StreamChecker(words): Constructor, init the data structure with the given words. query(letter): returns true if and only if for some k >= 1, the last k characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the giv...
["class StreamChecker:\n\n def __init__(self, words: List[str]):\n #reverse trie\n self.trie = {}\n self.stream = deque([])\n\n for word in set(words):\n node = self.trie \n for ch in word[::-1]:\n if not ch in node:\n node[ch]...
interview
https://leetcode.com/problems/stream-of-characters/
class StreamChecker: def __init__(self, words: List[str]): def query(self, letter: str) -> bool: # Your StreamChecker object will be instantiated and called as such: # obj = StreamChecker(words) # param_1 = obj.query(letter)
1,930
There is a sale in a supermarket, there will be a discount every n customer. There are some products in the supermarket where the id of the i-th product is products[i] and the price per unit of this product is prices[i]. The system will count the number of customers and when the n-th customer arrive he/she will have a ...
["class Cashier:\n\n def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):\n \n self.n = n\n self.count = 0\n self.discount = discount\n self.products = {}\n \n for i in range(0, len(products)):\n \n self.products[pro...
interview
https://leetcode.com/problems/apply-discount-every-n-orders/
class Cashier: def __init__(self, n: int, discount: int, products: List[int], prices: List[int]): def getBill(self, product: List[int], amount: List[int]) -> float: # Your Cashier object will be instantiated and called as such: # obj = Cashier(n, discount, products, prices) # param_1 = obj.getBill(product,amou...
1,931
Given a binary tree root and a linked list with head as the first node.  Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes downwards....
["class Solution(object):\n def isSubPath(self, h, r0):\n h_vals = []\n while h:\n h_vals.append(str(h.val))\n h = h.next\n h_str = ('-'.join(h_vals)) + '-' # serialized list\n\n st = [(r0, '-')] # DFS stack\n\n while st:\n r, pre = st.pop()\n ...
interview
https://leetcode.com/problems/linked-list-in-binary-tree/
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution...
1,932
Two players play a turn based game on a binary tree.  We are given the root of this binary tree, and the number of nodes n in the tree.  n is odd, and each node has a distinct value from 1 to n. Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y !=...
["# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:\n def count(node):\n...
interview
https://leetcode.com/problems/binary-tree-coloring-game/
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:
1,933
Given two strings representing two complex numbers. You need to return a string representing their multiplication. Note i2 = -1 according to the definition. Example 1: Input: "1+1i", "1+1i" Output: "0+2i" Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. Example ...
["class Solution:\n def complexNumberMultiply(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n a = a.split('+')\n b = b.split('+')\n a[1] = a[1][:-1]\n b[1] = b[1][:-1]\n a = list(map(int, a))\n b = l...
interview
https://leetcode.com/problems/complex-number-multiplication/
class Solution: def complexNumberMultiply(self, a: str, b: str) -> str:
1,934
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ ...
["# Definition for a binary tree node.\n # class TreeNode:\n # def __init__(self, x):\n # self.val = x\n # self.left = None\n # self.right = None\n \n class Solution:\n def zigzagLevelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n ...
interview
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
1,935
In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform...
["class Solution:\n def isToeplitzMatrix(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: bool\n \"\"\"\n if not matrix:\n return False\n colSize = len(matrix[0]) - 1\n for row in range(len(matrix) - 1):\n if matrix[row...
interview
https://leetcode.com/problems/swap-adjacent-in-lr-string/
class Solution: def canTransform(self, start: str, end: str) -> bool:
1,936
In an infinite binary tree where every node has two children, the nodes are labelled in row order. In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. Given the label of a node in this ...
["class Solution:\n def pathInZigZagTree(self, label: int) -> List[int]:\n res = []\n level = 0\n nodes_count = 0\n while nodes_count < label:\n nodes_count += 2**level\n level += 1\n while label != 0:\n res.append(label)\n level_max = (2...
interview
https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/
class Solution: def pathInZigZagTree(self, label: int) -> List[int]:
1,937
A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born. The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a per...
["class ThroneInheritance:\n\n def __init__(self, kingName: str):\n self.graph = collections.defaultdict(list)\n self.deaths = set()\n self.root = kingName\n \n\n def birth(self, parentName: str, childName: str) -> None:\n self.graph[parentName].append(childName)\n\n def deat...
interview
https://leetcode.com/problems/throne-inheritance/
class ThroneInheritance: def __init__(self, kingName: str): def birth(self, parentName: str, childName: str) -> None: def death(self, name: str) -> None: def getInheritanceOrder(self) -> List[str]: # Your ThroneInheritance object will be instantiated and called as such: # obj = ThroneInheritance(kingNa...
1,938
We are given a list of (axis-aligned) rectangles.  Each rectangle[i] = [x1, y1, x2, y2] , where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the ith rectangle. Find the total area covered by all rectangles in the plane.  Since the answer may be too ...
["class Solution:\n def rectangleArea(self, rectangles: List[List[int]]) -> int:\n \n def getArea(width):\n res = 0\n prev_low = 0\n for low, high in intervals:\n low = max(prev_low, low)\n if high > low:\n res += (high -...
interview
https://leetcode.com/problems/rectangle-area-ii/
class Solution: def rectangleArea(self, rectangles: List[List[int]]) -> int:
1,939
Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word. For a given query word, the spell checker handles two categories of spelling mistakes: Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case...
["class Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n original = set(wordlist)\n insensitive = {w.lower(): w for w in reversed(wordlist)}\n vowels = {}\n for c in reversed(wordlist):\n w = c.lower()\n t = w.replace('a', '...
interview
https://leetcode.com/problems/vowel-spellchecker/
class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:
1,940
We are given a linked list with head as the first node.  Let's number the nodes in the list: node_1, node_2, node_3, ... etc. Each node may have a next larger value: for node_i, next_larger(node_i) is the node_j.val such that j > i, node_j.val > node_i.val, and j is the smallest possible choice.  If such a j does not e...
["# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nextLargerNodes(self, head: ListNode) -> List[int]:\n if head==None:\n return 0\n temp=head\n arr=[]\n ...
interview
https://leetcode.com/problems/next-greater-node-in-linked-list/
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def nextLargerNodes(self, head: ListNode) -> List[int]:
1,941
With respect to a given puzzle string, a word is valid if both the following conditions are satisfied: word contains the first letter of puzzle. For each letter in word, that letter is in puzzle. For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", and "baggage"; while invalid word...
["class Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n # 1st step\n # construct a mask for each word\n # note that there may be duplicate mask for different words\n # so we need a dict to count the number\n orda = ord('a') # 97\n ...
interview
https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/
class Solution: def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:
1,942
Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0). Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.   Example 1: Input...
["class Solution:\n def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:\n result = []\n fcSet = [set(fc) for fc in favoriteCompanies]\n n = len(favoriteCompanies)\n for i, fcs1 in enumerate(fcSet):\n for j, fcs2 in enumerate(fcSet):\n if i==...
interview
https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/
class Solution: def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
1,943
Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order. Return the intersection of these two interval lists. (Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b.  The intersection of two closed intervals is a set of real numb...
["class Solution:\n def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n result = []\n i = j = 0\n \n while i < len(A) and j < len(B):\n low = max(A[i][0], B[j][0])\n high = min(A[i][1], B[j][1])\n \n if l...
interview
https://leetcode.com/problems/interval-list-intersections/
class Solution: def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
1,944
Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient. If there is no solution for the equation, return "No solution". If there are infinite solutions for the equation, return "Infinite solutions". If t...
["class Solution:\n def calc(self, part):\n part += \"+\" ## added tmp symbol in the end to sum last item within the loop\n start = x = n = 0\n coeff = 1\n for end, char in enumerate(part):\n # print(\"charIdx:\", equation[end], \"char: \", char, char == \"+\" or char == ...
interview
https://leetcode.com/problems/solve-the-equation/
class Solution: def solveEquation(self, equation: str) -> str:
1,945
Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column.  Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0. Return the maximum number of rows that have all values equal after some number of flips.   Example 1: Input: [[0,1]...
["class Solution:\n def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:\n dict_ = {}\n for row in matrix:\n curr_tuple = tuple(row)\n dict_[curr_tuple] = 1 + dict_.get(curr_tuple,0)\n visited = set()\n max_same = 0\n for row in matrix:\n ...
interview
https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/
class Solution: def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
1,946
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user's news feed. Your design should support the following methods: postTweet(userId, tweetId): Compose a new tweet. getNewsFeed(userId): Retrieve the 10 most recent tw...
["from collections import defaultdict, deque\n from heapq import merge\n from itertools import islice\n \n class Twitter:\n \n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.id2tweets = defaultdict(deque)\n self.id2follows = defaultdict(se...
interview
https://leetcode.com/problems/design-twitter/
class Twitter: def __init__(self): """ Initialize your data structure here. """ def postTweet(self, userId: int, tweetId: int) -> None: """ Compose a new tweet. """ def getNewsFeed(self, userId: int) -> List[int]: """ Retrieve the 10 most rece...
1,947
We are given two arrays A and B of words.  Each word is a string of lowercase letters. Now, say that word b is a subset of word a if every letter in b occurs in a, including multiplicity.  For example, "wrr" is a subset of "warrior", but is not a subset of "world". Now say a word a from A is universal if for every b in...
["class Solution:\n def wordSubsets(self, A: List[str], B: List[str]) -> List[str]:\n s = set(A)\n letters_required = {}\n for i in B:\n for j in i:\n count = i.count(j)\n if j not in letters_required or count > letters_required[j]:\n l...
interview
https://leetcode.com/problems/word-subsets/
class Solution: def wordSubsets(self, A: List[str], B: List[str]) -> List[str]:
1,948
You have a very large square wall and a circular dartboard placed on the wall. You have been challenged to throw darts into the board blindfolded. Darts thrown at the wall are represented as an array of points on a 2D plane.  Return the maximum number of points that are within or lie on any circular dartboard of radius...
["class Solution:\n def numPoints(self, points: List[List[int]], r: int) -> int:\n ans = 1\n for x, y in points: \n angles = []\n for x1, y1 in points: \n if (x1 != x or y1 != y) and (d:=sqrt((x1-x)**2 + (y1-y)**2)) <= 2*r: \n angle = atan2(y1-y, ...
interview
https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/
class Solution: def numPoints(self, points: List[List[int]], r: int) -> int:
1,949
In a gold mine grid of size m * 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 you will collect all the gold in that cell. From your position you can wa...
["class Solution:\n def getMaximumGold(self, grid: List[List[int]]) -> int:\n \n height = len(grid)\n width = len(grid[0])\n max_path = 0\n \n # generator for legal indices to check\n def index_gen(index):\n i,j = index\n if i > 0 and grid[i-1][j...
interview
https://leetcode.com/problems/path-with-maximum-gold/
class Solution: def getMaximumGold(self, grid: List[List[int]]) -> int:
1,950
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Example 1: Input: 1->2->3->3->4->4->5 Output: 1->2->5 Example 2: Input: 1->1->1->2->3 Output: 2->3
["# Definition for singly-linked list.\n # class ListNode:\n # def __init__(self, x):\n # self.val = x\n # self.next = None\n \n class Solution:\n def deleteDuplicates(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if not head o...
interview
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode:
1,951
We are given the root node of a maximum tree: a tree where every node has a value greater than any other value in its subtree. Just as in the previous problem, the given tree was constructed from an list A (root = Construct(A)) recursively with the following Construct(A) routine: If A is empty, return null. Otherwise,...
["# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode:\n if root and root.val > ...
interview
https://leetcode.com/problems/maximum-binary-tree-ii/
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode:
1,952
Reverse a linked list from position m to n. Do it in one-pass. Note: 1 ≤ m ≤ n ≤ length of list. Example: Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
["class Solution:\n def reverseBetween(self, head, m, n):\n \"\"\"\n :type head: ListNode\n :type m: int\n :type n: int\n :rtype: ListNode\n \"\"\"\n if head is None or head.__next__ is None or m == n: return head\n h = ListNode(-1)\n h.next = ...
interview
https://leetcode.com/problems/reverse-linked-list-ii/
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
1,953
Given a linked list, remove the n-th node from the end of list and return its head. Example: Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Follow up: Could you do this in one pass?
["# Definition for singly-linked list.\n # class ListNode:\n # def __init__(self, x):\n # self.val = x\n # self.next = None\n \n class Solution:\n # @return a ListNode\n def removeNthFromEnd(self, head, n):\n dummy=ListNode(0); dummy.next=head\n p1=p2=dummy\n for i in...
interview
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
1,954
In a project, you have a list of required skills req_skills, and a list of people.  The i-th person people[i] contains a list of skills that person has. Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill.  We can repr...
["class Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n \n\n def fulfill_skills(skills, person):\n remaining_skills = deque()\n for skill in skills:\n if skill not in people[person]:\n r...
interview
https://leetcode.com/problems/smallest-sufficient-team/
class Solution: def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:
1,955
You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times. Return the lexicographically smallest string that s can be changed to after usin...
["class Solution:\n def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:\n pr=[i for i in range(len(s))]\n def union(x,y):\n p1=find(x)\n p2=find(y)\n if p1!=p2:\n pr[p1]=p2\n def find(x):\n while pr[x]!=x:\n ...
interview
https://leetcode.com/problems/smallest-string-with-swaps/
class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
1,956
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row. Each of the digits 1-9 must occur exactly once in each column. Each of the the digits 1-9 must occur exactly...
["class Solution:\n def FindValid(self):\n a=\"123456789\"\n d,val={},{}\n for i in range(9):\n for j in range(9):\n temp=self.board[i][j]\n if temp!='.':\n d[(\"r\",i)]=d.get((\"r\",i),[])+[temp]\n d[(\"c\",...
interview
https://leetcode.com/problems/sudoku-solver/
class Solution: def solveSudoku(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """
1,957
Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In one step, you can move up, down, left or right from and to an empty cell. Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m-1, n-1) given that you can eliminate at most k obstacles. If it ...
["# O(M*N*K)\nclass Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n rows, cols = len(grid), len(grid[0])\n steps, min_steps = 0, rows + cols - 2\n if k >= min_steps - 1:\n return min_steps\n\n visited = [[-1] * cols for _ in range(rows)]\n vis...
interview
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/
class Solution: def shortestPath(self, grid: List[List[int]], k: int) -> int:
1,958
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 example, if groupSizes[1] = 3, then person 1 must be in a group of size 3. Retur...
["class Solution:\n def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:\n# mine\n# res = collections.defaultdict(list)\n# res_return = []\n# for i,j in enumerate(groupSizes):\n# res[j].append(i)\n \n# for j in res:\n# temp = [res[...
interview
https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/
class Solution: def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
1,959
We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.  Each glass holds one cup (250ml) of champagne. Then, some champagne is poured in the first glass at the top.  When the top most glass is full, any excess liquid poured will fall equally to the ...
["# Definition for a binary tree node.\n # class TreeNode:\n # def __init__(self, x):\n # self.val = x\n # self.left = None\n # self.right = None\n \n class Solution:\n def addValueToList(self, root, lst):\n if root is not None:\n lst.append(root.val)\n se...
interview
https://leetcode.com/problems/champagne-tower/
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
1,960
Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules: In the beginning, you have the permutation P=[1,2,3,...,m]. For the current i, find the position of queries[i] in the permutation P (indexing from 0) and t...
["class Solution:\n def processQueries(self, queries: List[int], m: int) -> List[int]:\n if not queries:\n return []\n p = list(range(1, m+1))\n res = []\n for i in queries:\n z = p.index(i)\n res.append(z)\n del p[z]\n p.insert(0,i)\...
interview
https://leetcode.com/problems/queries-on-a-permutation-with-key/
class Solution: def processQueries(self, queries: List[int], m: int) -> List[int]:
1,961
You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps. Implement the BrowserHistory class: BrowserHistory(string homepage) Initializes the object with the homepage of the browser. void visit(st...
["class BrowserHistory:\n\n def __init__(self, homepage: str):\n \n self.hashM = {}\n self.maxIndex, self.currIndex = 0, 0\n self.hashM[self.currIndex] = homepage\n\n def visit(self, url: str) -> None:\n \n self.hashM[self.currIndex + 1] = url\n self.currIndex = se...
interview
https://leetcode.com/problems/design-browser-history/
class BrowserHistory: def __init__(self, homepage: str): def visit(self, url: str) -> None: def back(self, steps: int) -> str: def forward(self, steps: int) -> str: # Your BrowserHistory object will be instantiated and called as such: # obj = BrowserHistory(homepage) # obj.visit(url) # param_2 = obj.ba...
1,962
Find the minimum length word from a given dictionary words, which has all the letters from the string licensePlate. Such a word is said to complete the given string licensePlate Here, for letters we ignore case. For example, "P" on the licensePlate still matches "p" on the word. It is guaranteed an answer exists. ...
["class Solution:\n def dominantIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) <= 1:\n return 0\n m = max(nums)\n ind = nums.index(m)\n del nums[ind]\n m_2 = max(nums)\n return ind ...
interview
https://leetcode.com/problems/shortest-completing-word/
class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
1,963
In LeetCode Store, there are some kinds of items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given the each item's price, a set of special offers, and the number we need to buy for each item...
["class Solution:\n def shoppingOffers(self, price, special, needs):\n \"\"\"\n :type price: List[int]\n :type special: List[List[int]]\n :type needs: List[int]\n :rtype: int\n \"\"\"\n def dfs(curr, special, needs):\n p=curr+sum(p*needs[i] for i,p...
interview
https://leetcode.com/problems/shopping-offers/
class Solution: def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int:
1,964
Print a binary tree in an m*n 2D string array following these rules: The row number m should be equal to the height of the given binary tree. The column number n should always be an odd number. The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The column and...
["def get_tree_height(node, parent_node_height):\n if node is None:\n return 0\n node.height = parent_node_height + 1\n if node.left is None and node.right is None:\n return 1\n return max(get_tree_height(node.left, node.height), get_tree_height(node.right, node.height)) + 1\n \n def fil...
interview
https://leetcode.com/problems/print-binary-tree/
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def printTree(self, root: TreeNode) -> List[List[str]]:
1,965
Alice and Bob have an undirected graph of n nodes and 3 types of edges: Type 1: Can be traversed by Alice only. Type 2: Can be traversed by Bob only. Type 3: Can by traversed by both Alice and Bob. Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and...
["class Solution:\n def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n if len(edges) == 0:\n return 0 if n == 0 else -1\n p = [i for i in range(n)]\n def getP(ind):\n nonlocal p\n if p[ind] == ind:\n return ind\n els...
interview
https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/
class Solution: def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:
1,966
Given a rows * columns matrix mat of ones and zeros, return how many submatrices have all ones.   Example 1: Input: mat = [[1,0,1],   [1,1,0],   [1,1,0]] Output: 13 Explanation: There are 6 rectangles of side 1x1. There are 2 rectangles of side 1x2. There are 3 rectangles of side 2x1. There is 1...
["class Solution:\n def numSubmat(self, mat: List[List[int]]) -> int:\n n, m = len(mat), len(mat[0])\n heights = [0] * m\n res = 0\n for i in range(0, n):\n stack = []\n count = 0\n for j in range(0, m):\n if mat[i][j] == 1:\n ...
interview
https://leetcode.com/problems/count-submatrices-with-all-ones/
class Solution: def numSubmat(self, mat: List[List[int]]) -> int:
1,967
Given a string S of digits, such as S = "123456579", we can split it into a Fibonacci-like sequence [123, 456, 579]. Formally, a Fibonacci-like sequence is a list F of non-negative integers such that: 0 <= F[i] <= 2^31 - 1, (that is, each integer fits a 32-bit signed integer type); F.length >= 3; and F[i] + F[i+1] = F...
["class Solution(object):\n def splitIntoFibonacci(self, S):\n \\\"\\\"\\\"\n :type S: str\n :rtype: List[int]\n \\\"\\\"\\\"\n n = len(S)\n for i in range(1, 11):\n for j in range(1, 11):\n if i + j >= n:\n break\n ...
interview
https://leetcode.com/problems/split-array-into-fibonacci-sequence/
class Solution: def splitIntoFibonacci(self, S: str) -> List[int]:
1,968
Given a list of folders, remove all sub-folders in those folders and return in any order the folders after removing. If a folder[i] is located within another folder[j], it is called a sub-folder of it. The format of a path is one or more concatenated strings of the form: / followed by one or more lowercase English lett...
["class Solution:\n def removeSubfolders(self, folder):\n \n folders = folder\n \n folders.sort()\n output = []\n parent = ' '\n \n for folder in folders:\n if not folder.startswith(parent):\n output.append(folder)\n parent = folder...
interview
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/
class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]:
1,969
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. Note: A leaf is a node with no children. Example: Input: [1,2,3] 1 / \ 2 3 O...
["# Definition for a binary tree node.\n # class TreeNode:\n # def __init__(self, x):\n # self.val = x\n # self.left = None\n # self.right = None\n \n class Solution:\n def sumNumbers(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n ...
interview
https://leetcode.com/problems/sum-root-to-leaf-numbers/
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def sumNumbers(self, root: TreeNode) -> int:
1,970
Given an integer n, find the closest integer (not including itself), which is a palindrome. The 'closest' is defined as absolute difference minimized between two integers. Example 1: Input: "123" Output: "121" Note: The input n is a positive integer represented by string, whose length will not exceed 18. If the...
["class Solution:\n def nearestPalindromic(self, num):\n \"\"\"\n :type n: str\n :rtype: str\n \"\"\"\n K = len(num)\n candidates = set([10**K + 1, 10**(K-1) - 1])\n Prefix = int(num[:(K+1)//2])\n \n for start in map(str, [Prefix-1, Prefix, Prefix+1]):...
interview
https://leetcode.com/problems/find-the-closest-palindrome/
class Solution: def nearestPalindromic(self, n: str) -> str:
1,971
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. Example: Input: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 Output: 4
["class Solution:\n def maximalSquare(self, matrix):\n \"\"\"\n :type matrix: List[List[str]]\n :rtype: int\n \"\"\"\n if not matrix:\n return 0\n \n m, n = len(matrix), len(matrix[0])\n dp = [int(matrix[i][0]) for i in range(m)]\n vmax = m...
interview
https://leetcode.com/problems/maximal-square/
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int:
1,972
S and T are strings composed of lowercase letters. In S, no letter occurs more than once. S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned strin...
["# Definition for a binary tree node.\n # class TreeNode:\n # def __init__(self, x):\n # self.val = x\n # self.left = None\n # self.right = None\n \n class Solution:\n def splitBST(self, root,target):\n \"\"\"\n :type root: TreeNode\n :type V: int\n :rtyp...
interview
https://leetcode.com/problems/custom-sort-string/
class Solution: def customSortString(self, S: str, T: str) -> str:
1,973
We have two types of tiles: a 2x1 domino shape, and an "L" tromino shape. These shapes may be rotated. XX <- domino XX <- "L" tromino X Given N, how many ways are there to tile a 2 x N board? Return your answer modulo 10^9 + 7. (In a tiling, every square must be covered by a tile. Two tilings are different if a...
["class Solution:\n def isIdealPermutation(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: bool\n \"\"\"\n # tle\n # for i in range(len(A)-2):\n # if A[i] > min(A[i+2:]):\n # return False\n # return True\n \n ...
interview
https://leetcode.com/problems/domino-and-tromino-tiling/
class Solution: def numTilings(self, N: int) -> int:
1,974
Given a binary tree, return the postorder traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [3,2,1] Follow up: Recursive solution is trivial, could you do it iteratively?
["# Definition for a binary tree node.\n # class TreeNode:\n # def __init__(self, x):\n # self.val = x\n # self.left = None\n # self.right = None\n \n class Solution:\n def postorderTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n ...
interview
https://leetcode.com/problems/binary-tree-postorder-traversal/
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]:
1,975
Design a stack which supports the following operations. Implement the CustomStack class: CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize. void push(int x) Adds x to the top of the stack if the stack hasn't ...
["class CustomStack:\n\n def __init__(self, maxSize: int):\n self.stack = []\n self.add = []\n self.limit = maxSize\n\n def push(self, x: int) -> None:\n if len(self.stack) < self.limit:\n self.stack.append(x)\n self.add.append(0)\n\n def pop(self) -> int:\n ...
interview
https://leetcode.com/problems/design-a-stack-with-increment-operation/
class CustomStack: def __init__(self, maxSize: int): def push(self, x: int) -> None: def pop(self) -> int: def increment(self, k: int, val: int) -> None: # Your CustomStack object will be instantiated and called as such: # obj = CustomStack(maxSize) # obj.push(x) # param_2 = obj.pop() # obj.increment(k...
1,976
Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary. For the method search, you'll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified wor...
["class MagicDictionary:\n \n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.l = []\n \n def buildDict(self, dict):\n \"\"\"\n Build a dictionary through a list of words\n :type dict: List[str]\n :rtype: void\n ...
interview
https://leetcode.com/problems/implement-magic-dictionary/
class MagicDictionary: def __init__(self): """ Initialize your data structure here. """ def buildDict(self, dictionary: List[str]) -> None: def search(self, searchWord: str) -> bool: # Your MagicDictionary object will be instantiated and called as such: # obj = MagicDictionary() # o...
1,977
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.   Example 1: Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1...
["class Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n count = 0 \n for i in range(1,len(grid)-1):\n for j in range(1,len(grid[0])-1):\n if grid[i][j] ==0 and self.dfs(grid,i,j):\n count+=1\n return count \n def dfs(self,grid,i...
interview
https://leetcode.com/problems/number-of-closed-islands/
class Solution: def closedIsland(self, grid: List[List[int]]) -> int:
1,978
You have a list of words and a pattern, and you want to know which words in words matches the pattern. A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word. (Recall that a permutation of letters is a bijection from...
["class Solution:\n def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n out = []\n for word in words:\n pat_dict = dict()\n used = set()\n if len(word) == len(pattern):\n can_be = True\n for i in range(len(word))...
interview
https://leetcode.com/problems/find-and-replace-pattern/
class Solution: def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
1,979
Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. Return the latest 24-hour time in "HH:MM" format. ...
["class Solution:\n def largestTimeFromDigits(self, A: List[int]) -> str:\n max_time = -1\n # enumerate all possibilities, with the permutation() func\n for h, i, j, k in itertools.permutations(A):\n hour = h*10 + i\n minute = j*10 + k\n if hour < 24 and minute <...
interview
https://leetcode.com/problems/largest-time-for-given-digits/
class Solution: def largestTimeFromDigits(self, arr: List[int]) -> str:
1,980
Design a Skiplist without using any built-in libraries. A Skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists are just si...
["class Skiplist:\n def __init__(self):\n self.skip_list={}\n \n\n def search(self, target: int) -> bool:\n if(target in self.skip_list):\n if(self.skip_list[target]>0):\n return True\n return False\n \n\n def add(self, num: int) -> None:\n if...
interview
https://leetcode.com/problems/design-skiplist/
class Skiplist: def __init__(self): def search(self, target: int) -> bool: def add(self, num: int) -> None: def erase(self, num: int) -> bool: # Your Skiplist object will be instantiated and called as such: # obj = Skiplist() # param_1 = obj.search(target) # obj.add(num) # param_3 = obj.erase(num)
1,981
We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed. Return the maximum total sum of all requests among all permutations of nums. Since...
["class Solution:\n def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:\n count = [0] * (len(nums) + 1)\n for start, end in requests:\n count[start] += 1\n count[end + 1] -= 1\n for i in range(1, len(nums) + 1):\n count[i] += count[i - 1]\n count.pop()\n\n res =...
interview
https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation/
class Solution: def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:
1,982
Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size. Each person may dislike some other people, and they should not go into the same group.  Formally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group. Retu...
["class Solution:\n def possibleBipartition(self, N: int, dislikes: List[List[int]]) -> bool:\n if not dislikes:\n return True\n group = [None] * (N + 1)\n group[dislikes[0][0]] = 1\n group[dislikes[0][1]] = -1\n group1 = set([1])\n group2 = set()\n counter...
interview
https://leetcode.com/problems/possible-bipartition/
class Solution: def possibleBipartition(self, N: int, dislikes: List[List[int]]) -> bool:
1,983
Implement the class ProductOfNumbers that supports two methods: 1. add(int num) Adds the number num to the back of the current list of numbers. 2. getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers. At any time, the pro...
["import math\nclass ProductOfNumbers:\n\n def __init__(self):\n self.numbers = [1]\n self.lastZero = 0\n\n def add(self, num: int) -> None:\n if num != 0:\n self.numbers.append(self.numbers[-1] * num)\n else:\n self.numbers = [1]\n \n\n def getProdu...
interview
https://leetcode.com/problems/product-of-the-last-k-numbers/
class ProductOfNumbers: def __init__(self): def add(self, num: int) -> None: def getProduct(self, k: int) -> int: # Your ProductOfNumbers object will be instantiated and called as such: # obj = ProductOfNumbers() # obj.add(num) # param_2 = obj.getProduct(k)
1,984
Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree: 3 / \ 9 20 / \ 15 7
["# Definition for a binary tree node.\n # class TreeNode:\n # def __init__(self, x):\n # self.val = x\n # self.left = None\n # self.right = None\n \n class Solution:\n def buildTree(self, preorder, inorder):\n \"\"\"\n :type preorder: List[int]\n :type inorder: L...
interview
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
1,985
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example: Consider the following matrix: [ [1, ...
["class Solution:\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n m = len(matrix)\n if m == 0:\n return False\n n = len(matrix[0])\n if n == 0:\n ...
interview
https://leetcode.com/problems/search-a-2d-matrix-ii/
class Solution: def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """
1,986
Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p[0] = start p[i] and p[i+1] differ by only one bit in their binary representation. p[0] and p[2^n -1] must also differ by only one bit in their binary representation.   Example 1: Input: n = 2, start = 3 Output: [3...
["class Solution:\n def circularPermutation(self, n: int, start: int) -> List[int]:\n res = [i ^ (i >> 1) for i in range(1 << n)]\n \n idx = res.index(start)\n return res[idx:] + res[:idx]", "class Solution:\n def circularPermutation(self, n: int, start: int) -> List[int]:\n ret...
interview
https://leetcode.com/problems/circular-permutation-in-binary-representation/
class Solution: def circularPermutation(self, n: int, start: int) -> List[int]:
1,987
We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like `'Z'`. For every block of color `C` we place not in the bottom row, we are placing it on top of a left block of color `A` and right block of color `B`. We are allowed to place the block there only if `(A, B, C)` is an...
["import heapq\n class Solution(object):\n def pourWater(self, heights, V, K):\n \"\"\"\n :type heights: List[int]\n :type V: int\n :type K: int\n :rtype: List[int]\n \"\"\"\n \n heap = []\n heapq.heappush(heap, (heights[K], -1, 0))\n l, r = K ...
interview
https://leetcode.com/problems/pyramid-transition-matrix/
class Solution: def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
1,988
Consider a directed graph, with nodes labelled 0, 1, ..., n-1.  In this graph, each edge is either red or blue, and there could be self-edges or parallel edges. Each [i, j] in red_edges denotes a red directed edge from node i to node j.  Similarly, each [i, j] in blue_edges denotes a blue directed edge from node i to n...
["class Solution:\n def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]:\n \n \n G = [[[], []] for i in range(n)]\n for i, j in red_edges: G[i][0].append(j)\n for i, j in blue_edges: G[i][1].append(j)\n res = [[0, ...
interview
https://leetcode.com/problems/shortest-path-with-alternating-colors/
class Solution: def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]:
1,989
Given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it palindrome. Return the length of the maximum length awesome substring of s.   Example 1: Input: s = "3242415" Output: 5 Explanation: "24241" is the longest awesome substring, we can form th...
["class Solution:\n def longestAwesome(self, s: str) -> int:\n cum = [0]\n firsts = {0: -1}\n lasts = {0: -1}\n for i, c in enumerate(s):\n cum.append(cum[-1] ^ (1 << (ord(c) - 48)))\n if cum[-1] not in firsts:\n firsts[cum[-1]] = i\n lasts[...
interview
https://leetcode.com/problems/find-longest-awesome-substring/
class Solution: def longestAwesome(self, s: str) -> int:
1,990
You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion. Given a set of pairs, find the length longest chain which can be formed. You ...
["class Solution:\n def findLongestChain(self, pairs):\n \"\"\"\n :type pairs: List[List[int]]\n :rtype: int\n \"\"\"\n pairs = sorted(pairs,key=lambda x:x[1])\n res = 1\n first = pairs[0]\n for i in pairs[1:]:\n if first[-1] < i[0]:\n ...
interview
https://leetcode.com/problems/maximum-length-of-pair-chain/
class Solution: def findLongestChain(self, pairs: List[List[int]]) -> int:
1,991
You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city i, you can pick any...
["class Solution:\n def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:\n n = len(locations)\n sloc = sorted([(x,i) for i,x in enumerate(locations)])\n froutes = [[0]*n for _ in range(fuel+1) ]\n st,fn = -1,-1\n for i in range(n):\n if...
interview
https://leetcode.com/problems/count-all-possible-routes/
class Solution: def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:
1,992
Design an Iterator class, which has: A constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments. A function next() that returns the next combination of length combinationLength in lexicographical order. A function hasNext() that returns True if...
["class CombinationIterator:\n def __init__(self, characters: str, combinationLength: int):\n self.nextCombIt = combinations(characters, combinationLength)\n self.nextComb = next(self.nextCombIt, None)\n\n def __next__(self) -> str:\n nextComb = self.nextComb\n self.nextComb = next(sel...
interview
https://leetcode.com/problems/iterator-for-combination/
class CombinationIterator: def __init__(self, characters: str, combinationLength: int): def next(self) -> str: def hasNext(self) -> bool: # Your CombinationIterator object will be instantiated and called as such: # obj = CombinationIterator(characters, combinationLength) # param_1 = obj.next() # param_2 = ...
1,993
Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th line of the source code. This represents the result of splitting the original source code string by the newline character \n. In C++, there are two types of comments, line comments, and block comments. The string...
["import re\n \n \n class Solution:\n def removeComments(self, source):\n \"\"\"\n :type source: List[str]\n :rtype: List[str]\n \"\"\"\n lines = re.sub('//.*|/\\*(.|\\n)*?\\*/', '', '\\n'.join(source)).split('\\n')\n return [line for line in lines if line]\n ...
interview
https://leetcode.com/problems/remove-comments/
class Solution: def removeComments(self, source: List[str]) -> List[str]:
1,994
We are given head, the head node of a linked list containing unique integer values. We are also given the list G, a subset of the values in the linked list. Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list. Example 1: Input: head: 0->1->2->3...
["# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def numComponents(self, head: ListNode, G: List[int]) -> int:\n s=set(G)\n prev_in=False\n c=0\n while head:\n ...
interview
https://leetcode.com/problems/linked-list-components/
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def numComponents(self, head: ListNode, G: List[int]) -> int:
1,995
You are driving a vehicle that has capacity empty seats initially available for passengers.  The vehicle only drives east (ie. it cannot turn around and drive west.) Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that mu...
["class Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n d = defaultdict(int)\n \n for a, b, c in trips:\n d[b] += a\n d[c] -= a\n \n k = 0\n for t in sorted(d.keys()):\n k += d[t]\n if k > capacit...
interview
https://leetcode.com/problems/car-pooling/
class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
1,996
In a directed graph, we start at some node and every turn, walk along a directed edge of the graph.  If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop. Now, say our starting node is eventually safe if and only if we must eventually walk to a terminal node.  More specifically, the...
["class Solution:\n def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:\n \\\"\\\"\\\"\n Just move along unvisited (-1) nodes and remark them as 0 on the queue while visiting others on the path and finish them as 1. If you meet them again on the queue while visiting (being 0) it means you...
interview
https://leetcode.com/problems/find-eventual-safe-states/
class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
1,997
Given a list of intervals, remove all intervals that are covered by another interval in the list. Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d. After doing so, return the number of remaining intervals.   Example 1: Input: intervals = [[1,4],[3,6],[2,8]] Output: 2 Explanation: Interval [3...
["class Solution:\n def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[0], -x[1]))\n \n prev_end = result = 0\n for _, end in intervals:\n if end > prev_end:\n result += 1; prev_end = end\n \n ...
interview
https://leetcode.com/problems/remove-covered-intervals/
class Solution: def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
1,998
There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w. Now given all the cities and fights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1. Exa...
["import collections\n \n solved_boards = {((1,2,3),(4,5,0)): 0}\n class Solution:\n def slidingPuzzle(self, board):\n \"\"\"\n :type board: List[List[int]]\n :rtype: int\n \"\"\"\n asked = tuple(tuple(row) for row in board)\n queue = collections.deque([((1,2,3),(4,5,...
interview
https://leetcode.com/problems/cheapest-flights-within-k-stops/
class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
1,999
Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. After doing so, return the head of the final linked list.  You may return any such answer.   (Note that in the examples below, all sequences are serializations of ListNode objects.) Exam...
["# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeZeroSumSublists(self, head: ListNode) -> ListNode:\n \n seen={}\n seen[0]=dummy=ListNode(0)\n dummy.nex...
interview
https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeZeroSumSublists(self, head: ListNode) -> ListNode: