task_id
stringlengths
3
79
prompt
stringlengths
255
3.9k
binary-tree-level-order-traversal
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrder(root: Optional[TreeNode]) -> List[List[int]]: """ Given the root of a binary tree, return the level order traversal of its nodes...
binary-tree-zigzag-level-order-traversal
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def zigzagLevelOrder(root: Optional[TreeNode]) -> List[List[int]]: """ Given the root of a binary tree, return the zigzag level order traversal...
maximum-depth-of-binary-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxDepth(root: Optional[TreeNode]) -> int: """ Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth...
construct-binary-tree-from-preorder-and-inorder-traversal
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: """ Given two integer arrays preorder and inorder where preorder ...
construct-binary-tree-from-inorder-and-postorder-traversal
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: """ Given two integer arrays inorder and postorder where inorder...
binary-tree-level-order-traversal-ii
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrderBottom(root: Optional[TreeNode]) -> List[List[int]]: """ Given the root of a binary tree, return the bottom-up level order traver...
convert-sorted-array-to-binary-search-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sortedArrayToBST(nums: List[int]) -> Optional[TreeNode]: """ Given an integer array nums where the elements are sorted in ascending order, ...
convert-sorted-list-to-binary-search-tree
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next # Definition for a binary tree node. # class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def so...
balanced-binary-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isBalanced(root: Optional[TreeNode]) -> bool: """ Given a binary tree, determine if it is height-balanced. Example 1: ...
minimum-depth-of-binary-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minDepth(root: Optional[TreeNode]) -> int: """ Given a binary tree, find its minimum depth. The minimum depth is the number of nodes al...
path-sum
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def hasPathSum(root: Optional[TreeNode], targetSum: int) -> bool: """ Given the root of a binary tree and an integer targetSum, return true if ...
path-sum-ii
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pathSum(root: Optional[TreeNode], targetSum: int) -> List[List[int]]: """ Given the root of a binary tree and an integer targetSum, return ...
flatten-binary-tree-to-linked-list
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def flatten(root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ """ Given ...
distinct-subsequences
def numDistinct(s: str, t: str) -> int: """ Given two strings s and t, return the number of distinct subsequences of s which equals t. The test cases are generated so that the answer fits on a 32-bit signed integer. Example 1: >>> numDistinct(s = "rabbbit", t = "rabbit") >>> 3 Expl...
pascals-triangle
def generate(numRows: int) -> List[List[int]]: """ Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: Example 1: >>> generate(numRows = 5) >>> [[1],[1,1],[1,2,1],[1,3,3,1],...
pascals-triangle-ii
def getRow(rowIndex: int) -> List[int]: """ Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: Example 1: >>> getRow(rowIndex = 3) >>> [1,3,3,1] Examp...
triangle
def minimumTotal(triangle: List[List[int]]) -> int: """ Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the ne...
best-time-to-buy-and-sell-stock
def maxProfit(prices: List[int]) -> int: """ You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you...
best-time-to-buy-and-sell-stock-ii
def maxProfit(prices: List[int]) -> int: """ You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately se...
best-time-to-buy-and-sell-stock-iii
def maxProfit(prices: List[int]) -> int: """ You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete at most two transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must se...
binary-tree-maximum-path-sum
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxPathSum(root: Optional[TreeNode]) -> int: """ A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the se...
valid-palindrome
def isPalindrome(s: str) -> bool: """ A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a...
word-ladder
def ladderLength(beginWord: str, endWord: str, wordList: List[str]) -> int: """ A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Eve...
longest-consecutive-sequence
def longestConsecutive(nums: List[int]) -> int: """ Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. Example 1: >>> longestConsecutive(nums = [100,4,200,1,3,2]) >>> 4 Explan...
sum-root-to-leaf-numbers
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sumNumbers(root: Optional[TreeNode]) -> int: """ You are given the root of a binary tree containing digits from 0 to 9 only. Each root-...
surrounded-regions
def solve(board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ """ You are given an m x n matrix board containing letters 'X' and 'O', capture regions that are surrounded: Connect: A cell is connected to adjacent cells horizontally or v...
palindrome-partitioning
def partition(s: str) -> List[List[str]]: """ Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Example 1: >>> partition(s = "aab") >>> [["a","a","b"],["aa","b"]] Example 2: >>> partition(s = "a") ...
palindrome-partitioning-ii
def minCut(s: str) -> int: """ Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. Example 1: >>> minCut(s = "aab") >>> 1 Explanation: The palindrome partitioning ["aa","b"] cou...
gas-station
def canCompleteCircuit(gas: List[int], cost: List[int]) -> int: """ There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You b...
candy
def candy(ratings: List[int]) -> int: """ There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a...
single-number
def singleNumber(nums: List[int]) -> int: """ Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. Example 1: >>> singleNumber(nums = [2,...
single-number-ii
def singleNumber(nums: List[int]) -> int: """ Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it. You must implement a solution with a linear runtime complexity and use only constant extra space. Exam...
word-break
def wordBreak(s: str, wordDict: List[str]) -> bool: """ Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation. ...
word-break-ii
def wordBreak(s: str, wordDict: List[str]) -> List[str]: """ Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order. Note that the same word in the dictionary may be reused mul...
linked-list-cycle
# class ListNode: # def __init__(x): # self.val = x # self.next = None class Solution: def hasCycle(head: Optional[ListNode]) -> bool: """ Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node i...
reorder-list
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def reorderList(head: Optional[ListNode]) -> None: """ Do not return anything, modify head in-place instead. """ """ You are given the head of a singly linked-l...
binary-tree-preorder-traversal
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def preorderTraversal(root: Optional[TreeNode]) -> List[int]: """ Given the root of a binary tree, return the preorder traversal of its nodes' ...
binary-tree-postorder-traversal
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def postorderTraversal(root: Optional[TreeNode]) -> List[int]: """ Given the root of a binary tree, return the postorder traversal of its nodes...
insertion-sort-list
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def insertionSortList(head: Optional[ListNode]) -> Optional[ListNode]: """ Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head...
sort-list
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def sortList(head: Optional[ListNode]) -> Optional[ListNode]: """ Given the head of a linked list, return the list after sorting it in ascending order. Example 1: ...
max-points-on-a-line
def maxPoints(points: List[List[int]]) -> int: """ Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line. Example 1: >>> maxPoints(points = [[1,1],[2,2],[3,3]]) >>> 3 Exa...
evaluate-reverse-polish-notation
def evalRPN(tokens: List[str]) -> int: """ You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation. Evaluate the expression. Return an integer that represents the value of the expression. Note that: The valid operators are '+', '-', '*', an...
reverse-words-in-a-string
def reverseWords(s: str) -> str: """ Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may...
maximum-product-subarray
def maxProduct(nums: List[int]) -> int: """ Given an integer array nums, find a subarray that has the largest product, and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. Example 1: >>> maxProduct(nums = [2,3,-2,4]) >>> 6 Explanatio...
find-minimum-in-rotated-sorted-array
def findMin(nums: List[int]) -> int: """ Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: [4,5,6,7,0,1,2] if it was rotated 4 times. [0,1,2,4,5,6,7] if it was rotated 7 times. Notice that ro...
find-minimum-in-rotated-sorted-array-ii
def findMin(nums: List[int]) -> int: """ Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become: [4,5,6,7,0,1,4] if it was rotated 4 times. [0,1,4,4,5,6,7] if it was rotated 7 times. Notice that ro...
binary-tree-upside-down
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def upsideDownBinaryTree(root: Optional[TreeNode]) -> Optional[TreeNode]: """ Given the root of a binary tree, turn the tree upside down and re...
longest-substring-with-at-most-two-distinct-characters
def lengthOfLongestSubstringTwoDistinct(s: str) -> int: """ Given a string s, return the length of the longest substring that contains at most two distinct characters. Example 1: >>> lengthOfLongestSubstringTwoDistinct(s = "eceba") >>> 3 Explanation: The substring is "ece" which its le...
intersection-of-two-linked-lists
# class ListNode: # def __init__(x): # self.val = x # self.next = None class Solution: def getIntersectionNode(headA: ListNode, headB: ListNode) -> Optional[ListNode]: """ Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If th...
one-edit-distance
def isOneEditDistance(s: str, t: str) -> bool: """ Given two strings s and t, return true if they are both one edit distance apart, otherwise return false. A string s is said to be one distance apart from a string t if you can: Insert exactly one character into s to get t. Delete exactly one ch...
find-peak-element
def findPeakElement(nums: List[int]) -> int: """ A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that num...
missing-ranges
def findMissingRanges(nums: List[int], lower: int, upper: int) -> List[List[int]]: """ You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are within the inclusive range. A number x is considered missing if x is in the range [lower, upper] and x is not ...
maximum-gap
def maximumGap(nums: List[int]) -> int: """ Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0. You must write an algorithm that runs in linear time and uses linear extra space. Exampl...
compare-version-numbers
def compareVersion(version1: str, version2: str) -> int: """ Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots '.'. The value of the revision is its integer conversion ignoring leading zeros. To compare version strings, compare their rev...
fraction-to-recurring-decimal
def fractionToDecimal(numerator: int, denominator: int) -> str: """ Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. If multiple answers are possible, return ...
two-sum-ii-input-array-is-sorted
def twoSum(numbers: List[int], target: int) -> List[int]: """ Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <=...
excel-sheet-column-title
def convertToTitle(columnNumber: int) -> str: """ Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... Example 1: >>> convertToTitl...
majority-element
def majorityElement(nums: List[int]) -> int: """ Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. Example 1: >>> majorityElement(nums = [3,2,...
excel-sheet-column-number
def titleToNumber(columnTitle: str) -> int: """ Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... Example 1: ...
factorial-trailing-zeroes
def trailingZeroes(n: int) -> int: """ Given an integer n, return the number of trailing zeroes in n!. Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1. Example 1: >>> trailingZeroes(n = 3) >>> 0 Explanation: 3! = 6, no trailing zero. Example 2: >>> trailing...
dungeon-game
def calculateMinimumHP(dungeon: List[List[int]]) -> int: """ The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through...
largest-number
def largestNumber(nums: List[int]) -> str: """ Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. Example 1: >>> largestNumber(nums = [10,2]...
reverse-words-in-a-string-ii
def reverseWords(s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ """ Given a character array s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by a single space. Your code...
repeated-dna-sequences
def findRepeatedDnaSequences(s: str) -> List[str]: """ The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'. For example, "ACGAATTCCG" is a DNA sequence. When studying DNA, it is useful to identify repeated sequences within the DNA. Given a string s...
best-time-to-buy-and-sell-stock-iv
def maxProfit(k: int, prices: List[int]) -> int: """ You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k. Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k tim...
rotate-array
def rotate(nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ """ Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. Example 1: >>> rotate(nums = [1,2,3,4,5,6,7], k = 3) >>> [5...
reverse-bits
def reverseBits(n: int) -> int: """ Reverse bits of a given 32 bits unsigned integer. Note: Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the in...
number-of-1-bits
def hammingWeight(n: int) -> int: """ Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight). Example 1: >>> hammingWeight(n = 11) >>> 3 Explanation: The input binary string 1011 has a total o...
house-robber
def rob(nums: List[int]) -> int: """ You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the pol...
binary-tree-right-side-view
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rightSideView(root: Optional[TreeNode]) -> List[int]: """ Given the root of a binary tree, imagine yourself standing on the right side of i...
number-of-islands
def numIslands(grid: List[List[str]]) -> int: """ Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of ...
bitwise-and-of-numbers-range
def rangeBitwiseAnd(left: int, right: int) -> int: """ Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive. Example 1: >>> rangeBitwiseAnd(left = 5, right = 7) >>> 4 Example 2: >>> rangeB...
happy-number
def isHappy(n: int) -> bool: """ Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits. Repeat the process until the number equals 1 (whe...
remove-linked-list-elements
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def removeElements(head: Optional[ListNode], val: int) -> Optional[ListNode]: """ Given the head of a linked list and an integer val, remove all the nodes of the linked list that has N...
count-primes
def countPrimes(n: int) -> int: """ Given an integer n, return the number of prime numbers that are strictly less than n. Example 1: >>> countPrimes(n = 10) >>> 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. Example 2: >>> countPrimes(n = ...
isomorphic-strings
def isIsomorphic(s: str, t: str) -> bool: """ Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. ...
reverse-linked-list
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(head: Optional[ListNode]) -> Optional[ListNode]: """ Given the head of a singly linked list, reverse the list, and return the reversed list. Example 1: ...
course-schedule
def canFinish(numCourses: int, prerequisites: List[List[int]]) -> bool: """ There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course a...
minimum-size-subarray-sum
def minSubArrayLen(target: int, nums: List[int]) -> int: """ Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead. Example 1: >>> minSubArrayL...
course-schedule-ii
def findOrder(numCourses: int, prerequisites: List[List[int]]) -> List[int]: """ There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take cou...
word-search-ii
def findWords(board: List[List[str]], words: List[str]) -> List[str]: """ Given an m x n board of characters and a list of strings words, return all words on the board. Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring....
house-robber-ii
def rob(nums: List[int]) -> int: """ You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security sy...
shortest-palindrome
def shortestPalindrome(s: str) -> str: """ You are given a string s. You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation. Example 1: >>> shortestPalindrome(s = "aacecaaa") >>> "aaacecaaa" Ex...
kth-largest-element-in-an-array
def findKthLargest(nums: List[int], k: int) -> int: """ Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Can you solve it without sorting? Example 1: >>> find...
combination-sum-iii
def combinationSum3(k: int, n: int) -> List[List[int]]: """ Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Only numbers 1 through 9 are used. Each number is used at most once. Return a list of all possible valid combinations. The list...
contains-duplicate
def containsDuplicate(nums: List[int]) -> bool: """ Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. Example 1: >>> containsDuplicate(nums = [1,2,3,1]) >>> true Explanation: The element 1 occur...
the-skyline-problem
def getSkyline(buildings: List[List[int]]) -> List[List[int]]: """ A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively. Th...
contains-duplicate-ii
def containsNearbyDuplicate(nums: List[int], k: int) -> bool: """ Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k. Example 1: >>> containsNearbyDuplicate(nums = [1,2,3,1], k = 3) ...
contains-duplicate-iii
def containsNearbyAlmostDuplicate(nums: List[int], indexDiff: int, valueDiff: int) -> bool: """ You are given an integer array nums and two integers indexDiff and valueDiff. Find a pair of indices (i, j) such that: i != j, abs(i - j) <= indexDiff. abs(nums[i] - nums[j]) <= valueDiff, and ...
maximal-square
def maximalSquare(matrix: List[List[str]]) -> int: """ Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. Example 1: >>> maximalSquare(matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","...
count-complete-tree-nodes
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def countNodes(root: Optional[TreeNode]) -> int: """ Given the root of a complete binary tree, return the number of the nodes in the tree. ...
rectangle-area
def computeArea(ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int: """ Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles. The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-...
basic-calculator
def calculate(s: str) -> int: """ Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). Examp...
invert-binary-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def invertTree(root: Optional[TreeNode]) -> Optional[TreeNode]: """ Given the root of a binary tree, invert the tree, and return its root. ...
basic-calculator-ii
def calculate(s: str) -> int: """ Given a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. ...
summary-ranges
def summaryRanges(nums: List[int]) -> List[str]: """ You are given a sorted unique integer array nums. A range [a,b] is the set of all integers from a to b (inclusive). Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by ...
majority-element-ii
def majorityElement(nums: List[int]) -> List[int]: """ Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. Example 1: >>> majorityElement(nums = [3,2,3]) >>> [3] Example 2: >>> majorityElement(nums = [1]) >>> [1] Example 3...
kth-smallest-element-in-a-bst
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def kthSmallest(root: Optional[TreeNode], k: int) -> int: """ Given the root of a binary search tree, and an integer k, return the kth smallest...
power-of-two
def isPowerOfTwo(n: int) -> bool: """ Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2x. Example 1: >>> isPowerOfTwo(n = 1) >>> true Explanation: 20 = 1 Example 2...
number-of-digit-one
def countDigitOne(n: int) -> int: """ Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. Example 1: >>> countDigitOne(n = 13) >>> 6 Example 2: >>> countDigitOne(n = 0) >>> 0 """