algospaced-dsa / algospaced-ui /src /data /neetcode150Data.ts
iamfebin's picture
feat: better sandbox test runner evaluation and LeetCode parsing support
88c96ae
Raw History Blame Contribute Delete
191 kB
// Canonical 150 LeetCode / NeetCode DSA Review Dataset // Pre-seeded with rich descriptions, examples, constraints, starter code, and reference solutions. // Zero-cold-start, instant O(1) offline and guest-mode support. export interface CatalogExample { input: string; output: string; explanation?: string; } export interface CatalogProblem { id: string; problem_number: number; name: string; pattern: string; difficulty: 'Easy' | 'Medium' | 'Hard'; time_complexity: string; space_complexity: string; starter_code: string; description: string; examples: CatalogExample[]; constraints: string[]; leetcode_url: string; reference_solution?: string; } export const NEETCODE_150_DATA: CatalogProblem[] = [ { "id": "nc-217", "problem_number": 217, "name": "Contains Duplicate", "pattern": "Arrays & Hashing", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def containsDuplicate(self, nums: list[int]) -> bool:\n pass", "description": "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.", "examples": [ { "input": "nums = [1,2,3,1]", "output": "true" }, { "input": "nums = [1,2,3,4]", "output": "false" } ], "constraints": [ "1 <= nums.length <= 10^5", "-10^9 <= nums[i] <= 10^9" ], "leetcode_url": "https://leetcode.com/problems/contains-duplicate/", "reference_solution": "class Solution:\n def containsDuplicate(self, nums: list[int]) -> bool:\n seen = set()\n for n in nums:\n if n in seen:\n return True\n seen.add(n)\n return False" }, { "id": "nc-242", "problem_number": 242, "name": "Valid Anagram", "pattern": "Arrays & Hashing", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n pass", "description": "Given two strings s and t, return true if t is an anagram of s, and false otherwise.", "examples": [ { "input": "s = \"anagram\", t = \"nagaram\"", "output": "true" }, { "input": "s = \"rat\", t = \"car\"", "output": "false" } ], "constraints": [ "1 <= s.length, t.length <= 5 * 10^4", "s and t consist of lowercase English letters." ], "leetcode_url": "https://leetcode.com/problems/valid-anagram/", "reference_solution": "class Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n if len(s) != len(t):\n return False\n counts = {}\n for char in s:\n counts[char] = counts.get(char, 0) + 1\n for char in t:\n if char not in counts or counts[char] == 0:\n return False\n counts[char] -= 1\n return True" }, { "id": "nc-1", "problem_number": 1, "name": "Two Sum", "pattern": "Arrays & Hashing", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def twoSum(self, nums: list[int], target: int) -> list[int]:\n pass", "description": "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.", "examples": [ { "input": "nums = [2,7,11,15], target = 9", "output": "[0,1]" } ], "constraints": [ "2 <= nums.length <= 10^4", "-10^9 <= nums[i] <= 10^9", "Exactly one solution exists." ], "leetcode_url": "https://leetcode.com/problems/two-sum/", "reference_solution": "class Solution:\n def twoSum(self, nums: list[int], target: int) -> list[int]:\n prev = {}\n for i, n in enumerate(nums):\n diff = target - n\n if diff in prev:\n return [prev[diff], i]\n prev[n] = i\n return []" }, { "id": "nc-49", "problem_number": 49, "name": "Group Anagrams", "pattern": "Arrays & Hashing", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(M * N)", "starter_code": "class Solution:\n def groupAnagrams(self, strs: list[str]) -> list[list[str]]:\n pass", "description": "Given an array of strings strs, group the anagrams together. You can return the answer in any order.", "examples": [ { "input": "strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]", "output": "[[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]" } ], "constraints": [ "1 <= strs.length <= 10^4", "0 <= strs[i].length <= 100" ], "leetcode_url": "https://leetcode.com/problems/group-anagrams/", "reference_solution": "from collections import defaultdict\n\nclass Solution:\n def groupAnagrams(self, strs: list[str]) -> list[list[str]]:\n res = defaultdict(list)\n for s in strs:\n count = [0] * 26\n for c in s:\n count[ord(c) - ord('a')] += 1\n res[tuple(count)].append(s)\n return list(res.values())" }, { "id": "nc-347", "problem_number": 347, "name": "Top K Frequent Elements", "pattern": "Arrays & Hashing", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def topKFrequent(self, nums: list[int], k: int) -> list[int]:\n pass", "description": "Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.", "examples": [ { "input": "nums = [1,1,1,2,2,3], k = 2", "output": "[1,2]" } ], "constraints": [ "1 <= nums.length <= 10^5", "1 <= k <= unique elements count" ], "leetcode_url": "https://leetcode.com/problems/top-k-frequent-elements/", "reference_solution": "class Solution:\n def topKFrequent(self, nums: list[int], k: int) -> list[int]:\n count = {}\n freq = [[] for _ in range(len(nums) + 1)]\n for n in nums:\n count[n] = 1 + count.get(n, 0)\n for n, c in count.items():\n freq[c].append(n)\n res = []\n for i in range(len(freq) - 1, 0, -1):\n for n in freq[i]:\n res.append(n)\n if len(res) == k:\n return res\n return res" }, { "id": "nc-271", "problem_number": 271, "name": "Encode and Decode Strings", "pattern": "Arrays & Hashing", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Codec:\n def encode(self, strs: list[str]) -> str:\n pass\n def decode(self, s: str) -> list[str]:\n pass", "description": "Design an algorithm to encode a list of strings to a single string and decode it back.", "examples": [ { "input": "dummy_input = [\"lint\",\"code\",\"love\",\"you\"]", "output": "[\"lint\",\"code\",\"love\",\"you\"]" } ], "constraints": [ "1 <= strs.length <= 200" ], "leetcode_url": "https://leetcode.com/problems/encode-and-decode-strings/", "reference_solution": "class Codec:\n def encode(self, strs: list[str]) -> str:\n res = \"\"\n for s in strs:\n res += str(len(s)) + \"#\" + s\n return res\n\n def decode(self, s: str) -> list[str]:\n res, i = [], 0\n while i < len(s):\n j = i\n while s[j] != \"#\":\n j += 1\n length = int(s[i:j])\n res.append(s[j + 1 : j + 1 + length])\n i = j + 1 + length\n return res" }, { "id": "nc-238", "problem_number": 238, "name": "Product of Array Except Self", "pattern": "Arrays & Hashing", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def productExceptSelf(self, nums: list[int]) -> list[int]:\n pass", "description": "Given an integer array nums, return an array answer such that answer[i] is equal to the product of all elements except nums[i]. Without division in O(n).", "examples": [ { "input": "nums = [1,2,3,4]", "output": "[24,12,8,6]" } ], "constraints": [ "2 <= nums.length <= 10^5", "-30 <= nums[i] <= 30" ], "leetcode_url": "https://leetcode.com/problems/product-of-array-except-self/", "reference_solution": "class Solution:\n def productExceptSelf(self, nums: list[int]) -> list[int]:\n res = [1] * len(nums)\n prefix = 1\n for i in range(len(nums)):\n res[i] = prefix\n prefix *= nums[i]\n postfix = 1\n for i in range(len(nums) - 1, -1, -1):\n res[i] *= postfix\n postfix *= nums[i]\n return res" }, { "id": "nc-36", "problem_number": 36, "name": "Valid Sudoku", "pattern": "Arrays & Hashing", "difficulty": "Medium", "time_complexity": "O(1)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def isValidSudoku(self, board: list[list[str]]) -> bool:\n pass", "description": "Determine if a 9 x 9 Sudoku board is valid according to Sudoku rules.", "examples": [ { "input": "board = [[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"],[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",.\"],[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",.\"],[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"],[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"],[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"],[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",.\"],[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"],[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]", "output": "true" } ], "constraints": [ "board is 9x9", "digits 1-9 or '.'" ], "leetcode_url": "https://leetcode.com/problems/valid-sudoku/", "reference_solution": "from collections import defaultdict\n\nclass Solution:\n def isValidSudoku(self, board: list[list[str]]) -> bool:\n cols = defaultdict(set)\n rows = defaultdict(set)\n squares = defaultdict(set)\n for r in range(9):\n for c in range(9):\n if board[r][c] == \".\":\n continue\n val = board[r][c]\n if val in rows[r] or val in cols[c] or val in squares[(r // 3, c // 3)]:\n return False\n cols[c].add(val)\n rows[r].add(val)\n squares[(r // 3, c // 3)].add(val)\n return True" }, { "id": "nc-128", "problem_number": 128, "name": "Longest Consecutive Sequence", "pattern": "Arrays & Hashing", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def longestConsecutive(self, nums: list[int]) -> int:\n pass", "description": "Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence in O(n) time.", "examples": [ { "input": "nums = [100,4,200,1,3,2]", "output": "4" } ], "constraints": [ "0 <= nums.length <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/longest-consecutive-sequence/", "reference_solution": "class Solution:\n def longestConsecutive(self, nums: list[int]) -> int:\n numSet = set(nums)\n longest = 0\n for n in numSet:\n if (n - 1) not in numSet:\n length = 1\n while (n + length) in numSet:\n length += 1\n longest = max(longest, length)\n return longest" }, { "id": "nc-125", "problem_number": 125, "name": "Valid Palindrome", "pattern": "Two Pointers", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def isPalindrome(self, s: str) -> bool:\n pass", "description": "Check if a string is a palindrome considering only alphanumeric characters and ignoring cases.", "examples": [ { "input": "s = \"A man, a plan, a canal: Panama\"", "output": "true" } ], "constraints": [ "1 <= s.length <= 2 * 10^5" ], "leetcode_url": "https://leetcode.com/problems/valid-palindrome/", "reference_solution": "class Solution:\n def isPalindrome(self, s: str) -> bool:\n l, r = 0, len(s) - 1\n while l < r:\n while l < r and not s[l].isalnum():\n l += 1\n while l < r and not s[r].isalnum():\n r -= 1\n if s[l].lower() != s[r].lower():\n return False\n l += 1\n r -= 1\n return True" }, { "id": "nc-167", "problem_number": 167, "name": "Two Sum II - Input Array Is Sorted", "pattern": "Two Pointers", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def twoSum(self, numbers: list[int], target: int) -> list[int]:\n pass", "description": "Given a 1-indexed sorted array numbers, find two numbers that add up to target.", "examples": [ { "input": "numbers = [2,7,11,15], target = 9", "output": "[1,2]" } ], "constraints": [ "2 <= numbers.length <= 3 * 10^4" ], "leetcode_url": "https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/", "reference_solution": "class Solution:\n def twoSum(self, numbers: list[int], target: int) -> list[int]:\n l, r = 0, len(numbers) - 1\n while l < r:\n cur = numbers[l] + numbers[r]\n if cur > target:\n r -= 1\n elif cur < target:\n l += 1\n else:\n return [l + 1, r + 1]\n return []" }, { "id": "nc-15", "problem_number": 15, "name": "3Sum", "pattern": "Two Pointers", "difficulty": "Medium", "time_complexity": "O(N^2)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def threeSum(self, nums: list[int]) -> list[list[int]]:\n pass", "description": "Find all unique triplets in nums that sum to 0.", "examples": [ { "input": "nums = [-1,0,1,2,-1,-4]", "output": "[[-1,-1,2],[-1,0,1]]" } ], "constraints": [ "3 <= nums.length <= 3000" ], "leetcode_url": "https://leetcode.com/problems/3sum/", "reference_solution": "class Solution:\n def threeSum(self, nums: list[int]) -> list[list[int]]:\n res = []\n nums.sort()\n for i, a in enumerate(nums):\n if a > 0:\n break\n if i > 0 and a == nums[i - 1]:\n continue\n l, r = i + 1, len(nums) - 1\n while l < r:\n threeSum = a + nums[l] + nums[r]\n if threeSum > 0:\n r -= 1\n elif threeSum < 0:\n l += 1\n else:\n res.append([a, nums[l], nums[r]])\n l += 1\n r -= 1\n while nums[l] == nums[l - 1] and l < r:\n l += 1\n return res" }, { "id": "nc-11", "problem_number": 11, "name": "Container With Most Water", "pattern": "Two Pointers", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def maxArea(self, height: list[int]) -> int:\n pass", "description": "Find two lines that together with the x-axis form a container storing the most water.", "examples": [ { "input": "height = [1,8,6,2,5,4,8,3,7]", "output": "49" } ], "constraints": [ "2 <= height.length <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/container-with-most-water/", "reference_solution": "class Solution:\n def maxArea(self, height: list[int]) -> int:\n l, r = 0, len(height) - 1\n res = 0\n while l < r:\n res = max(res, min(height[l], height[r]) * (r - l))\n if height[l] <= height[r]:\n l += 1\n else:\n r -= 1\n return res" }, { "id": "nc-42", "problem_number": 42, "name": "Trapping Rain Water", "pattern": "Two Pointers", "difficulty": "Hard", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def trap(self, height: list[int]) -> int:\n pass", "description": "Compute how much water an elevation map can trap after raining.", "examples": [ { "input": "height = [0,1,0,2,1,0,1,3,2,1,2,1]", "output": "6" } ], "constraints": [ "1 <= height.length <= 2 * 10^4" ], "leetcode_url": "https://leetcode.com/problems/trapping-rain-water/", "reference_solution": "class Solution:\n def trap(self, height: list[int]) -> int:\n if not height:\n return 0\n l, r = 0, len(height) - 1\n leftMax, rightMax = height[l], height[r]\n res = 0\n while l < r:\n if leftMax < rightMax:\n l += 1\n leftMax = max(leftMax, height[l])\n res += leftMax - height[l]\n else:\n r -= 1\n rightMax = max(rightMax, height[r])\n res += rightMax - height[r]\n return res" }, { "id": "nc-121", "problem_number": 121, "name": "Best Time to Buy and Sell Stock", "pattern": "Sliding Window", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def maxProfit(self, prices: list[int]) -> int:\n pass", "description": "Maximize profit by choosing a single day to buy one stock and choosing a different day in the future to sell it.", "examples": [ { "input": "prices = [7,1,5,3,6,4]", "output": "5" } ], "constraints": [ "1 <= prices.length <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock/", "reference_solution": "class Solution:\n def maxProfit(self, prices: list[int]) -> int:\n l, r = 0, 1\n maxP = 0\n while r < len(prices):\n if prices[l] < prices[r]:\n maxP = max(maxP, prices[r] - prices[l])\n else:\n l = r\n r += 1\n return maxP" }, { "id": "nc-3", "problem_number": 3, "name": "Longest Substring Without Repeating Characters", "pattern": "Sliding Window", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n pass", "description": "Find the length of the longest substring without duplicate characters.", "examples": [ { "input": "s = \"abcabcbb\"", "output": "3" } ], "constraints": [ "0 <= s.length <= 5 * 10^4" ], "leetcode_url": "https://leetcode.com/problems/longest-substring-without-repeating-characters/", "reference_solution": "class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n charSet = set()\n l, res = 0, 0\n for r in range(len(s)):\n while s[r] in charSet:\n charSet.remove(s[l])\n l += 1\n charSet.add(s[r])\n res = max(res, r - l + 1)\n return res" }, { "id": "nc-424", "problem_number": 424, "name": "Longest Repeating Character Replacement", "pattern": "Sliding Window", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n pass", "description": "Choose at most k characters and replace them with any other uppercase character to get the longest substring containing the same letter.", "examples": [ { "input": "s = \"ABAB\", k = 2", "output": "4" } ], "constraints": [ "1 <= s.length <= 10^5", "0 <= k <= s.length" ], "leetcode_url": "https://leetcode.com/problems/longest-repeating-character-replacement/", "reference_solution": "class Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n count = {}\n res = l = maxf = 0\n for r in range(len(s)):\n count[s[r]] = 1 + count.get(s[r], 0)\n maxf = max(maxf, count[s[r]])\n while (r - l + 1) - maxf > k:\n count[s[l]] -= 1\n l += 1\n res = max(res, r - l + 1)\n return res" }, { "id": "nc-567", "problem_number": 567, "name": "Permutation in String", "pattern": "Sliding Window", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n pass", "description": "Return true if s2 contains a permutation of s1, or false otherwise.", "examples": [ { "input": "s1 = \"ab\", s2 = \"eidbaooo\"", "output": "true" } ], "constraints": [ "1 <= s1.length, s2.length <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/permutation-in-string/", "reference_solution": "class Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n if len(s1) > len(s2):\n return False\n s1C, s2C = [0] * 26, [0] * 26\n for i in range(len(s1)):\n s1C[ord(s1[i]) - ord('a')] += 1\n s2C[ord(s2[i]) - ord('a')] += 1\n matches = sum(1 for i in range(26) if s1C[i] == s2C[i])\n l = 0\n for r in range(len(s1), len(s2)):\n if matches == 26:\n return True\n idx = ord(s2[r]) - ord('a')\n s2C[idx] += 1\n if s1C[idx] == s2C[idx]: matches += 1\n elif s1C[idx] + 1 == s2C[idx]: matches -= 1\n idx = ord(s2[l]) - ord('a')\n s2C[idx] -= 1\n if s1C[idx] == s2C[idx]: matches += 1\n elif s1C[idx] - 1 == s2C[idx]: matches -= 1\n l += 1\n return matches == 26" }, { "id": "nc-76", "problem_number": 76, "name": "Minimum Window Substring", "pattern": "Sliding Window", "difficulty": "Hard", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def minWindow(self, s: str, t: str) -> str:\n pass", "description": "Given two strings s and t, return the minimum window substring of s such that every character in t is included in the window.", "examples": [ { "input": "s = \"ADOBECODEBANC\", t = \"ABC\"", "output": "\"BANC\"" } ], "constraints": [ "1 <= s.length, t.length <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/minimum-window-substring/", "reference_solution": "class Solution:\n def minWindow(self, s: str, t: str) -> str:\n if not t: return \"\"\n countT, window = {}, {}\n for c in t: countT[c] = 1 + countT.get(c, 0)\n have, need = 0, len(countT)\n res, resLen = [-1, -1], float('inf')\n l = 0\n for r in range(len(s)):\n c = s[r]\n window[c] = 1 + window.get(c, 0)\n if c in countT and window[c] == countT[c]: have += 1\n while have == need:\n if (r - l + 1) < resLen:\n res = [l, r]\n resLen = r - l + 1\n window[s[l]] -= 1\n if s[l] in countT and window[s[l]] < countT[s[l]]: have -= 1\n l += 1\n l, r = res\n return s[l:r+1] if resLen != float('inf') else \"\"" }, { "id": "nc-239", "problem_number": 239, "name": "Sliding Window Maximum", "pattern": "Sliding Window", "difficulty": "Hard", "time_complexity": "O(N)", "space_complexity": "O(K)", "starter_code": "class Solution:\n def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:\n pass", "description": "Return the max sliding window of size k moving from very left of array to very right.", "examples": [ { "input": "nums = [1,3,-1,-3,5,3,6,7], k = 3", "output": "[3,3,5,5,6,7]" } ], "constraints": [ "1 <= nums.length <= 10^5", "1 <= k <= nums.length" ], "leetcode_url": "https://leetcode.com/problems/sliding-window-maximum/", "reference_solution": "from collections import deque\n\nclass Solution:\n def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:\n output = []\n q = deque()\n l = r = 0\n while r < len(nums):\n while q and nums[q[-1]] < nums[r]:\n q.pop()\n q.append(r)\n if l > q[0]:\n q.popleft()\n if (r + 1) >= k:\n output.append(nums[q[0]])\n l += 1\n r += 1\n return output" }, { "id": "nc-20", "problem_number": 20, "name": "Valid Parentheses", "pattern": "Stack", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def isValid(self, s: str) -> bool:\n pass", "description": "Determine if the input string has valid matching brackets '()', '{}', '[]'.", "examples": [ { "input": "s = \"()[]{}\"", "output": "true" }, { "input": "s = \"(]\"", "output": "false" } ], "constraints": [ "1 <= s.length <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/valid-parentheses/", "reference_solution": "class Solution:\n def isValid(self, s: str) -> bool:\n Map = {\")\": \"(\", \"]\": \"[\", \"}\": \"{\"}\n stack = []\n for c in s:\n if c not in Map:\n stack.append(c)\n continue\n if not stack or stack[-1] != Map[c]:\n return False\n stack.pop()\n return not stack" }, { "id": "nc-155", "problem_number": 155, "name": "Min Stack", "pattern": "Stack", "difficulty": "Medium", "time_complexity": "O(1)", "space_complexity": "O(N)", "starter_code": "class MinStack:\n def __init__(self):\n pass\n def push(self, val: int) -> None:\n pass\n def pop(self) -> None:\n pass\n def top(self) -> int:\n pass\n def getMin(self) -> int:\n pass", "description": "Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.", "examples": [ { "input": "[\"MinStack\",\"push\",\"push\",\"push\",\"getMin\",\"pop\",\"top\",\"getMin\"]", "output": "[null,null,null,null,-3,null,0,-2]" } ], "constraints": [ "Methods push, pop, top and getMin are called." ], "leetcode_url": "https://leetcode.com/problems/min-stack/", "reference_solution": "class MinStack:\n def __init__(self):\n self.stack = []\n self.minStack = []\n def push(self, val: int) -> None:\n self.stack.append(val)\n val = min(val, self.minStack[-1] if self.minStack else val)\n self.minStack.append(val)\n def pop(self) -> None:\n self.stack.pop()\n self.minStack.pop()\n def top(self) -> int:\n return self.stack[-1]\n def getMin(self) -> int:\n return self.minStack[-1]" }, { "id": "nc-150", "problem_number": 150, "name": "Evaluate Reverse Polish Notation", "pattern": "Stack", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def evalRPN(self, tokens: list[str]) -> int:\n pass", "description": "Evaluate the value of an arithmetic expression in Reverse Polish Notation.", "examples": [ { "input": "tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]", "output": "9" } ], "constraints": [ "1 <= tokens.length <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/evaluate-reverse-polish-notation/", "reference_solution": "class Solution:\n def evalRPN(self, tokens: list[str]) -> int:\n stack = []\n for c in tokens:\n if c == \"+\":\n stack.append(stack.pop() + stack.pop())\n elif c == \"-\":\n a, b = stack.pop(), stack.pop()\n stack.append(b - a)\n elif c == \"*\":\n stack.append(stack.pop() * stack.pop())\n elif c == \"/\":\n a, b = stack.pop(), stack.pop()\n stack.append(int(float(b) / a))\n else:\n stack.append(int(c))\n return stack[0]" }, { "id": "nc-739", "problem_number": 739, "name": "Daily Temperatures", "pattern": "Stack", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def dailyTemperatures(self, temperatures: list[int]) -> list[int]:\n pass", "description": "Given daily temperatures, return an array answer where answer[i] is the days you have to wait after ith day to get warmer temperature.", "examples": [ { "input": "temperatures = [73,74,75,71,69,72,76,73]", "output": "[1,1,4,2,1,1,0,0]" } ], "constraints": [ "1 <= temperatures.length <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/daily-temperatures/", "reference_solution": "class Solution:\n def dailyTemperatures(self, temperatures: list[int]) -> list[int]:\n res = [0] * len(temperatures)\n stack = []\n for i, t in enumerate(temperatures):\n while stack and t > stack[-1][0]:\n stackT, stackInd = stack.pop()\n res[stackInd] = i - stackInd\n stack.append((t, i))\n return res" }, { "id": "nc-853", "problem_number": 853, "name": "Car Fleet", "pattern": "Stack", "difficulty": "Medium", "time_complexity": "O(N log N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def carFleet(self, target: int, position: list[int], speed: list[int]) -> int:\n pass", "description": "Calculate how many car fleets will arrive at destination target position.", "examples": [ { "input": "target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]", "output": "3" } ], "constraints": [ "n == position.length == speed.length" ], "leetcode_url": "https://leetcode.com/problems/car-fleet/", "reference_solution": "class Solution:\n def carFleet(self, target: int, position: list[int], speed: list[int]) -> int:\n pair = [(p, s) for p, s in zip(position, speed)]\n pair.sort(reverse=True)\n stack = []\n for p, s in pair:\n stack.append((target - p) / s)\n if len(stack) >= 2 and stack[-1] <= stack[-2]:\n stack.pop()\n return len(stack)" }, { "id": "nc-84", "problem_number": 84, "name": "Largest Rectangle in Histogram", "pattern": "Stack", "difficulty": "Hard", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def largestRectangleArea(self, heights: list[int]) -> int:\n pass", "description": "Given an array of integers heights representing bar heights, return area of the largest rectangle in histogram.", "examples": [ { "input": "heights = [2,1,5,6,2,3]", "output": "10" } ], "constraints": [ "1 <= heights.length <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/largest-rectangle-in-histogram/", "reference_solution": "class Solution:\n def largestRectangleArea(self, heights: list[int]) -> int:\n maxArea = 0\n stack = []\n for i, h in enumerate(heights):\n start = i\n while stack and stack[-1][1] > h:\n index, height = stack.pop()\n maxArea = max(maxArea, height * (i - index))\n start = index\n stack.append((start, h))\n for i, h in stack:\n maxArea = max(maxArea, h * (len(heights) - i))\n return maxArea" }, { "id": "nc-704", "problem_number": 704, "name": "Binary Search", "pattern": "Binary Search", "difficulty": "Easy", "time_complexity": "O(log N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def search(self, nums: list[int], target: int) -> int:\n pass", "description": "Given an array of integers nums which is sorted in ascending order, search target in nums in O(log n) runtime.", "examples": [ { "input": "nums = [-1,0,3,5,9,12], target = 9", "output": "4" } ], "constraints": [ "1 <= nums.length <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/binary-search/", "reference_solution": "class Solution:\n def search(self, nums: list[int], target: int) -> int:\n l, r = 0, len(nums) - 1\n while l <= r:\n m = l + ((r - l) // 2)\n if nums[m] > target:\n r = m - 1\n elif nums[m] < target:\n l = m + 1\n else:\n return m\n return -1" }, { "id": "nc-74", "problem_number": 74, "name": "Search a 2D Matrix", "pattern": "Binary Search", "difficulty": "Medium", "time_complexity": "O(log(M * N))", "space_complexity": "O(1)", "starter_code": "class Solution:\n def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:\n pass", "description": "Write an efficient algorithm that searches for a value target in an m x n integer matrix with sorted rows.", "examples": [ { "input": "matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3", "output": "true" } ], "constraints": [ "m == matrix.length", "n == matrix[i].length" ], "leetcode_url": "https://leetcode.com/problems/search-a-2d-matrix/", "reference_solution": "class Solution:\n def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:\n ROWS, COLS = len(matrix), len(matrix[0])\n top, bot = 0, ROWS - 1\n while top <= bot:\n row = (top + bot) // 2\n if target > matrix[row][-1]:\n top = row + 1\n elif target < matrix[row][0]:\n bot = row - 1\n else:\n break\n if not (top <= bot):\n return False\n row = (top + bot) // 2\n l, r = 0, COLS - 1\n while l <= r:\n m = (l + r) // 2\n if target > matrix[row][m]:\n l = m + 1\n elif target < matrix[row][m]:\n r = m - 1\n else:\n return True\n return False" }, { "id": "nc-875", "problem_number": 875, "name": "Koko Eating Bananas", "pattern": "Binary Search", "difficulty": "Medium", "time_complexity": "O(N log(max(P)))", "space_complexity": "O(1)", "starter_code": "class Solution:\n def minEatingSpeed(self, piles: list[int], h: int) -> int:\n pass", "description": "Return the minimum integer k such that Koko can eat all bananas within h hours.", "examples": [ { "input": "piles = [3,6,7,11], h = 8", "output": "4" } ], "constraints": [ "1 <= piles.length <= 10^4", "piles.length <= h <= 10^9" ], "leetcode_url": "https://leetcode.com/problems/koko-eating-bananas/", "reference_solution": "import math\n\nclass Solution:\n def minEatingSpeed(self, piles: list[int], h: int) -> int:\n l, r = 1, max(piles)\n res = r\n while l <= r:\n k = (l + r) // 2\n totalTime = sum(math.ceil(p / k) for p in piles)\n if totalTime <= h:\n res = k\n r = k - 1\n else:\n l = k + 1\n return res" }, { "id": "nc-153", "problem_number": 153, "name": "Find Minimum in Rotated Sorted Array", "pattern": "Binary Search", "difficulty": "Medium", "time_complexity": "O(log N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def findMin(self, nums: list[int]) -> int:\n pass", "description": "Given the sorted rotated array nums of unique elements, return the minimum element in O(log n).", "examples": [ { "input": "nums = [3,4,5,1,2]", "output": "1" } ], "constraints": [ "n == nums.length", "1 <= n <= 5000" ], "leetcode_url": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/", "reference_solution": "class Solution:\n def findMin(self, nums: list[int]) -> int:\n res = nums[0]\n l, r = 0, len(nums) - 1\n while l <= r:\n if nums[l] < nums[r]:\n res = min(res, nums[l])\n break\n m = (l + r) // 2\n res = min(res, nums[m])\n if nums[m] >= nums[l]:\n l = m + 1\n else:\n r = m - 1\n return res" }, { "id": "nc-33", "problem_number": 33, "name": "Search in Rotated Sorted Array", "pattern": "Binary Search", "difficulty": "Medium", "time_complexity": "O(log N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def search(self, nums: list[int], target: int) -> int:\n pass", "description": "Given rotated sorted array nums with unique values and target, return index of target or -1 in O(log n).", "examples": [ { "input": "nums = [4,5,6,7,0,1,2], target = 0", "output": "4" } ], "constraints": [ "1 <= nums.length <= 5000" ], "leetcode_url": "https://leetcode.com/problems/search-in-rotated-sorted-array/", "reference_solution": "class Solution:\n def search(self, nums: list[int], target: int) -> int:\n l, r = 0, len(nums) - 1\n while l <= r:\n mid = (l + r) // 2\n if target == nums[mid]: return mid\n if nums[l] <= nums[mid]:\n if target > nums[mid] or target < nums[l]: l = mid + 1\n else: r = mid - 1\n else:\n if target < nums[mid] or target > nums[r]: r = mid - 1\n else: l = mid + 1\n return -1" }, { "id": "nc-981", "problem_number": 981, "name": "Time Based Key-Value Store", "pattern": "Binary Search", "difficulty": "Medium", "time_complexity": "O(log N)", "space_complexity": "O(N)", "starter_code": "class TimeMap:\n def __init__(self):\n pass\n def set(self, key: str, value: str, timestamp: int) -> None:\n pass\n def get(self, key: str, timestamp: int) -> str:\n pass", "description": "Design a time-based key-value data structure that can store multiple values for the same key at different time stamps.", "examples": [ { "input": "[\"TimeMap\",\"set\",\"get\",\"get\",\"set\",\"get\",\"get\"]", "output": "[null,null,\"bar\",\"bar\",null,\"bar2\",\"bar2\"]" } ], "constraints": [ "1 <= key.length, value.length <= 100" ], "leetcode_url": "https://leetcode.com/problems/time-based-key-value-store/", "reference_solution": "class TimeMap:\n def __init__(self):\n self.keyStore = {}\n def set(self, key: str, value: str, timestamp: int) -> None:\n if key not in self.keyStore: self.keyStore[key] = []\n self.keyStore[key].append([value, timestamp])\n def get(self, key: str, timestamp: int) -> str:\n res, values = \"\", self.keyStore.get(key, [])\n l, r = 0, len(values) - 1\n while l <= r:\n m = (l + r) // 2\n if values[m][1] <= timestamp:\n res = values[m][0]\n l = m + 1\n else:\n r = m - 1\n return res" }, { "id": "nc-4", "problem_number": 4, "name": "Median of Two Sorted Arrays", "pattern": "Binary Search", "difficulty": "Hard", "time_complexity": "O(log(min(N, M)))", "space_complexity": "O(1)", "starter_code": "class Solution:\n def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float:\n pass", "description": "Given two sorted arrays nums1 and nums2, return median of two sorted arrays in O(log (m+n)).", "examples": [ { "input": "nums1 = [1,3], nums2 = [2]", "output": "2.00000" } ], "constraints": [ "nums1.length == m", "nums2.length == n" ], "leetcode_url": "https://leetcode.com/problems/median-of-two-sorted-arrays/", "reference_solution": "class Solution:\n def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float:\n A, B = nums1, nums2\n total = len(nums1) + len(nums2)\n half = total // 2\n if len(B) < len(A): A, B = B, A\n l, r = 0, len(A) - 1\n while True:\n i = (l + r) // 2\n j = half - i - 2\n Aleft = A[i] if i >= 0 else float(\"-infinity\")\n Aright = A[i + 1] if (i + 1) < len(A) else float(\"infinity\")\n Bleft = B[j] if j >= 0 else float(\"-infinity\")\n Bright = B[j + 1] if (j + 1) < len(B) else float(\"infinity\")\n if Aleft <= Bright and Bleft <= Aright:\n if total % 2:\n return min(Aright, Bright)\n return (max(Aleft, Bleft) + min(Aright, Bright)) / 2\n elif Aleft > Bright:\n r = i - 1\n else:\n l = i + 1" }, { "id": "nc-206", "problem_number": 206, "name": "Reverse Linked List", "pattern": "Linked List", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n pass", "description": "Given the head of a singly linked list, reverse the list, and return the reversed list.", "examples": [ { "input": "head = [1,2,3,4,5]", "output": "[5,4,3,2,1]" } ], "constraints": [ "The number of nodes in the list is in range [0, 5000]." ], "leetcode_url": "https://leetcode.com/problems/reverse-linked-list/", "reference_solution": "class Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n prev, curr = None, head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev" }, { "id": "nc-21", "problem_number": 21, "name": "Merge Two Sorted Lists", "pattern": "Linked List", "difficulty": "Easy", "time_complexity": "O(N + M)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n pass", "description": "Merge two sorted linked lists into one sorted list.", "examples": [ { "input": "list1 = [1,2,4], list2 = [1,3,4]", "output": "[1,1,2,3,4,4]" } ], "constraints": [ "Number of nodes in both lists is in range [0, 50]." ], "leetcode_url": "https://leetcode.com/problems/merge-two-sorted-lists/", "reference_solution": "class Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n dummy = node = ListNode()\n while list1 and list2:\n if list1.val < list2.val:\n node.next = list1\n list1 = list1.next\n else:\n node.next = list2\n list2 = list2.next\n node = node.next\n node.next = list1 or list2\n return dummy.next" }, { "id": "nc-141", "problem_number": 141, "name": "Linked List Cycle", "pattern": "Linked List", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n pass", "description": "Given head, return true if there is a cycle in the linked list.", "examples": [ { "input": "head = [3,2,0,-4], pos = 1", "output": "true" } ], "constraints": [ "The number of the nodes in the list is in range [0, 10^4]." ], "leetcode_url": "https://leetcode.com/problems/linked-list-cycle/", "reference_solution": "class Solution:\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n return True\n return False" }, { "id": "nc-143", "problem_number": 143, "name": "Reorder List", "pattern": "Linked List", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n pass", "description": "Reorder the list to be on the following form: L0 \u2192 Ln \u2192 L1 \u2192 Ln - 1 \u2192 L2 \u2192 Ln - 2 \u2192 \u2026", "examples": [ { "input": "head = [1,2,3,4]", "output": "[1,4,2,3]" } ], "constraints": [ "Number of nodes in list is in range [1, 5 * 10^4]." ], "leetcode_url": "https://leetcode.com/problems/reorder-list/", "reference_solution": "class Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n slow, fast = head, head.next\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n second = slow.next\n prev = slow.next = None\n while second:\n tmp = second.next\n second.next = prev\n prev = second\n second = tmp\n first, second = head, prev\n while second:\n tmp1, tmp2 = first.next, second.next\n first.next = second\n second.next = tmp1\n first, second = tmp1, tmp2" }, { "id": "nc-19", "problem_number": 19, "name": "Remove Nth Node From End of List", "pattern": "Linked List", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n pass", "description": "Remove the nth node from the end of the list and return its head.", "examples": [ { "input": "head = [1,2,3,4,5], n = 2", "output": "[1,2,3,5]" } ], "constraints": [ "1 <= sz <= 30", "1 <= n <= sz" ], "leetcode_url": "https://leetcode.com/problems/remove-nth-node-from-end-of-list/", "reference_solution": "class Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n dummy = ListNode(0, head)\n left = dummy\n right = head\n while n > 0 and right:\n right = right.next\n n -= 1\n while right:\n left = left.next\n right = right.next\n left.next = left.next.next\n return dummy.next" }, { "id": "nc-138", "problem_number": 138, "name": "Copy List with Random Pointer", "pattern": "Linked List", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':\n pass", "description": "Construct a deep copy of a linked list where each node has next and random pointers.", "examples": [ { "input": "head = [[7,null],[13,0],[11,4],[10,2],[1,0]]", "output": "[[7,null],[13,0],[11,4],[10,2],[1,0]]" } ], "constraints": [ "0 <= n <= 1000" ], "leetcode_url": "https://leetcode.com/problems/copy-list-with-random-pointer/", "reference_solution": "class Solution:\n def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':\n oldToCopy = {None: None}\n cur = head\n while cur:\n oldToCopy[cur] = Node(cur.val)\n cur = cur.next\n cur = head\n while cur:\n copy = oldToCopy[cur]\n copy.next = oldToCopy[cur.next]\n copy.random = oldToCopy[cur.random]\n cur = cur.next\n return oldToCopy[head]" }, { "id": "nc-2", "problem_number": 2, "name": "Add Two Numbers", "pattern": "Linked List", "difficulty": "Medium", "time_complexity": "O(max(N, M))", "space_complexity": "O(1)", "starter_code": "class Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n pass", "description": "Add two non-empty linked lists representing two non-negative integers stored in reverse order.", "examples": [ { "input": "l1 = [2,4,3], l2 = [5,6,4]", "output": "[7,0,8]" } ], "constraints": [ "Number of nodes in range [1, 100]." ], "leetcode_url": "https://leetcode.com/problems/add-two-numbers/", "reference_solution": "class Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n dummy = ListNode()\n cur = dummy\n carry = 0\n while l1 or l2 or carry:\n v1 = l1.val if l1 else 0\n v2 = l2.val if l2 else 0\n val = v1 + v2 + carry\n carry = val // 10\n val = val % 10\n cur.next = ListNode(val)\n cur = cur.next\n l1 = l1.next if l1 else None\n l2 = l2.next if l2 else None\n return dummy.next" }, { "id": "nc-287", "problem_number": 287, "name": "Find the Duplicate Number", "pattern": "Linked List", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def findDuplicate(self, nums: list[int]) -> int:\n pass", "description": "Find the duplicate number in nums without modifying the array and using only O(1) extra space.", "examples": [ { "input": "nums = [1,3,4,2,2]", "output": "2" } ], "constraints": [ "1 <= n <= 10^5", "nums.length == n + 1" ], "leetcode_url": "https://leetcode.com/problems/find-the-duplicate-number/", "reference_solution": "class Solution:\n def findDuplicate(self, nums: list[int]) -> int:\n slow = fast = 0\n while True:\n slow = nums[slow]\n fast = nums[nums[fast]]\n if slow == fast:\n break\n slow2 = 0\n while True:\n slow = nums[slow]\n slow2 = nums[slow2]\n if slow == slow2:\n return slow" }, { "id": "nc-146", "problem_number": 146, "name": "LRU Cache", "pattern": "Linked List", "difficulty": "Medium", "time_complexity": "O(1)", "space_complexity": "O(capacity)", "starter_code": "class LRUCache:\n def __init__(self, capacity: int):\n pass\n def get(self, key: int) -> int:\n pass\n def put(self, key: int, value: int) -> None:\n pass", "description": "Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.", "examples": [ { "input": "[\"LRUCache\",\"put\",\"put\",\"get\",\"put\",\"get\",\"put\",\"get\",\"get\",\"get\"]", "output": "[null,null,null,1,null,-1,null,-1,3,4]" } ], "constraints": [ "1 <= capacity <= 3000" ], "leetcode_url": "https://leetcode.com/problems/lru-cache/", "reference_solution": "class Node:\n def __init__(self, k, v):\n self.key, self.val = k, v\n self.prev = self.next = None\n\nclass LRUCache:\n def __init__(self, capacity: int):\n self.cap = capacity\n self.cache = {}\n self.left, self.right = Node(0, 0), Node(0, 0)\n self.left.next, self.right.prev = self.right, self.left\n def remove(self, node):\n prev, nxt = node.prev, node.next\n prev.next, nxt.prev = nxt, prev\n def insert(self, node):\n prev, nxt = self.right.prev, self.right\n prev.next = nxt.prev = node\n node.next, node.prev = nxt, prev\n def get(self, key: int) -> int:\n if key in self.cache:\n self.remove(self.cache[key])\n self.insert(self.cache[key])\n return self.cache[key].val\n return -1\n def put(self, key: int, value: int) -> None:\n if key in self.cache:\n self.remove(self.cache[key])\n self.cache[key] = Node(key, value)\n self.insert(self.cache[key])\n if len(self.cache) > self.cap:\n lru = self.left.next\n self.remove(lru)\n del self.cache[lru.key]" }, { "id": "nc-23", "problem_number": 23, "name": "Merge k Sorted Lists", "pattern": "Linked List", "difficulty": "Hard", "time_complexity": "O(N log K)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def mergeKLists(self, lists: list[Optional[ListNode]]) -> Optional[ListNode]:\n pass", "description": "Merge all the linked-lists into one sorted linked-list and return it.", "examples": [ { "input": "lists = [[1,4,5],[1,3,4],[2,6]]", "output": "[1,1,2,3,4,4,5,6]" } ], "constraints": [ "k == lists.length", "0 <= k <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/merge-k-sorted-lists/", "reference_solution": "class Solution:\n def mergeKLists(self, lists: list[Optional[ListNode]]) -> Optional[ListNode]:\n if not lists or len(lists) == 0:\n return None\n while len(lists) > 1:\n mergedLists = []\n for i in range(0, len(lists), 2):\n l1 = lists[i]\n l2 = lists[i + 1] if (i + 1) < len(lists) else None\n mergedLists.append(self.mergeList(l1, l2))\n lists = mergedLists\n return lists[0]\n def mergeList(self, l1, l2):\n dummy = node = ListNode()\n while l1 and l2:\n if l1.val < l2.val:\n node.next, l1 = l1, l1.next\n else:\n node.next, l2 = l2, l2.next\n node = node.next\n node.next = l1 or l2\n return dummy.next" }, { "id": "nc-25", "problem_number": 25, "name": "Reverse Nodes in k-Group", "pattern": "Linked List", "difficulty": "Hard", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n pass", "description": "Reverse the nodes of the list k at a time, and return the modified list.", "examples": [ { "input": "head = [1,2,3,4,5], k = 2", "output": "[2,1,4,3,5]" } ], "constraints": [ "1 <= k <= sz <= 5000" ], "leetcode_url": "https://leetcode.com/problems/reverse-nodes-in-k-group/", "reference_solution": "class Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n dummy = ListNode(0, head)\n groupPrev = dummy\n while True:\n kth = self.getKth(groupPrev, k)\n if not kth:\n break\n groupNext = kth.next\n prev, curr = kth.next, groupPrev.next\n while curr != groupNext:\n tmp = curr.next\n curr.next = prev\n prev = curr\n curr = tmp\n tmp = groupPrev.next\n groupPrev.next = kth\n groupPrev = tmp\n return dummy.next\n def getKth(self, curr, k):\n while curr and k > 0:\n curr = curr.next\n k -= 1\n return curr" }, { "id": "nc-226", "problem_number": 226, "name": "Invert Binary Tree", "pattern": "Trees", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n pass", "description": "Given the root of a binary tree, invert the tree, and return its root.", "examples": [ { "input": "root = [4,2,7,1,3,6,9]", "output": "[4,7,2,9,6,3,1]" } ], "constraints": [ "The number of nodes in the tree is in the range [0, 100]." ], "leetcode_url": "https://leetcode.com/problems/invert-binary-tree/", "reference_solution": "class Solution:\n def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n if not root:\n return None\n root.left, root.right = root.right, root.left\n self.invertTree(root.left)\n self.invertTree(root.right)\n return root" }, { "id": "nc-104", "problem_number": 104, "name": "Maximum Depth of Binary Tree", "pattern": "Trees", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def maxDepth(self, root: Optional[TreeNode]) -> int:\n pass", "description": "Given the root of a binary tree, return its maximum depth.", "examples": [ { "input": "root = [3,9,20,null,null,15,7]", "output": "3" } ], "constraints": [ "Number of nodes is in range [0, 10^4]." ], "leetcode_url": "https://leetcode.com/problems/maximum-depth-of-binary-tree/", "reference_solution": "class Solution:\n def maxDepth(self, root: Optional[TreeNode]) -> int:\n if not root:\n return 0\n return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))" }, { "id": "nc-543", "problem_number": 543, "name": "Diameter of Binary Tree", "pattern": "Trees", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n pass", "description": "Return the length of the diameter of the tree.", "examples": [ { "input": "root = [1,2,3,4,5]", "output": "3" } ], "constraints": [ "Number of nodes in range [1, 10^4]." ], "leetcode_url": "https://leetcode.com/problems/diameter-of-binary-tree/", "reference_solution": "class Solution:\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n res = 0\n def dfs(curr):\n nonlocal res\n if not curr:\n return 0\n left, right = dfs(curr.left), dfs(curr.right)\n res = max(res, left + right)\n return 1 + max(left, right)\n dfs(root)\n return res" }, { "id": "nc-110", "problem_number": 110, "name": "Balanced Binary Tree", "pattern": "Trees", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def isBalanced(self, root: Optional[TreeNode]) -> bool:\n pass", "description": "Determine if a binary tree is height-balanced.", "examples": [ { "input": "root = [3,9,20,null,null,15,7]", "output": "true" } ], "constraints": [ "Number of nodes in range [0, 5000]." ], "leetcode_url": "https://leetcode.com/problems/balanced-binary-tree/", "reference_solution": "class Solution:\n def isBalanced(self, root: Optional[TreeNode]) -> bool:\n def dfs(root):\n if not root:\n return [True, 0]\n left, right = dfs(root.left), dfs(root.right)\n balanced = left[0] and right[0] and abs(left[1] - right[1]) <= 1\n return [balanced, 1 + max(left[1], right[1])]\n return dfs(root)[0]" }, { "id": "nc-100", "problem_number": 100, "name": "Same Tree", "pattern": "Trees", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n pass", "description": "Check if two binary trees are structurally identical and the nodes have the same value.", "examples": [ { "input": "p = [1,2,3], q = [1,2,3]", "output": "true" } ], "constraints": [ "Number of nodes in range [0, 100]." ], "leetcode_url": "https://leetcode.com/problems/same-tree/", "reference_solution": "class Solution:\n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n if not p and not q:\n return True\n if p and q and p.val == q.val:\n return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n return False" }, { "id": "nc-572", "problem_number": 572, "name": "Subtree of Another Tree", "pattern": "Trees", "difficulty": "Easy", "time_complexity": "O(S * T)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n pass", "description": "Return true if there is a subtree of root with the same structure and node values of subRoot.", "examples": [ { "input": "root = [3,4,5,1,2], subRoot = [4,1,2]", "output": "true" } ], "constraints": [ "Number of nodes in root is in range [1, 2000]." ], "leetcode_url": "https://leetcode.com/problems/subtree-of-another-tree/", "reference_solution": "class Solution:\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n if not subRoot:\n return True\n if not root:\n return False\n if self.sameTree(root, subRoot):\n return True\n return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)\n def sameTree(self, root, subRoot):\n if not root and not subRoot:\n return True\n if root and subRoot and root.val == subRoot.val:\n return self.sameTree(root.left, subRoot.left) and self.sameTree(root.right, subRoot.right)\n return False" }, { "id": "nc-235", "problem_number": 235, "name": "Lowest Common Ancestor of a Binary Search Tree", "pattern": "Trees", "difficulty": "Medium", "time_complexity": "O(log N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n pass", "description": "Find the lowest common ancestor (LCA) node of two given nodes in the BST.", "examples": [ { "input": "root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8", "output": "6" } ], "constraints": [ "All Node.val are unique." ], "leetcode_url": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/", "reference_solution": "class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n cur = root\n while cur:\n if p.val > cur.val and q.val > cur.val:\n cur = cur.right\n elif p.val < cur.val and q.val < cur.val:\n cur = cur.left\n else:\n return cur" }, { "id": "nc-102", "problem_number": 102, "name": "Binary Tree Level Order Traversal", "pattern": "Trees", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def levelOrder(self, root: Optional[TreeNode]) -> list[list[int]]:\n pass", "description": "Return the level order traversal of its nodes' values (i.e., from left to right, level by level).", "examples": [ { "input": "root = [3,9,20,null,null,15,7]", "output": "[[3],[9,20],[15,7]]" } ], "constraints": [ "Number of nodes in range [0, 2000]." ], "leetcode_url": "https://leetcode.com/problems/binary-tree-level-order-traversal/", "reference_solution": "from collections import deque\n\nclass Solution:\n def levelOrder(self, root: Optional[TreeNode]) -> list[list[int]]:\n res = []\n q = deque([root])\n while q:\n val = []\n for _ in range(len(q)):\n node = q.popleft()\n if node:\n val.append(node.val)\n q.append(node.left)\n q.append(node.right)\n if val:\n res.append(val)\n return res" }, { "id": "nc-199", "problem_number": 199, "name": "Binary Tree Right Side View", "pattern": "Trees", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def rightSideView(self, root: Optional[TreeNode]) -> list[int]:\n pass", "description": "Return the values of the nodes you can see ordered from top to bottom standing on the right side.", "examples": [ { "input": "root = [1,2,3,null,5,null,4]", "output": "[1,3,4]" } ], "constraints": [ "Number of nodes in range [0, 100]." ], "leetcode_url": "https://leetcode.com/problems/binary-tree-right-side-view/", "reference_solution": "from collections import deque\n\nclass Solution:\n def rightSideView(self, root: Optional[TreeNode]) -> list[int]:\n res = []\n q = deque([root])\n while q:\n rightSide = None\n for _ in range(len(q)):\n node = q.popleft()\n if node:\n rightSide = node\n q.append(node.left)\n q.append(node.right)\n if rightSide:\n res.append(rightSide.val)\n return res" }, { "id": "nc-1448", "problem_number": 1448, "name": "Count Good Nodes in Binary Tree", "pattern": "Trees", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def goodNodes(self, root: TreeNode) -> int:\n pass", "description": "A node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.", "examples": [ { "input": "root = [3,1,4,3,null,1,5]", "output": "4" } ], "constraints": [ "Number of nodes in range [1, 10^5]." ], "leetcode_url": "https://leetcode.com/problems/count-good-nodes-in-binary-tree/", "reference_solution": "class Solution:\n def goodNodes(self, root: TreeNode) -> int:\n def dfs(node, maxVal):\n if not node:\n return 0\n res = 1 if node.val >= maxVal else 0\n maxVal = max(maxVal, node.val)\n res += dfs(node.left, maxVal)\n res += dfs(node.right, maxVal)\n return res\n return dfs(root, root.val)" }, { "id": "nc-98", "problem_number": 98, "name": "Validate Binary Search Tree", "pattern": "Trees", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n pass", "description": "Determine if a binary tree is a valid binary search tree (BST).", "examples": [ { "input": "root = [2,1,3]", "output": "true" } ], "constraints": [ "Number of nodes in range [1, 10^4]." ], "leetcode_url": "https://leetcode.com/problems/validate-binary-search-tree/", "reference_solution": "class Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n def valid(node, left, right):\n if not node:\n return True\n if not (left < node.val < right):\n return False\n return valid(node.left, left, node.val) and valid(node.right, node.val, right)\n return valid(root, float(\"-inf\"), float(\"inf\"))" }, { "id": "nc-230", "problem_number": 230, "name": "Kth Smallest Element in a BST", "pattern": "Trees", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n pass", "description": "Given the root of a BST, return the kth smallest value (1-indexed) of all the values in the tree.", "examples": [ { "input": "root = [3,1,4,null,2], k = 1", "output": "1" } ], "constraints": [ "1 <= k <= n <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/kth-smallest-element-in-a-bst/", "reference_solution": "class Solution:\n def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n stack = []\n curr = root\n while stack or curr:\n while curr:\n stack.append(curr)\n curr = curr.left\n curr = stack.pop()\n k -= 1\n if k == 0:\n return curr.val\n curr = curr.right" }, { "id": "nc-105", "problem_number": 105, "name": "Construct Binary Tree from Preorder and Inorder Traversal", "pattern": "Trees", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def buildTree(self, preorder: list[int], inorder: list[int]) -> Optional[TreeNode]:\n pass", "description": "Construct and return the binary tree given two integer arrays preorder and inorder.", "examples": [ { "input": "preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]", "output": "[3,9,20,null,null,15,7]" } ], "constraints": [ "1 <= preorder.length <= 3000" ], "leetcode_url": "https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/", "reference_solution": "class Solution:\n def buildTree(self, preorder: list[int], inorder: list[int]) -> Optional[TreeNode]:\n if not preorder or not inorder:\n return None\n root = TreeNode(preorder[0])\n mid = inorder.index(preorder[0])\n root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid])\n root.right = self.buildTree(preorder[mid + 1 :], inorder[mid + 1 :])\n return root" }, { "id": "nc-124", "problem_number": 124, "name": "Binary Tree Maximum Path Sum", "pattern": "Trees", "difficulty": "Hard", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def maxPathSum(self, root: Optional[TreeNode]) -> int:\n pass", "description": "Return the maximum path sum of any non-empty path in a binary tree.", "examples": [ { "input": "root = [1,2,3]", "output": "6" }, { "input": "root = [-10,9,20,null,null,15,7]", "output": "42" } ], "constraints": [ "Number of nodes in range [1, 3 * 10^4]." ], "leetcode_url": "https://leetcode.com/problems/binary-tree-maximum-path-sum/", "reference_solution": "class Solution:\n def maxPathSum(self, root: Optional[TreeNode]) -> int:\n res = [root.val]\n def dfs(root):\n if not root:\n return 0\n leftMax = max(dfs(root.left), 0)\n rightMax = max(dfs(root.right), 0)\n res[0] = max(res[0], root.val + leftMax + rightMax)\n return root.val + max(leftMax, rightMax)\n dfs(root)\n return res[0]" }, { "id": "nc-297", "problem_number": 297, "name": "Serialize and Deserialize Binary Tree", "pattern": "Trees", "difficulty": "Hard", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Codec:\n def serialize(self, root):\n pass\n def deserialize(self, data):\n pass", "description": "Design an algorithm to serialize and deserialize a binary tree.", "examples": [ { "input": "root = [1,2,3,null,null,4,5]", "output": "[1,2,3,null,null,4,5]" } ], "constraints": [ "Number of nodes in range [0, 10^4]." ], "leetcode_url": "https://leetcode.com/problems/serialize-and-deserialize-binary-tree/", "reference_solution": "class Codec:\n def serialize(self, root):\n res = []\n def dfs(node):\n if not node:\n res.append(\"N\")\n return\n res.append(str(node.val))\n dfs(node.left)\n dfs(node.right)\n dfs(root)\n return \",\".join(res)\n def deserialize(self, data):\n vals = data.split(\",\")\n self.i = 0\n def dfs():\n if vals[self.i] == \"N\":\n self.i += 1\n return None\n node = TreeNode(int(vals[self.i]))\n self.i += 1\n node.left = dfs()\n node.right = dfs()\n return node\n return dfs()" }, { "id": "nc-703", "problem_number": 703, "name": "Kth Largest Element in a Stream", "pattern": "Heap / Priority Queue", "difficulty": "Easy", "time_complexity": "O(N log K)", "space_complexity": "O(K)", "starter_code": "class KthLargest:\n def __init__(self, k: int, nums: list[int]):\n pass\n def add(self, val: int) -> int:\n pass", "description": "Design a class to find the kth largest element in a stream.", "examples": [ { "input": "[\"KthLargest\",\"add\",\"add\",\"add\",\"add\",\"add\"]", "output": "[null,4,5,5,8,8]" } ], "constraints": [ "1 <= k <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/kth-largest-element-in-a-stream/", "reference_solution": "import heapq\n\nclass KthLargest:\n def __init__(self, k: int, nums: list[int]):\n self.minHeap, self.k = nums, k\n heapq.heapify(self.minHeap)\n while len(self.minHeap) > k: heapq.heappop(self.minHeap)\n def add(self, val: int) -> int:\n heapq.heappush(self.minHeap, val)\n if len(self.minHeap) > self.k: heapq.heappop(self.minHeap)\n return self.minHeap[0]" }, { "id": "nc-1046", "problem_number": 1046, "name": "Last Stone Weight", "pattern": "Heap / Priority Queue", "difficulty": "Easy", "time_complexity": "O(N log N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def lastStoneWeight(self, stones: list[int]) -> int:\n pass", "description": "Smash the two heaviest stones x and y together until at most one stone is left.", "examples": [ { "input": "stones = [2,7,4,1,8,1]", "output": "1" } ], "constraints": [ "1 <= stones.length <= 30" ], "leetcode_url": "https://leetcode.com/problems/last-stone-weight/", "reference_solution": "import heapq\n\nclass Solution:\n def lastStoneWeight(self, stones: list[int]) -> int:\n stones = [-s for s in stones]\n heapq.heapify(stones)\n while len(stones) > 1:\n first = heapq.heappop(stones)\n second = heapq.heappop(stones)\n if second > first: heapq.heappush(stones, first - second)\n stones.append(0)\n return abs(stones[0])" }, { "id": "nc-973", "problem_number": 973, "name": "K Closest Points to Origin", "pattern": "Heap / Priority Queue", "difficulty": "Medium", "time_complexity": "O(N log K)", "space_complexity": "O(K)", "starter_code": "class Solution:\n def kClosest(self, points: list[list[int]], k: int) -> list[list[int]]:\n pass", "description": "Given an array of points, return the k closest points to the origin (0, 0).", "examples": [ { "input": "points = [[1,3],[-2,2]], k = 1", "output": "[[-2,2]]" } ], "constraints": [ "1 <= k <= points.length <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/k-closest-points-to-origin/", "reference_solution": "import heapq\n\nclass Solution:\n def kClosest(self, points: list[list[int]], k: int) -> list[list[int]]:\n pts = []\n for x, y in points:\n dist = (x ** 2) + (y ** 2)\n pts.append([dist, x, y])\n heapq.heapify(pts)\n res = []\n for _ in range(k):\n dist, x, y = heapq.heappop(pts)\n res.append([x, y])\n return res" }, { "id": "nc-215", "problem_number": 215, "name": "Kth Largest Element in an Array", "pattern": "Heap / Priority Queue", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def findKthLargest(self, nums: list[int], k: int) -> int:\n pass", "description": "Given an integer array nums and an integer k, return the kth largest element in the array.", "examples": [ { "input": "nums = [3,2,1,5,6,4], k = 2", "output": "5" } ], "constraints": [ "1 <= k <= nums.length <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/kth-largest-element-in-an-array/", "reference_solution": "import heapq\n\nclass Solution:\n def findKthLargest(self, nums: list[int], k: int) -> int:\n return heapq.nlargest(k, nums)[-1]" }, { "id": "nc-621", "problem_number": 621, "name": "Task Scheduler", "pattern": "Heap / Priority Queue", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def leastInterval(self, tasks: list[str], n: int) -> int:\n pass", "description": "Return the minimum number of CPU intervals required to complete all tasks with cooling period n.", "examples": [ { "input": "tasks = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 2", "output": "8" } ], "constraints": [ "1 <= tasks.length <= 10^4", "0 <= n <= 100" ], "leetcode_url": "https://leetcode.com/problems/task-scheduler/", "reference_solution": "from collections import Counter, deque\nimport heapq\n\nclass Solution:\n def leastInterval(self, tasks: list[str], n: int) -> int:\n count = Counter(tasks)\n maxHeap = [-cnt for cnt in count.values()]\n heapq.heapify(maxHeap)\n time = 0\n q = deque()\n while maxHeap or q:\n time += 1\n if maxHeap:\n cnt = 1 + heapq.heappop(maxHeap)\n if cnt: q.append([cnt, time + n])\n if q and q[0][1] == time:\n heapq.heappush(maxHeap, q.popleft()[0])\n return time" }, { "id": "nc-355", "problem_number": 355, "name": "Design Twitter", "pattern": "Heap / Priority Queue", "difficulty": "Medium", "time_complexity": "O(10 log K)", "space_complexity": "O(N)", "starter_code": "class Twitter:\n def __init__(self):\n pass\n def postTweet(self, userId: int, tweetId: int) -> None:\n pass\n def getNewsFeed(self, userId: int) -> list[int]:\n pass\n def follow(self, followerId: int, followeeId: int) -> None:\n pass\n def unfollow(self, followerId: int, followeeId: int) -> None:\n pass", "description": "Design a simplified version of Twitter where users can post tweets, follow/unfollow, and get the 10 most recent tweets.", "examples": [ { "input": "[\"Twitter\",\"postTweet\",\"getNewsFeed\",\"follow\",\"postTweet\",\"getNewsFeed\"]", "output": "[null,null,[5],null,null,[6,5]]" } ], "constraints": [ "1 <= userId, followeeId <= 500" ], "leetcode_url": "https://leetcode.com/problems/design-twitter/", "reference_solution": "from collections import defaultdict\nimport heapq\n\nclass Twitter:\n def __init__(self):\n self.count = 0\n self.tweetMap = defaultdict(list)\n self.followMap = defaultdict(set)\n def postTweet(self, userId: int, tweetId: int) -> None:\n self.tweetMap[userId].append([self.count, tweetId])\n self.count -= 1\n def getNewsFeed(self, userId: int) -> list[int]:\n res, minHeap = [], []\n self.followMap[userId].add(userId)\n for followeeId in self.followMap[userId]:\n if followeeId in self.tweetMap:\n index = len(self.tweetMap[followeeId]) - 1\n count, tweetId = self.tweetMap[followeeId][index]\n heapq.heappush(minHeap, [count, tweetId, followeeId, index - 1])\n while minHeap and len(res) < 10:\n count, tweetId, followeeId, index = heapq.heappop(minHeap)\n res.append(tweetId)\n if index >= 0:\n count, tweetId = self.tweetMap[followeeId][index]\n heapq.heappush(minHeap, [count, tweetId, followeeId, index - 1])\n return res\n def follow(self, followerId: int, followeeId: int) -> None:\n self.followMap[followerId].add(followeeId)\n def unfollow(self, followerId: int, followeeId: int) -> None:\n if followeeId in self.followMap[followerId]: self.followMap[followerId].remove(followeeId)" }, { "id": "nc-295", "problem_number": 295, "name": "Find Median from Data Stream", "pattern": "Heap / Priority Queue", "difficulty": "Hard", "time_complexity": "O(log N)", "space_complexity": "O(N)", "starter_code": "class MedianFinder:\n def __init__(self):\n pass\n def addNum(self, num: int) -> None:\n pass\n def findMedian(self) -> float:\n pass", "description": "Find the median of all elements added so far from a data stream.", "examples": [ { "input": "[\"MedianFinder\",\"addNum\",\"addNum\",\"findMedian\",\"addNum\",\"findMedian\"]", "output": "[null,null,null,1.5,null,2.0]" } ], "constraints": [ "-10^5 <= num <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/find-median-from-data-stream/", "reference_solution": "import heapq\n\nclass MedianFinder:\n def __init__(self):\n self.small, self.large = [], []\n def addNum(self, num: int) -> None:\n if self.large and num > self.large[0]: heapq.heappush(self.large, num)\n else: heapq.heappush(self.small, -1 * num)\n if len(self.small) > len(self.large) + 1:\n val = -1 * heapq.heappop(self.small)\n heapq.heappush(self.large, val)\n if len(self.large) > len(self.small) + 1:\n val = heapq.heappop(self.large)\n heapq.heappush(self.small, -1 * val)\n def findMedian(self) -> float:\n if len(self.small) > len(self.large): return -1 * self.small[0]\n elif len(self.large) > len(self.small): return self.large[0]\n return (-1 * self.small[0] + self.large[0]) / 2.0" }, { "id": "nc-78", "problem_number": 78, "name": "Subsets", "pattern": "Backtracking", "difficulty": "Medium", "time_complexity": "O(N * 2^N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def subsets(self, nums: list[int]) -> list[list[int]]:\n pass", "description": "Given an integer array nums of unique elements, return all possible subsets (the power set).", "examples": [ { "input": "nums = [1,2,3]", "output": "[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]" } ], "constraints": [ "1 <= nums.length <= 10" ], "leetcode_url": "https://leetcode.com/problems/subsets/", "reference_solution": "class Solution:\n def subsets(self, nums: list[int]) -> list[list[int]]:\n res = []\n subset = []\n def dfs(i):\n if i >= len(nums):\n res.append(subset.copy())\n return\n subset.append(nums[i])\n dfs(i + 1)\n subset.pop()\n dfs(i + 1)\n dfs(0)\n return res" }, { "id": "nc-39", "problem_number": 39, "name": "Combination Sum", "pattern": "Backtracking", "difficulty": "Medium", "time_complexity": "O(2^target)", "space_complexity": "O(target)", "starter_code": "class Solution:\n def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:\n pass", "description": "Return a list of all unique combinations of candidates where the chosen numbers sum to target.", "examples": [ { "input": "candidates = [2,3,6,7], target = 7", "output": "[[2,2,3],[7]]" } ], "constraints": [ "1 <= candidates.length <= 30" ], "leetcode_url": "https://leetcode.com/problems/combination-sum/", "reference_solution": "class Solution:\n def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:\n res = []\n def dfs(i, cur, total):\n if total == target:\n res.append(cur.copy())\n return\n if i >= len(candidates) or total > target:\n return\n cur.append(candidates[i])\n dfs(i, cur, total + candidates[i])\n cur.pop()\n dfs(i + 1, cur, total)\n dfs(0, [], 0)\n return res" }, { "id": "nc-40", "problem_number": 40, "name": "Combination Sum II", "pattern": "Backtracking", "difficulty": "Medium", "time_complexity": "O(2^N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def combinationSum2(self, candidates: list[int], target: int) -> list[list[int]]:\n pass", "description": "Find all unique combinations in candidates where the candidate numbers sum to target, using each number once.", "examples": [ { "input": "candidates = [10,1,2,7,6,1,5], target = 8", "output": "[[1,1,6],[1,2,5],[1,7],[2,6]]" } ], "constraints": [ "1 <= candidates.length <= 100" ], "leetcode_url": "https://leetcode.com/problems/combination-sum-ii/", "reference_solution": "class Solution:\n def combinationSum2(self, candidates: list[int], target: int) -> list[list[int]]:\n candidates.sort()\n res = []\n def backtrack(cur, pos, target):\n if target == 0:\n res.append(cur.copy())\n return\n if target <= 0:\n return\n prev = -1\n for i in range(pos, len(candidates)):\n if candidates[i] == prev:\n continue\n cur.append(candidates[i])\n backtrack(cur, i + 1, target - candidates[i])\n cur.pop()\n prev = candidates[i]\n backtrack([], 0, target)\n return res" }, { "id": "nc-46", "problem_number": 46, "name": "Permutations", "pattern": "Backtracking", "difficulty": "Medium", "time_complexity": "O(N! * N)", "space_complexity": "O(N!)", "starter_code": "class Solution:\n def permute(self, nums: list[int]) -> list[list[int]]:\n pass", "description": "Given an array nums of distinct integers, return all the possible permutations.", "examples": [ { "input": "nums = [1,2,3]", "output": "[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]" } ], "constraints": [ "1 <= nums.length <= 6" ], "leetcode_url": "https://leetcode.com/problems/permutations/", "reference_solution": "class Solution:\n def permute(self, nums: list[int]) -> list[list[int]]:\n res = []\n if len(nums) == 1: return [nums[:]]\n for i in range(len(nums)):\n n = nums.pop(0)\n perms = self.permute(nums)\n for perm in perms: perm.append(n)\n res.extend(perms)\n nums.append(n)\n return res" }, { "id": "nc-90", "problem_number": 90, "name": "Subsets II", "pattern": "Backtracking", "difficulty": "Medium", "time_complexity": "O(N * 2^N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def subsetsWithDup(self, nums: list[int]) -> list[list[int]]:\n pass", "description": "Given an integer array nums that may contain duplicates, return all possible subsets (the power set).", "examples": [ { "input": "nums = [1,2,2]", "output": "[[],[1],[1,2],[1,2,2],[2],[2,2]]" } ], "constraints": [ "1 <= nums.length <= 10" ], "leetcode_url": "https://leetcode.com/problems/subsets-ii/", "reference_solution": "class Solution:\n def subsetsWithDup(self, nums: list[int]) -> list[list[int]]:\n res = []\n nums.sort()\n def backtrack(i, subset):\n if i == len(nums):\n res.append(subset[::])\n return\n subset.append(nums[i])\n backtrack(i + 1, subset)\n subset.pop()\n while i + 1 < len(nums) and nums[i] == nums[i + 1]: i += 1\n backtrack(i + 1, subset)\n backtrack(0, [])\n return res" }, { "id": "nc-22", "problem_number": 22, "name": "Generate Parentheses", "pattern": "Backtracking", "difficulty": "Medium", "time_complexity": "O(4^N / sqrt(N))", "space_complexity": "O(N)", "starter_code": "class Solution:\n def generateParenthesis(self, n: int) -> list[str]:\n pass", "description": "Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.", "examples": [ { "input": "n = 3", "output": "[\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]" } ], "constraints": [ "1 <= n <= 8" ], "leetcode_url": "https://leetcode.com/problems/generate-parentheses/", "reference_solution": "class Solution:\n def generateParenthesis(self, n: int) -> list[str]:\n stack, res = [], []\n def backtrack(openN, closedN):\n if openN == closedN == n:\n res.append(\"\".join(stack))\n return\n if openN < n:\n stack.append(\"(\")\n backtrack(openN + 1, closedN)\n stack.pop()\n if closedN < openN:\n stack.append(\")\")\n backtrack(openN, closedN + 1)\n stack.pop()\n backtrack(0, 0)\n return res" }, { "id": "nc-79", "problem_number": 79, "name": "Word Search", "pattern": "Backtracking", "difficulty": "Medium", "time_complexity": "O(M * N * 4^L)", "space_complexity": "O(L)", "starter_code": "class Solution:\n def exist(self, board: list[list[str]], word: str) -> bool:\n pass", "description": "Given an m x n grid of characters board and a string word, return true if word exists in the grid.", "examples": [ { "input": "board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCCED\"", "output": "true" } ], "constraints": [ "m == board.length", "n = board[i].length", "1 <= word.length <= 15" ], "leetcode_url": "https://leetcode.com/problems/word-search/", "reference_solution": "class Solution:\n def exist(self, board: list[list[str]], word: str) -> bool:\n ROWS, COLS = len(board), len(board[0])\n path = set()\n def dfs(r, c, i):\n if i == len(word): return True\n if (r < 0 or c < 0 or r >= ROWS or c >= COLS or word[i] != board[r][c] or (r, c) in path): return False\n path.add((r, c))\n res = (dfs(r + 1, c, i + 1) or dfs(r - 1, c, i + 1) or dfs(r, c + 1, i + 1) or dfs(r, c - 1, i + 1))\n path.remove((r, c))\n return res\n for r in range(ROWS):\n for c in range(COLS):\n if dfs(r, c, 0): return True\n return False" }, { "id": "nc-131", "problem_number": 131, "name": "Palindrome Partitioning", "pattern": "Backtracking", "difficulty": "Medium", "time_complexity": "O(N * 2^N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def partition(self, s: str) -> list[list[str]]:\n pass", "description": "Partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitionings.", "examples": [ { "input": "s = \"aab\"", "output": "[[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]" } ], "constraints": [ "1 <= s.length <= 16" ], "leetcode_url": "https://leetcode.com/problems/palindrome-partitioning/", "reference_solution": "class Solution:\n def partition(self, s: str) -> list[list[str]]:\n res, part = [], []\n def dfs(i):\n if i >= len(s):\n res.append(part.copy())\n return\n for j in range(i, len(s)):\n if self.isPali(s, i, j):\n part.append(s[i : j + 1])\n dfs(j + 1)\n part.pop()\n dfs(0)\n return res\n def isPali(self, s, l, r):\n while l < r:\n if s[l] != s[r]: return False\n l, r = l + 1, r - 1\n return True" }, { "id": "nc-17", "problem_number": 17, "name": "Letter Combinations of a Phone Number", "pattern": "Backtracking", "difficulty": "Medium", "time_complexity": "O(N * 4^N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def letterCombinations(self, digits: str) -> list[str]:\n pass", "description": "Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.", "examples": [ { "input": "digits = \"23\"", "output": "[\"ad\",\"ae\",\"af\",\"bd\",\"be\",\"bf\",\"cd\",\"ce\",\"cf\"]" } ], "constraints": [ "0 <= digits.length <= 4" ], "leetcode_url": "https://leetcode.com/problems/letter-combinations-of-a-phone-number/", "reference_solution": "class Solution:\n def letterCombinations(self, digits: str) -> list[str]:\n res = []\n digitToChar = {\"2\": \"abc\", \"3\": \"def\", \"4\": \"ghi\", \"5\": \"jkl\", \"6\": \"mno\", \"7\": \"qprs\", \"8\": \"tuv\", \"9\": \"wxyz\"}\n def backtrack(i, curStr):\n if len(curStr) == len(digits):\n res.append(curStr)\n return\n for c in digitToChar[digits[i]]:\n backtrack(i + 1, curStr + c)\n if digits: backtrack(0, \"\")\n return res" }, { "id": "nc-51", "problem_number": 51, "name": "N-Queens", "pattern": "Backtracking", "difficulty": "Hard", "time_complexity": "O(N!)", "space_complexity": "O(N^2)", "starter_code": "class Solution:\n def solveNQueens(self, n: int) -> list[list[str]]:\n pass", "description": "Place n queens on an n x n chessboard such that no two queens attack each other.", "examples": [ { "input": "n = 4", "output": "[[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]" } ], "constraints": [ "1 <= n <= 9" ], "leetcode_url": "https://leetcode.com/problems/n-queens/", "reference_solution": "class Solution:\n def solveNQueens(self, n: int) -> list[list[str]]:\n col, posDiag, negDiag = set(), set(), set()\n res = []\n board = [[\".\"] * n for _ in range(n)]\n def backtrack(r):\n if r == n:\n copy = [\"\".join(row) for row in board]\n res.append(copy)\n return\n for c in range(n):\n if c in col or (r + c) in posDiag or (r - c) in negDiag: continue\n col.add(c); posDiag.add(r + c); negDiag.add(r - c); board[r][c] = \"Q\"\n backtrack(r + 1)\n col.remove(c); posDiag.remove(r + c); negDiag.remove(r - c); board[r][c] = \".\"\n backtrack(0)\n return res" }, { "id": "nc-208", "problem_number": 208, "name": "Implement Trie (Prefix Tree)", "pattern": "Tries", "difficulty": "Medium", "time_complexity": "O(L)", "space_complexity": "O(N * L)", "starter_code": "class Trie:\n def __init__(self):\n pass\n def insert(self, word: str) -> None:\n pass\n def search(self, word: str) -> bool:\n pass\n def startsWith(self, prefix: str) -> bool:\n pass", "description": "Implement a trie with insert, search, and startsWith methods.", "examples": [ { "input": "[\"Trie\",\"insert\",\"search\",\"search\",\"startsWith\",\"insert\",\"search\"]", "output": "[null,null,true,false,true,null,true]" } ], "constraints": [ "1 <= word.length, prefix.length <= 2000" ], "leetcode_url": "https://leetcode.com/problems/implement-trie-prefix-tree/", "reference_solution": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.end = False\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n def insert(self, word: str) -> None:\n curr = self.root\n for c in word:\n if c not in curr.children:\n curr.children[c] = TrieNode()\n curr = curr.children[c]\n curr.end = True\n def search(self, word: str) -> bool:\n curr = self.root\n for c in word:\n if c not in curr.children: return False\n curr = curr.children[c]\n return curr.end\n def startsWith(self, prefix: str) -> bool:\n curr = self.root\n for c in prefix:\n if c not in curr.children: return False\n curr = curr.children[c]\n return True" }, { "id": "nc-211", "problem_number": 211, "name": "Design Add and Search Words Data Structure", "pattern": "Tries", "difficulty": "Medium", "time_complexity": "O(M)", "space_complexity": "O(N)", "starter_code": "class WordDictionary:\n def __init__(self):\n pass\n def addWord(self, word: str) -> None:\n pass\n def search(self, word: str) -> bool:\n pass", "description": "Design a data structure that supports adding new words and finding if a string matches any previously added string, with '.' wildcard support.", "examples": [ { "input": "[\"WordDictionary\",\"addWord\",\"addWord\",\"addWord\",\"search\",\"search\",\"search\",\"search\"]", "output": "[null,null,null,null,false,true,true,true]" } ], "constraints": [ "1 <= word.length <= 25" ], "leetcode_url": "https://leetcode.com/problems/design-add-and-search-words-data-structure/", "reference_solution": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.word = False\n\nclass WordDictionary:\n def __init__(self):\n self.root = TrieNode()\n def addWord(self, word: str) -> None:\n cur = self.root\n for c in word:\n if c not in cur.children: cur.children[c] = TrieNode()\n cur = cur.children[c]\n cur.word = True\n def search(self, word: str) -> bool:\n def dfs(j, root):\n cur = root\n for i in range(j, len(word)):\n c = word[i]\n if c == \".\":\n for child in cur.children.values():\n if dfs(i + 1, child): return True\n return False\n else:\n if c not in cur.children: return False\n cur = cur.children[c]\n return cur.word\n return dfs(0, self.root)" }, { "id": "nc-212", "problem_number": 212, "name": "Word Search II", "pattern": "Tries", "difficulty": "Hard", "time_complexity": "O(M * N * 4^L)", "space_complexity": "O(W * L)", "starter_code": "class Solution:\n def findWords(self, board: list[list[str]], words: list[str]) -> list[str]:\n pass", "description": "Given an m x n board of characters and a list of strings words, return all words on the board.", "examples": [ { "input": "board = [[\"o\",\"a\",\"a\",\"n\"],[\"e\",\"t\",\"a\",\"e\"],[\"i\",\"h\",\"k\",\"r\"],[\"i\",\"f\",\"l\",\"v\"]], words = [\"oath\",\"pea\",\"eat\",\"rain\"]", "output": "[\"eat\",\"oath\"]" } ], "constraints": [ "m == board.length", "n == board[i].length", "1 <= words.length <= 3 * 10^4" ], "leetcode_url": "https://leetcode.com/problems/word-search-ii/", "reference_solution": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.isWord = False\n def addWord(self, word):\n cur = self\n for c in word:\n if c not in cur.children: cur.children[c] = TrieNode()\n cur = cur.children[c]\n cur.isWord = True\n\nclass Solution:\n def findWords(self, board: list[list[str]], words: list[str]) -> list[str]:\n root = TrieNode()\n for w in words: root.addWord(w)\n ROWS, COLS = len(board), len(board[0])\n res, visit = set(), set()\n def dfs(r, c, node, word):\n if (r < 0 or c < 0 or r == ROWS or c == COLS or (r, c) in visit or board[r][c] not in node.children):\n return\n visit.add((r, c))\n node = node.children[board[r][c]]\n word += board[r][c]\n if node.isWord: res.add(word)\n dfs(r + 1, c, node, word)\n dfs(r - 1, c, node, word)\n dfs(r, c + 1, node, word)\n dfs(r, c - 1, node, word)\n visit.remove((r, c))\n for r in range(ROWS):\n for c in range(COLS):\n dfs(r, c, root, \"\")\n return list(res)" }, { "id": "nc-200", "problem_number": 200, "name": "Number of Islands", "pattern": "Graphs", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(M * N)", "starter_code": "class Solution:\n def numIslands(self, grid: list[list[str]]) -> int:\n pass", "description": "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.", "examples": [ { "input": "grid = [[\"1\",\"1\",\"1\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"0\",\"0\",\"0\",\"0\",\"0\"]]", "output": "1" } ], "constraints": [ "m == grid.length", "n == grid[i].length" ], "leetcode_url": "https://leetcode.com/problems/number-of-islands/", "reference_solution": "class Solution:\n def numIslands(self, grid: list[list[str]]) -> int:\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n islands = 0\n def dfs(r, c):\n if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] != \"1\": return\n grid[r][c] = \"0\"\n dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == \"1\":\n dfs(r, c)\n islands += 1\n return islands" }, { "id": "nc-695", "problem_number": 695, "name": "Max Area of Island", "pattern": "Graphs", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(M * N)", "starter_code": "class Solution:\n def maxAreaOfIsland(self, grid: list[list[int]]) -> int:\n pass", "description": "Return the maximum area of an island in grid. If there is no island, return 0.", "examples": [ { "input": "grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]", "output": "6" } ], "constraints": [ "m == grid.length", "n == grid[i].length" ], "leetcode_url": "https://leetcode.com/problems/max-area-of-island/", "reference_solution": "class Solution:\n def maxAreaOfIsland(self, grid: list[list[int]]) -> int:\n ROWS, COLS = len(grid), len(grid[0])\n visit = set()\n def dfs(r, c):\n if r < 0 or r == ROWS or c < 0 or c == COLS or grid[r][c] == 0 or (r, c) in visit: return 0\n visit.add((r, c))\n return 1 + dfs(r + 1, c) + dfs(r - 1, c) + dfs(r, c + 1) + dfs(r, c - 1)\n area = 0\n for r in range(ROWS):\n for c in range(COLS):\n area = max(area, dfs(r, c))\n return area" }, { "id": "nc-133", "problem_number": 133, "name": "Clone Graph", "pattern": "Graphs", "difficulty": "Medium", "time_complexity": "O(V + E)", "space_complexity": "O(V)", "starter_code": "class Solution:\n def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:\n pass", "description": "Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph.", "examples": [ { "input": "adjList = [[2,4],[1,3],[2,4],[1,3]]", "output": "[[2,4],[1,3],[2,4],[1,3]]" } ], "constraints": [ "The number of nodes in the graph is in range [0, 100]." ], "leetcode_url": "https://leetcode.com/problems/clone-graph/", "reference_solution": "class Solution:\n def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:\n oldToNew = {}\n def dfs(node):\n if node in oldToNew: return oldToNew[node]\n copy = Node(node.val)\n oldToNew[node] = copy\n for nei in node.neighbors: copy.neighbors.append(dfs(nei))\n return copy\n return dfs(node) if node else None" }, { "id": "nc-286", "problem_number": 286, "name": "Walls and Gates", "pattern": "Graphs", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(M * N)", "starter_code": "class Solution:\n def wallsAndGates(self, rooms: list[list[int]]) -> None:\n pass", "description": "Fill each empty room with the distance to its nearest gate. A gate is 0, a wall is -1, an empty room is 2147483647.", "examples": [ { "input": "rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]", "output": "[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]" } ], "constraints": [ "m == rooms.length", "n == rooms[i].length" ], "leetcode_url": "https://leetcode.com/problems/walls-and-gates/", "reference_solution": "from collections import deque\n\nclass Solution:\n def wallsAndGates(self, rooms: list[list[int]]) -> None:\n ROWS, COLS = len(rooms), len(rooms[0])\n q = deque()\n for r in range(ROWS):\n for c in range(COLS):\n if rooms[r][c] == 0: q.append((r, c))\n while q:\n r, c = q.popleft()\n for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n nr, nc = r + dr, c + dc\n if 0 <= nr < ROWS and 0 <= nc < COLS and rooms[nr][nc] == 2147483647:\n rooms[nr][nc] = rooms[r][c] + 1\n q.append((nr, nc))" }, { "id": "nc-994", "problem_number": 994, "name": "Rotting Oranges", "pattern": "Graphs", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(M * N)", "starter_code": "class Solution:\n def orangesRotting(self, grid: list[list[int]]) -> int:\n pass", "description": "Return the minimum number of minutes that must elapse until no cell has a fresh orange.", "examples": [ { "input": "grid = [[2,1,1],[1,1,0],[0,1,1]]", "output": "4" } ], "constraints": [ "m == grid.length", "n == grid[i].length" ], "leetcode_url": "https://leetcode.com/problems/rotting-oranges/", "reference_solution": "from collections import deque\n\nclass Solution:\n def orangesRotting(self, grid: list[list[int]]) -> int:\n q = deque()\n fresh = time = 0\n ROWS, COLS = len(grid), len(grid[0])\n for r in range(ROWS):\n for c in range(COLS):\n if grid[r][c] == 1: fresh += 1\n if grid[r][c] == 2: q.append((r, c))\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n while fresh > 0 and q:\n for _ in range(len(q)):\n r, c = q.popleft()\n for dr, dc in directions:\n row, col = r + dr, c + dc\n if row in range(ROWS) and col in range(COLS) and grid[row][col] == 1:\n grid[row][col] = 2\n q.append((row, col))\n fresh -= 1\n time += 1\n return time if fresh == 0 else -1" }, { "id": "nc-417", "problem_number": 417, "name": "Pacific Atlantic Water Flow", "pattern": "Graphs", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(M * N)", "starter_code": "class Solution:\n def pacificAtlantic(self, heights: list[list[int]]) -> list[list[int]]:\n pass", "description": "Return a list of grid coordinates where water can flow to both the Pacific and Atlantic oceans.", "examples": [ { "input": "heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]", "output": "[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]" } ], "constraints": [ "m == heights.length", "n == heights[r].length" ], "leetcode_url": "https://leetcode.com/problems/pacific-atlantic-water-flow/", "reference_solution": "class Solution:\n def pacificAtlantic(self, heights: list[list[int]]) -> list[list[int]]:\n ROWS, COLS = len(heights), len(heights[0])\n pac, atl = set(), set()\n def dfs(r, c, visit, prevHeight):\n if (r, c) in visit or r < 0 or c < 0 or r == ROWS or c == COLS or heights[r][c] < prevHeight: return\n visit.add((r, c))\n dfs(r + 1, c, visit, heights[r][c]); dfs(r - 1, c, visit, heights[r][c])\n dfs(r, c + 1, visit, heights[r][c]); dfs(r, c - 1, visit, heights[r][c])\n for c in range(COLS):\n dfs(0, c, pac, heights[0][c]); dfs(ROWS - 1, c, atl, heights[ROWS - 1][c])\n for r in range(ROWS):\n dfs(r, 0, pac, heights[r][0]); dfs(r, COLS - 1, atl, heights[r][COLS - 1])\n res = []\n for r in range(ROWS):\n for c in range(COLS):\n if (r, c) in pac and (r, c) in atl: res.append([r, c])\n return res" }, { "id": "nc-130", "problem_number": 130, "name": "Surrounded Regions", "pattern": "Graphs", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(M * N)", "starter_code": "class Solution:\n def solve(self, board: list[list[str]]) -> None:\n pass", "description": "Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.", "examples": [ { "input": "board = [[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"O\",\"X\"],[\"X\",\"X\",\"O\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]", "output": "[[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]" } ], "constraints": [ "m == board.length", "n == board[i].length" ], "leetcode_url": "https://leetcode.com/problems/surrounded-regions/", "reference_solution": "class Solution:\n def solve(self, board: list[list[str]]) -> None:\n ROWS, COLS = len(board), len(board[0])\n def capture(r, c):\n if r < 0 or c < 0 or r == ROWS or c == COLS or board[r][c] != \"O\": return\n board[r][c] = \"T\"\n capture(r + 1, c); capture(r - 1, c); capture(r, c + 1); capture(r, c - 1)\n for r in range(ROWS):\n for c in range(COLS):\n if board[r][c] == \"O\" and (r in [0, ROWS - 1] or c in [0, COLS - 1]): capture(r, c)\n for r in range(ROWS):\n for c in range(COLS):\n if board[r][c] == \"O\": board[r][c] = \"X\"\n elif board[r][c] == \"T\": board[r][c] = \"O\"" }, { "id": "nc-207", "problem_number": 207, "name": "Course Schedule", "pattern": "Graphs", "difficulty": "Medium", "time_complexity": "O(V + E)", "space_complexity": "O(V + E)", "starter_code": "class Solution:\n def canFinish(self, numCourses: int, prerequisites: list[list[int]]) -> bool:\n pass", "description": "Return true if you can finish all courses given prerequisite pairs, or false otherwise.", "examples": [ { "input": "numCourses = 2, prerequisites = [[1,0]]", "output": "true" } ], "constraints": [ "1 <= numCourses <= 2000" ], "leetcode_url": "https://leetcode.com/problems/course-schedule/", "reference_solution": "class Solution:\n def canFinish(self, numCourses: int, prerequisites: list[list[int]]) -> bool:\n preMap = {i: [] for i in range(numCourses)}\n for crs, pre in prerequisites: preMap[crs].append(pre)\n visiting = set()\n def dfs(crs):\n if crs in visiting: return False\n if preMap[crs] == []: return True\n visiting.add(crs)\n for pre in preMap[crs]:\n if not dfs(pre): return False\n visiting.remove(crs)\n preMap[crs] = []\n return True\n for c in range(numCourses):\n if not dfs(c): return False\n return True" }, { "id": "nc-210", "problem_number": 210, "name": "Course Schedule II", "pattern": "Graphs", "difficulty": "Medium", "time_complexity": "O(V + E)", "space_complexity": "O(V + E)", "starter_code": "class Solution:\n def findOrder(self, numCourses: int, prerequisites: list[list[int]]) -> list[int]:\n pass", "description": "Return the ordering of courses you should take to finish all courses.", "examples": [ { "input": "numCourses = 2, prerequisites = [[1,0]]", "output": "[0,1]" } ], "constraints": [ "1 <= numCourses <= 2000" ], "leetcode_url": "https://leetcode.com/problems/course-schedule-ii/", "reference_solution": "class Solution:\n def findOrder(self, numCourses: int, prerequisites: list[list[int]]) -> list[int]:\n prereq = {c: [] for c in range(numCourses)}\n for crs, pre in prerequisites: prereq[crs].append(pre)\n output = []\n visit, cycle = set(), set()\n def dfs(crs):\n if crs in cycle: return False\n if crs in visit: return True\n cycle.add(crs)\n for pre in prereq[crs]:\n if not dfs(pre): return False\n cycle.remove(crs)\n visit.add(crs)\n output.append(crs)\n return True\n for c in range(numCourses):\n if not dfs(c): return []\n return output" }, { "id": "nc-261", "problem_number": 261, "name": "Graph Valid Tree", "pattern": "Graphs", "difficulty": "Medium", "time_complexity": "O(V + E)", "space_complexity": "O(V + E)", "starter_code": "class Solution:\n def validTree(self, n: int, edges: list[list[int]]) -> bool:\n pass", "description": "Given n nodes labeled from 0 to n - 1 and a list of undirected edges, return true if these edges form a valid tree.", "examples": [ { "input": "n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]", "output": "true" } ], "constraints": [ "1 <= n <= 2000" ], "leetcode_url": "https://leetcode.com/problems/graph-valid-tree/", "reference_solution": "class Solution:\n def validTree(self, n: int, edges: list[list[int]]) -> bool:\n if not n: return True\n adj = {i: [] for i in range(n)}\n for n1, n2 in edges:\n adj[n1].append(n2)\n adj[n2].append(n1)\n visit = set()\n def dfs(i, prev):\n if i in visit: return False\n visit.add(i)\n for j in adj[i]:\n if j == prev: continue\n if not dfs(j, i): return False\n return True\n return dfs(0, -1) and len(visit) == n" }, { "id": "nc-323", "problem_number": 323, "name": "Number of Connected Components in an Undirected Graph", "pattern": "Graphs", "difficulty": "Medium", "time_complexity": "O(V + E)", "space_complexity": "O(V)", "starter_code": "class Solution:\n def countComponents(self, n: int, edges: list[list[int]]) -> int:\n pass", "description": "Find the number of connected components in an undirected graph.", "examples": [ { "input": "n = 5, edges = [[0,1],[1,2],[3,4]]", "output": "2" } ], "constraints": [ "1 <= n <= 2000" ], "leetcode_url": "https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/", "reference_solution": "class Solution:\n def countComponents(self, n: int, edges: list[list[int]]) -> int:\n par = [i for i in range(n)]\n rank = [1] * n\n def find(n1):\n res = n1\n while res != par[res]:\n par[res] = par[par[res]]\n res = par[res]\n return res\n def union(n1, n2):\n p1, p2 = find(n1), find(n2)\n if p1 == p2: return 0\n if rank[p2] > rank[p1]: par[p1] = p2; rank[p2] += rank[p1]\n else: par[p2] = p1; rank[p1] += rank[p2]\n return 1\n res = n\n for n1, n2 in edges: res -= union(n1, n2)\n return res" }, { "id": "nc-684", "problem_number": 684, "name": "Redundant Connection", "pattern": "Graphs", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def findRedundantConnection(self, edges: list[list[int]]) -> list[int]:\n pass", "description": "Return an edge that can be removed so that the resulting graph is a tree of n nodes.", "examples": [ { "input": "edges = [[1,2],[1,3],[2,3]]", "output": "[2,3]" } ], "constraints": [ "n == edges.length", "3 <= n <= 1000" ], "leetcode_url": "https://leetcode.com/problems/redundant-connection/", "reference_solution": "class Solution:\n def findRedundantConnection(self, edges: list[list[int]]) -> list[int]:\n par = [i for i in range(len(edges) + 1)]\n rank = [1] * (len(edges) + 1)\n def find(n):\n p = par[n]\n while p != par[p]:\n par[p] = par[par[p]]\n p = par[p]\n return p\n def union(n1, n2):\n p1, p2 = find(n1), find(n2)\n if p1 == p2: return False\n if rank[p1] > rank[p2]: par[p2] = p1; rank[p1] += rank[p2]\n else: par[p1] = p2; rank[p2] += rank[p1]\n return True\n for n1, n2 in edges:\n if not union(n1, n2): return [n1, n2]" }, { "id": "nc-127", "problem_number": 127, "name": "Word Ladder", "pattern": "Graphs", "difficulty": "Hard", "time_complexity": "O(M^2 * N)", "space_complexity": "O(M^2 * N)", "starter_code": "class Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: list[str]) -> int:\n pass", "description": "Return the number of words in the shortest transformation sequence from beginWord to endWord.", "examples": [ { "input": "beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]", "output": "5" } ], "constraints": [ "1 <= beginWord.length <= 10" ], "leetcode_url": "https://leetcode.com/problems/word-ladder/", "reference_solution": "from collections import defaultdict, deque\n\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: list[str]) -> int:\n if endWord not in wordList: return 0\n nei = defaultdict(list)\n wordList.append(beginWord)\n for word in wordList:\n for j in range(len(word)):\n pattern = word[:j] + \"*\" + word[j + 1 :]\n nei[pattern].append(word)\n visit = set([beginWord])\n q = deque([beginWord])\n res = 1\n while q:\n for _ in range(len(q)):\n word = q.popleft()\n if word == endWord: return res\n for j in range(len(word)):\n pattern = word[:j] + \"*\" + word[j + 1 :]\n for neiWord in nei[pattern]:\n if neiWord not in visit:\n visit.add(neiWord)\n q.append(neiWord)\n res += 1\n return 0" }, { "id": "nc-743", "problem_number": 743, "name": "Network Delay Time", "pattern": "Advanced Graphs", "difficulty": "Medium", "time_complexity": "O(E log V)", "space_complexity": "O(V + E)", "starter_code": "class Solution:\n def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n pass", "description": "Given network times, return the minimum time it takes for all n nodes to receive the signal from node k.", "examples": [ { "input": "times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2", "output": "2" } ], "constraints": [ "1 <= k <= n <= 100", "1 <= times.length <= 6000" ], "leetcode_url": "https://leetcode.com/problems/network-delay-time/", "reference_solution": "from collections import defaultdict\nimport heapq\n\nclass Solution:\n def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n edges = defaultdict(list)\n for u, v, w in times:\n edges[u].append((v, w))\n minHeap = [(0, k)]\n visit = set()\n t = 0\n while minHeap:\n w1, n1 = heapq.heappop(minHeap)\n if n1 in visit: continue\n visit.add(n1)\n t = max(t, w1)\n for n2, w2 in edges[n1]:\n if n2 not in visit:\n heapq.heappush(minHeap, (w1 + w2, n2))\n return t if len(visit) == n else -1" }, { "id": "nc-332", "problem_number": 332, "name": "Reconstruct Itinerary", "pattern": "Advanced Graphs", "difficulty": "Hard", "time_complexity": "O(E log E)", "space_complexity": "O(E)", "starter_code": "class Solution:\n def findItinerary(self, tickets: list[list[str]]) -> list[str]:\n pass", "description": "Find the itinerary that begins with 'JFK' using all tickets exactly once in lexical order.", "examples": [ { "input": "tickets = [[\"MUC\",\"LHR\"],[\"JFK\",\"MUC\"],[\"SFO\",\"SJC\"],[\"LHR\",\"SFO\"]]", "output": "[\"JFK\",\"MUC\",\"LHR\",\"SFO\",\"SJC\"]" } ], "constraints": [ "1 <= tickets.length <= 300" ], "leetcode_url": "https://leetcode.com/problems/reconstruct-itinerary/", "reference_solution": "from collections import defaultdict\n\nclass Solution:\n def findItinerary(self, tickets: list[list[str]]) -> list[str]:\n adj = defaultdict(list)\n for src, dst in sorted(tickets, reverse=True):\n adj[src].append(dst)\n res = []\n def dfs(src):\n while adj[src]:\n dfs(adj[src].pop())\n res.append(src)\n dfs(\"JFK\")\n return res[::-1]" }, { "id": "nc-1584", "problem_number": 1584, "name": "Min Cost to Connect All Points", "pattern": "Advanced Graphs", "difficulty": "Medium", "time_complexity": "O(N^2 log N)", "space_complexity": "O(N^2)", "starter_code": "class Solution:\n def minCostConnectPoints(self, points: list[list[int]]) -> int:\n pass", "description": "Return the minimum cost to make all points connected using Manhattan distance (Prim's or Kruskal's).", "examples": [ { "input": "points = [[0,0],[2,2],[3,10],[5,2],[7,0]]", "output": "20" } ], "constraints": [ "1 <= points.length <= 1000" ], "leetcode_url": "https://leetcode.com/problems/min-cost-to-connect-all-points/", "reference_solution": "from collections import defaultdict\nimport heapq\n\nclass Solution:\n def minCostConnectPoints(self, points: list[list[int]]) -> int:\n N = len(points)\n adj = defaultdict(list)\n for i in range(N):\n x1, y1 = points[i]\n for j in range(i + 1, N):\n x2, y2 = points[j]\n dist = abs(x1 - x2) + abs(y1 - y2)\n adj[i].append((dist, j))\n adj[j].append((dist, i))\n res = 0\n visit = set()\n minH = [[0, 0]]\n while len(visit) < N:\n cost, i = heapq.heappop(minH)\n if i in visit: continue\n res += cost\n visit.add(i)\n for neiCost, nei in adj[i]:\n if nei not in visit:\n heapq.heappush(minH, [neiCost, nei])\n return res" }, { "id": "nc-778", "problem_number": 778, "name": "Swim in Rising Water", "pattern": "Advanced Graphs", "difficulty": "Hard", "time_complexity": "O(N^2 log N)", "space_complexity": "O(N^2)", "starter_code": "class Solution:\n def swimInWater(self, grid: list[list[int]]) -> int:\n pass", "description": "Return the minimum time until you can reach the bottom right square from top left square.", "examples": [ { "input": "grid = [[0,2],[1,3]]", "output": "3" } ], "constraints": [ "n == grid.length == grid[i].length", "1 <= n <= 50" ], "leetcode_url": "https://leetcode.com/problems/swim-in-rising-water/", "reference_solution": "import heapq\n\nclass Solution:\n def swimInWater(self, grid: list[list[int]]) -> int:\n N = len(grid)\n visit = set()\n minH = [[grid[0][0], 0, 0]]\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n visit.add((0, 0))\n while minH:\n t, r, c = heapq.heappop(minH)\n if r == N - 1 and c == N - 1:\n return t\n for dr, dc in directions:\n nr, nc = r + dr, c + dc\n if 0 <= nr < N and 0 <= nc < N and (nr, nc) not in visit:\n visit.add((nr, nc))\n heapq.heappush(minH, [max(t, grid[nr][nc]), nr, nc])" }, { "id": "nc-269", "problem_number": 269, "name": "Alien Dictionary", "pattern": "Advanced Graphs", "difficulty": "Hard", "time_complexity": "O(C)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def alienOrder(self, words: list[str]) -> str:\n pass", "description": "Derive the alphabetical order of characters in a foreign language given sorted words.", "examples": [ { "input": "words = [\"wrt\",\"wrf\",\"er\",\"ett\",\"rftt\"]", "output": "\"wertf\"" } ], "constraints": [ "1 <= words.length <= 100", "1 <= words[i].length <= 100" ], "leetcode_url": "https://leetcode.com/problems/alien-dictionary/", "reference_solution": "class Solution:\n def alienOrder(self, words: list[str]) -> str:\n adj = {c: set() for w in words for c in w}\n for i in range(len(words) - 1):\n w1, w2 = words[i], words[i + 1]\n minLen = min(len(w1), len(w2))\n if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]: return \"\"\n for j in range(minLen):\n if w1[j] != w2[j]:\n adj[w1[j]].add(w2[j])\n break\n visited = {} # False = visited, True = in current path\n res = []\n def dfs(c):\n if c in visited: return visited[c]\n visited[c] = True\n for nei in adj[c]:\n if dfs(nei): return True\n visited[c] = False\n res.append(c)\n for c in adj:\n if dfs(c): return \"\"\n return \"\".join(res[::-1])" }, { "id": "nc-787", "problem_number": 787, "name": "Cheapest Flights Within K Stops", "pattern": "Advanced Graphs", "difficulty": "Medium", "time_complexity": "O(K * E)", "space_complexity": "O(V)", "starter_code": "class Solution:\n def findCheapestPrice(self, n: int, flights: list[list[int]], src: int, dst: int, k: int) -> int:\n pass", "description": "Find the cheapest price from src to dst with at most k stops (Bellman-Ford).", "examples": [ { "input": "n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1", "output": "700" } ], "constraints": [ "1 <= n <= 100", "0 <= k < n" ], "leetcode_url": "https://leetcode.com/problems/cheapest-flights-within-k-stops/", "reference_solution": "class Solution:\n def findCheapestPrice(self, n: int, flights: list[list[int]], src: int, dst: int, k: int) -> int:\n prices = [float(\"inf\")] * n\n prices[src] = 0\n for _ in range(k + 1):\n tmp = prices.copy()\n for s, d, p in flights:\n if prices[s] == float(\"inf\"): continue\n if prices[s] + p < tmp[d]: tmp[d] = prices[s] + p\n prices = tmp\n return -1 if prices[dst] == float(\"inf\") else prices[dst]" }, { "id": "nc-70", "problem_number": 70, "name": "Climbing Stairs", "pattern": "1-D DP", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def climbStairs(self, n: int) -> int:\n pass", "description": "You are climbing a staircase. It takes n steps to reach the top. Each time you can climb 1 or 2 steps. In how many distinct ways can you climb to the top?", "examples": [ { "input": "n = 3", "output": "3" } ], "constraints": [ "1 <= n <= 45" ], "leetcode_url": "https://leetcode.com/problems/climbing-stairs/", "reference_solution": "class Solution:\n def climbStairs(self, n: int) -> int:\n one, two = 1, 1\n for _ in range(n - 1):\n one, two = one + two, one\n return one" }, { "id": "nc-746", "problem_number": 746, "name": "Min Cost Climbing Stairs", "pattern": "1-D DP", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def minCostClimbingStairs(self, cost: list[int]) -> int:\n pass", "description": "Return the minimum cost to reach the top of the floor after starting from step 0 or 1.", "examples": [ { "input": "cost = [10,15,20]", "output": "15" } ], "constraints": [ "2 <= cost.length <= 1000" ], "leetcode_url": "https://leetcode.com/problems/min-cost-climbing-stairs/", "reference_solution": "class Solution:\n def minCostClimbingStairs(self, cost: list[int]) -> int:\n cost.append(0)\n for i in range(len(cost) - 3, -1, -1):\n cost[i] += min(cost[i + 1], cost[i + 2])\n return min(cost[0], cost[1])" }, { "id": "nc-198", "problem_number": 198, "name": "House Robber", "pattern": "1-D DP", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def rob(self, nums: list[int]) -> int:\n pass", "description": "Determine the maximum amount of money you can rob tonight without alerting the police (cannot rob adjacent houses).", "examples": [ { "input": "nums = [1,2,3,1]", "output": "4" } ], "constraints": [ "1 <= nums.length <= 100", "0 <= nums[i] <= 400" ], "leetcode_url": "https://leetcode.com/problems/house-robber/", "reference_solution": "class Solution:\n def rob(self, nums: list[int]) -> int:\n rob1, rob2 = 0, 0\n for n in nums:\n rob1, rob2 = rob2, max(n + rob1, rob2)\n return rob2" }, { "id": "nc-213", "problem_number": 213, "name": "House Robber II", "pattern": "1-D DP", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def rob(self, nums: list[int]) -> int:\n pass", "description": "All houses at this place are arranged in a circle. Rob the maximum money without triggering the alarm.", "examples": [ { "input": "nums = [2,3,2]", "output": "3" } ], "constraints": [ "1 <= nums.length <= 100" ], "leetcode_url": "https://leetcode.com/problems/house-robber-ii/", "reference_solution": "class Solution:\n def rob(self, nums: list[int]) -> int:\n def helper(arr):\n r1, r2 = 0, 0\n for n in arr:\n r1, r2 = r2, max(n + r1, r2)\n return r2\n return max(nums[0], helper(nums[1:]), helper(nums[:-1]))" }, { "id": "nc-5", "problem_number": 5, "name": "Longest Palindromic Substring", "pattern": "1-D DP", "difficulty": "Medium", "time_complexity": "O(N^2)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def longestPalindrome(self, s: str) -> str:\n pass", "description": "Given a string s, return the longest palindromic substring in s.", "examples": [ { "input": "s = \"babad\"", "output": "\"bab\"" } ], "constraints": [ "1 <= s.length <= 1000" ], "leetcode_url": "https://leetcode.com/problems/longest-palindromic-substring/", "reference_solution": "class Solution:\n def longestPalindrome(self, s: str) -> str:\n res = \"\"\n for i in range(len(s)):\n # odd length\n l, r = i, i\n while l >= 0 and r < len(s) and s[l] == s[r]:\n if (r - l + 1) > len(res): res = s[l:r + 1]\n l -= 1\n r += 1\n # even length\n l, r = i, i + 1\n while l >= 0 and r < len(s) and s[l] == s[r]:\n if (r - l + 1) > len(res): res = s[l:r + 1]\n l -= 1\n r += 1\n return res" }, { "id": "nc-647", "problem_number": 647, "name": "Palindromic Substrings", "pattern": "1-D DP", "difficulty": "Medium", "time_complexity": "O(N^2)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def countSubstrings(self, s: str) -> int:\n pass", "description": "Given a string s, return the number of palindromic substrings in it.", "examples": [ { "input": "s = \"aaa\"", "output": "6" } ], "constraints": [ "1 <= s.length <= 1000" ], "leetcode_url": "https://leetcode.com/problems/palindromic-substring/", "reference_solution": "class Solution:\n def countSubstrings(self, s: str) -> int:\n res = 0\n for i in range(len(s)):\n for l, r in ((i, i), (i, i + 1)):\n while l >= 0 and r < len(s) and s[l] == s[r]:\n res += 1\n l -= 1\n r += 1\n return res" }, { "id": "nc-91", "problem_number": 91, "name": "Decode Ways", "pattern": "1-D DP", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def numDecodings(self, s: str) -> int:\n pass", "description": "Return the number of ways to decode an encoded message containing digits mapping to 'A'-'Z'.", "examples": [ { "input": "s = \"226\"", "output": "3" } ], "constraints": [ "1 <= s.length <= 100" ], "leetcode_url": "https://leetcode.com/problems/decode-ways/", "reference_solution": "class Solution:\n def numDecodings(self, s: str) -> int:\n dp = {len(s): 1}\n for i in range(len(s) - 1, -1, -1):\n if s[i] == \"0\":\n dp[i] = 0\n else:\n dp[i] = dp[i + 1]\n if i + 1 < len(s) and (s[i] == \"1\" or (s[i] == \"2\" and s[i + 1] in \"0123456\")):\n dp[i] += dp[i + 2]\n return dp[0]" }, { "id": "nc-322", "problem_number": 322, "name": "Coin Change", "pattern": "1-D DP", "difficulty": "Medium", "time_complexity": "O(amount * len(coins))", "space_complexity": "O(amount)", "starter_code": "class Solution:\n def coinChange(self, coins: list[int], amount: int) -> int:\n pass", "description": "Return the fewest number of coins needed to make up the given amount. If impossible, return -1.", "examples": [ { "input": "coins = [1,2,5], amount = 11", "output": "3" } ], "constraints": [ "1 <= coins.length <= 12", "0 <= amount <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/coin-change/", "reference_solution": "class Solution:\n def coinChange(self, coins: list[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for a in range(1, amount + 1):\n for c in coins:\n if a - c >= 0:\n dp[a] = min(dp[a], 1 + dp[a - c])\n return dp[amount] if dp[amount] != amount + 1 else -1" }, { "id": "nc-152", "problem_number": 152, "name": "Maximum Product Subarray", "pattern": "1-D DP", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def maxProduct(self, nums: list[int]) -> int:\n pass", "description": "Find a contiguous non-empty subarray within a numerical array that has the largest product.", "examples": [ { "input": "nums = [2,3,-2,4]", "output": "6" } ], "constraints": [ "1 <= nums.length <= 2 * 10^4" ], "leetcode_url": "https://leetcode.com/problems/maximum-product-subarray/", "reference_solution": "class Solution:\n def maxProduct(self, nums: list[int]) -> int:\n res = max(nums)\n curMin, curMax = 1, 1\n for n in nums:\n if n == 0:\n curMin, curMax = 1, 1\n continue\n tmp = curMax * n\n curMax = max(n * curMax, n * curMin, n)\n curMin = min(tmp, n * curMin, n)\n res = max(res, curMax)\n return res" }, { "id": "nc-139", "problem_number": 139, "name": "Word Break", "pattern": "1-D DP", "difficulty": "Medium", "time_complexity": "O(N * M * K)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def wordBreak(self, s: str, wordDict: list[str]) -> bool:\n pass", "description": "Return true if s can be segmented into a space-separated sequence of one or more dictionary words.", "examples": [ { "input": "s = \"leetcode\", wordDict = [\"leet\",\"code\"]", "output": "true" } ], "constraints": [ "1 <= s.length <= 300" ], "leetcode_url": "https://leetcode.com/problems/word-break/", "reference_solution": "class Solution:\n def wordBreak(self, s: str, wordDict: list[str]) -> bool:\n dp = [False] * (len(s) + 1)\n dp[len(s)] = True\n for i in range(len(s) - 1, -1, -1):\n for w in wordDict:\n if (i + len(w)) <= len(s) and s[i:i + len(w)] == w:\n dp[i] = dp[i + len(w)]\n if dp[i]: break\n return dp[0]" }, { "id": "nc-300", "problem_number": 300, "name": "Longest Increasing Subsequence", "pattern": "1-D DP", "difficulty": "Medium", "time_complexity": "O(N log N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def lengthOfLIS(self, nums: list[int]) -> int:\n pass", "description": "Given an integer array nums, return the length of the longest strictly increasing subsequence.", "examples": [ { "input": "nums = [10,9,2,5,3,7,101,18]", "output": "4" } ], "constraints": [ "1 <= nums.length <= 2500" ], "leetcode_url": "https://leetcode.com/problems/longest-increasing-subsequence/", "reference_solution": "import bisect\n\nclass Solution:\n def lengthOfLIS(self, nums: list[int]) -> int:\n sub = []\n for x in nums:\n idx = bisect.bisect_left(sub, x)\n if idx == len(sub): sub.append(x)\n else: sub[idx] = x\n return len(sub)" }, { "id": "nc-416", "problem_number": 416, "name": "Partition Equal Subset Sum", "pattern": "1-D DP", "difficulty": "Medium", "time_complexity": "O(N * sum)", "space_complexity": "O(sum)", "starter_code": "class Solution:\n def canPartition(self, nums: list[int]) -> bool:\n pass", "description": "Determine if nums can be partitioned into two subsets such that the sum of elements in both subsets is equal.", "examples": [ { "input": "nums = [1,5,11,5]", "output": "true" } ], "constraints": [ "1 <= nums.length <= 200", "1 <= nums[i] <= 100" ], "leetcode_url": "https://leetcode.com/problems/partition-equal-subset-sum/", "reference_solution": "class Solution:\n def canPartition(self, nums: list[int]) -> bool:\n total = sum(nums)\n if total % 2 != 0: return False\n target = total // 2\n dp = {0}\n for n in nums:\n nextDp = set()\n for t in dp:\n if t + n == target: return True\n nextDp.add(t + n)\n nextDp.add(t)\n dp = nextDp\n return target in dp" }, { "id": "nc-62", "problem_number": 62, "name": "Unique Paths", "pattern": "2-D DP", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n pass", "description": "A robot is located at the top-left corner of a m x n grid. How many possible unique paths are there to the bottom-right corner?", "examples": [ { "input": "m = 3, n = 7", "output": "28" } ], "constraints": [ "1 <= m, n <= 100" ], "leetcode_url": "https://leetcode.com/problems/unique-paths/", "reference_solution": "class Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n row = [1] * n\n for _ in range(m - 1):\n newRow = [1] * n\n for j in range(n - 2, -1, -1):\n newRow[j] = newRow[j + 1] + row[j]\n row = newRow\n return row[0]" }, { "id": "nc-1143", "problem_number": 1143, "name": "Longest Common Subsequence", "pattern": "2-D DP", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(M * N)", "starter_code": "class Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n pass", "description": "Given two strings text1 and text2, return the length of their longest common subsequence.", "examples": [ { "input": "text1 = \"abcde\", text2 = \"ace\"", "output": "3" } ], "constraints": [ "1 <= text1.length, text2.length <= 1000" ], "leetcode_url": "https://leetcode.com/problems/longest-common-subsequence/", "reference_solution": "class Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n dp = [[0 for _ in range(len(text2) + 1)] for _ in range(len(text1) + 1)]\n for i in range(len(text1) - 1, -1, -1):\n for j in range(len(text2) - 1, -1, -1):\n if text1[i] == text2[j]:\n dp[i][j] = 1 + dp[i + 1][j + 1]\n else:\n dp[i][j] = max(dp[i + 1][j], dp[i][j + 1])\n return dp[0][0]" }, { "id": "nc-309", "problem_number": 309, "name": "Best Time to Buy and Sell Stock with Cooldown", "pattern": "2-D DP", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def maxProfit(self, prices: list[int]) -> int:\n pass", "description": "Find the maximum profit you can achieve with stock trading with a 1-day cooldown after selling.", "examples": [ { "input": "prices = [1,2,3,0,2]", "output": "3" } ], "constraints": [ "1 <= prices.length <= 5000" ], "leetcode_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/", "reference_solution": "class Solution:\n def maxProfit(self, prices: list[int]) -> int:\n dp = {}\n def dfs(i, buying):\n if i >= len(prices): return 0\n if (i, buying) in dp: return dp[(i, buying)]\n cooldown = dfs(i + 1, buying)\n if buying:\n buy = dfs(i + 1, not buying) - prices[i]\n dp[(i, buying)] = max(buy, cooldown)\n else:\n sell = dfs(i + 2, not buying) + prices[i]\n dp[(i, buying)] = max(sell, cooldown)\n return dp[(i, buying)]\n return dfs(0, True)" }, { "id": "nc-518", "problem_number": 518, "name": "Coin Change II", "pattern": "2-D DP", "difficulty": "Medium", "time_complexity": "O(N * amount)", "space_complexity": "O(amount)", "starter_code": "class Solution:\n def change(self, amount: int, coins: list[int]) -> int:\n pass", "description": "Return the number of combinations that make up the given amount using infinite coins of each denomination.", "examples": [ { "input": "amount = 5, coins = [1,2,5]", "output": "4" } ], "constraints": [ "1 <= coins.length <= 300", "0 <= amount <= 5000" ], "leetcode_url": "https://leetcode.com/problems/coin-change-ii/", "reference_solution": "class Solution:\n def change(self, amount: int, coins: list[int]) -> int:\n dp = [0] * (amount + 1)\n dp[0] = 1\n for c in coins:\n for a in range(c, amount + 1):\n dp[a] += dp[a - c]\n return dp[amount]" }, { "id": "nc-494", "problem_number": 494, "name": "Target Sum", "pattern": "2-D DP", "difficulty": "Medium", "time_complexity": "O(N * total)", "space_complexity": "O(total)", "starter_code": "class Solution:\n def findTargetSumWays(self, nums: list[int], target: int) -> int:\n pass", "description": "Assign '+' or '-' before each integer in nums so that the resulting expression evaluates to target.", "examples": [ { "input": "nums = [1,1,1,1,1], target = 3", "output": "5" } ], "constraints": [ "1 <= nums.length <= 20", "0 <= sum(nums[i]) <= 1000" ], "leetcode_url": "https://leetcode.com/problems/target-sum/", "reference_solution": "from collections import defaultdict\n\nclass Solution:\n def findTargetSumWays(self, nums: list[int], target: int) -> int:\n dp = defaultdict(int)\n dp[0] = 1\n for n in nums:\n nextDp = defaultdict(int)\n for cur, count in dp.items():\n nextDp[cur + n] += count\n nextDp[cur - n] += count\n dp = nextDp\n return dp[target]" }, { "id": "nc-97", "problem_number": 97, "name": "Interleaving String", "pattern": "2-D DP", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(M * N)", "starter_code": "class Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n pass", "description": "Given s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.", "examples": [ { "input": "s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbcbcac\"", "output": "true" } ], "constraints": [ "0 <= s1.length, s2.length <= 100", "0 <= s3.length <= 200" ], "leetcode_url": "https://leetcode.com/problems/interleaving-string/", "reference_solution": "class Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n if len(s1) + len(s2) != len(s3): return False\n dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)]\n dp[len(s1)][len(s2)] = True\n for i in range(len(s1), -1, -1):\n for j in range(len(s2), -1, -1):\n if i < len(s1) and s1[i] == s3[i + j] and dp[i + 1][j]:\n dp[i][j] = True\n if j < len(s2) and s2[j] == s3[i + j] and dp[i][j + 1]:\n dp[i][j] = True\n return dp[0][0]" }, { "id": "nc-329", "problem_number": 329, "name": "Longest Increasing Path in a Matrix", "pattern": "2-D DP", "difficulty": "Hard", "time_complexity": "O(M * N)", "space_complexity": "O(M * N)", "starter_code": "class Solution:\n def longestIncreasingPath(self, matrix: list[list[int]]) -> int:\n pass", "description": "Given an m x n integers matrix, return the length of the longest increasing path.", "examples": [ { "input": "matrix = [[9,9,4],[6,6,8],[2,1,1]]", "output": "4" } ], "constraints": [ "m == matrix.length", "n == matrix[i].length", "1 <= m, n <= 200" ], "leetcode_url": "https://leetcode.com/problems/longest-increasing-path-in-a-matrix/", "reference_solution": "class Solution:\n def longestIncreasingPath(self, matrix: list[list[int]]) -> int:\n ROWS, COLS = len(matrix), len(matrix[0])\n dp = {}\n def dfs(r, c, prevVal):\n if r < 0 or r == ROWS or c < 0 or c == COLS or matrix[r][c] <= prevVal:\n return 0\n if (r, c) in dp: return dp[(r, c)]\n res = 1\n for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n res = max(res, 1 + dfs(r + dr, c + dc, matrix[r][c]))\n dp[(r, c)] = res\n return res\n for r in range(ROWS):\n for c in range(COLS): dfs(r, c, -1)\n return max(dp.values())" }, { "id": "nc-115", "problem_number": 115, "name": "Distinct Subsequences", "pattern": "2-D DP", "difficulty": "Hard", "time_complexity": "O(M * N)", "space_complexity": "O(M * N)", "starter_code": "class Solution:\n def numDistinct(self, s: str, t: str) -> int:\n pass", "description": "Given two strings s and t, return the number of distinct subsequences of s which equals t.", "examples": [ { "input": "s = \"rabbbit\", t = \"rabbit\"", "output": "3" } ], "constraints": [ "1 <= s.length, t.length <= 1000" ], "leetcode_url": "https://leetcode.com/problems/distinct-subsequences/", "reference_solution": "class Solution:\n def numDistinct(self, s: str, t: str) -> int:\n cache = {}\n def dfs(i, j):\n if j == len(t): return 1\n if i == len(s): return 0\n if (i, j) in cache: return cache[(i, j)]\n if s[i] == t[j]:\n cache[(i, j)] = dfs(i + 1, j + 1) + dfs(i + 1, j)\n else:\n cache[(i, j)] = dfs(i + 1, j)\n return cache[(i, j)]\n return dfs(0, 0)" }, { "id": "nc-72", "problem_number": 72, "name": "Edit Distance", "pattern": "2-D DP", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(M * N)", "starter_code": "class Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n pass", "description": "Return minimum operations to convert word1 to word2 (insert, delete, or replace a character).", "examples": [ { "input": "word1 = \"horse\", word2 = \"ros\"", "output": "3" } ], "constraints": [ "0 <= word1.length, word2.length <= 500" ], "leetcode_url": "https://leetcode.com/problems/edit-distance/", "reference_solution": "class Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n dp = [[float(\"inf\")] * (len(word2) + 1) for _ in range(len(word1) + 1)]\n for j in range(len(word2) + 1): dp[len(word1)][j] = len(word2) - j\n for i in range(len(word1) + 1): dp[i][len(word2)] = len(word1) - i\n for i in range(len(word1) - 1, -1, -1):\n for j in range(len(word2) - 1, -1, -1):\n if word1[i] == word2[j]:\n dp[i][j] = dp[i + 1][j + 1]\n else:\n dp[i][j] = 1 + min(dp[i + 1][j], dp[i][j + 1], dp[i + 1][j + 1])\n return dp[0][0]" }, { "id": "nc-312", "problem_number": 312, "name": "Burst Balloons", "pattern": "2-D DP", "difficulty": "Hard", "time_complexity": "O(N^3)", "space_complexity": "O(N^2)", "starter_code": "class Solution:\n def maxCoins(self, nums: list[int]) -> int:\n pass", "description": "Burst balloon i to get nums[i - 1] * nums[i] * nums[i + 1] coins. Return the maximum coins you can collect.", "examples": [ { "input": "nums = [3,1,5,8]", "output": "167" } ], "constraints": [ "n == nums.length", "1 <= n <= 300" ], "leetcode_url": "https://leetcode.com/problems/burst-balloons/", "reference_solution": "class Solution:\n def maxCoins(self, nums: list[int]) -> int:\n nums = [1] + [n for n in nums if n > 0] + [1]\n n = len(nums)\n dp = [[0] * n for _ in range(n)]\n for length in range(1, n - 1):\n for left in range(0, n - length - 1):\n right = left + length + 1\n for i in range(left + 1, right):\n dp[left][right] = max(dp[left][right], nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right])\n return dp[0][n - 1]" }, { "id": "nc-10", "problem_number": 10, "name": "Regular Expression Matching", "pattern": "2-D DP", "difficulty": "Hard", "time_complexity": "O(M * N)", "space_complexity": "O(M * N)", "starter_code": "class Solution:\n def isMatch(self, s: str, p: str) -> bool:\n pass", "description": "Implement regular expression matching with support for '.' and '*'.", "examples": [ { "input": "s = \"aa\", p = \"a*\"", "output": "true" } ], "constraints": [ "1 <= s.length <= 20", "1 <= p.length <= 20" ], "leetcode_url": "https://leetcode.com/problems/regular-expression-matching/", "reference_solution": "class Solution:\n def isMatch(self, s: str, p: str) -> bool:\n cache = {}\n def dfs(i, j):\n if (i, j) in cache: return cache[(i, j)]\n if i >= len(s) and j >= len(p): return True\n if j >= len(p): return False\n match = i < len(s) and (s[i] == p[j] or p[j] == \".\")\n if (j + 1) < len(p) and p[j + 1] == \"*\":\n cache[(i, j)] = dfs(i, j + 2) or (match and dfs(i + 1, j))\n return cache[(i, j)]\n if match:\n cache[(i, j)] = dfs(i + 1, j + 1)\n return cache[(i, j)]\n cache[(i, j)] = False\n return False\n return dfs(0, 0)" }, { "id": "nc-53", "problem_number": 53, "name": "Maximum Subarray", "pattern": "Greedy", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def maxSubArray(self, nums: list[int]) -> int:\n pass", "description": "Given an integer array nums, find the subarray with the largest sum, and return its sum (Kadane's Algorithm).", "examples": [ { "input": "nums = [-2,1,-3,4,-1,2,1,-5,4]", "output": "6" } ], "constraints": [ "1 <= nums.length <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/maximum-subarray/", "reference_solution": "class Solution:\n def maxSubArray(self, nums: list[int]) -> int:\n maxSub = nums[0]\n curSum = 0\n for n in nums:\n if curSum < 0: curSum = 0\n curSum += n\n maxSub = max(maxSub, curSum)\n return maxSub" }, { "id": "nc-55", "problem_number": 55, "name": "Jump Game", "pattern": "Greedy", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def canJump(self, nums: list[int]) -> bool:\n pass", "description": "Determine if you are able to reach the last index starting at index 0.", "examples": [ { "input": "nums = [2,3,1,1,4]", "output": "true" } ], "constraints": [ "1 <= nums.length <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/jump-game/", "reference_solution": "class Solution:\n def canJump(self, nums: list[int]) -> bool:\n goal = len(nums) - 1\n for i in range(len(nums) - 2, -1, -1):\n if i + nums[i] >= goal: goal = i\n return goal == 0" }, { "id": "nc-45", "problem_number": 45, "name": "Jump Game II", "pattern": "Greedy", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def jump(self, nums: list[int]) -> int:\n pass", "description": "Return the minimum number of jumps to reach the last index.", "examples": [ { "input": "nums = [2,3,1,1,4]", "output": "2" } ], "constraints": [ "1 <= nums.length <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/jump-game-ii/", "reference_solution": "class Solution:\n def jump(self, nums: list[int]) -> int:\n res = 0\n l = r = 0\n while r < len(nums) - 1:\n farthest = 0\n for i in range(l, r + 1):\n farthest = max(farthest, i + nums[i])\n l = r + 1\n r = farthest\n res += 1\n return res" }, { "id": "nc-134", "problem_number": 134, "name": "Gas Station", "pattern": "Greedy", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def canCompleteCircuit(self, gas: list[int], cost: list[int]) -> int:\n pass", "description": "Return the starting gas station's index if you can travel around the circuit once, or -1 otherwise.", "examples": [ { "input": "gas = [1,2,3,4,5], cost = [3,4,5,1,2]", "output": "3" } ], "constraints": [ "n == gas.length == cost.length", "1 <= n <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/gas-station/", "reference_solution": "class Solution:\n def canCompleteCircuit(self, gas: list[int], cost: list[int]) -> int:\n if sum(gas) < sum(cost): return -1\n total = 0\n res = 0\n for i in range(len(gas)):\n total += (gas[i] - cost[i])\n if total < 0:\n total = 0\n res = i + 1\n return res" }, { "id": "nc-846", "problem_number": 846, "name": "Hand of Straights", "pattern": "Greedy", "difficulty": "Medium", "time_complexity": "O(N log N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def isNStraightHand(self, hand: list[int], groupSize: int) -> bool:\n pass", "description": "Determine if Alice can rearrange hand into groups of groupSize consecutive cards.", "examples": [ { "input": "hand = [1,2,3,6,2,3,4,7,8], groupSize = 3", "output": "true" } ], "constraints": [ "1 <= hand.length <= 10^4", "1 <= groupSize <= hand.length" ], "leetcode_url": "https://leetcode.com/problems/hand-of-straights/", "reference_solution": "from collections import Counter\nimport heapq\n\nclass Solution:\n def isNStraightHand(self, hand: list[int], groupSize: int) -> bool:\n if len(hand) % groupSize != 0: return False\n count = Counter(hand)\n minH = list(count.keys())\n heapq.heapify(minH)\n while minH:\n first = minH[0]\n for i in range(first, first + groupSize):\n if i not in count: return False\n count[i] -= 1\n if count[i] == 0:\n if i != minH[0]: return False\n heapq.heappop(minH)\n return True" }, { "id": "nc-1899", "problem_number": 1899, "name": "Merge Triplets to Form Target Triplet", "pattern": "Greedy", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def mergeTriplets(self, triplets: list[list[int]], target: list[int]) -> bool:\n pass", "description": "Return true if you can obtain target by merging triplets using component-wise maximum.", "examples": [ { "input": "triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]", "output": "true" } ], "constraints": [ "1 <= triplets.length <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/merge-triplets-to-form-target-triplet/", "reference_solution": "class Solution:\n def mergeTriplets(self, triplets: list[list[int]], target: list[int]) -> bool:\n good = set()\n for t in triplets:\n if t[0] > target[0] or t[1] > target[1] or t[2] > target[2]: continue\n for i, v in enumerate(t):\n if v == target[i]: good.add(i)\n return len(good) == 3" }, { "id": "nc-763", "problem_number": 763, "name": "Partition Labels", "pattern": "Greedy", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def partitionLabels(self, s: str) -> list[int]:\n pass", "description": "Partition s into as many parts as possible so that each letter appears in at most one part.", "examples": [ { "input": "s = \"ababcbacadefegdehijhklij\"", "output": "[9,7,8]" } ], "constraints": [ "1 <= s.length <= 500" ], "leetcode_url": "https://leetcode.com/problems/partition-labels/", "reference_solution": "class Solution:\n def partitionLabels(self, s: str) -> list[int]:\n lastIndex = {c: i for i, c in enumerate(s)}\n res = []\n size, end = 0, 0\n for i, c in enumerate(s):\n size += 1\n end = max(end, lastIndex[c])\n if i == end:\n res.append(size)\n size = 0\n return res" }, { "id": "nc-678", "problem_number": 678, "name": "Valid Parenthesis String", "pattern": "Greedy", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def checkValidString(self, s: str) -> bool:\n pass", "description": "Given a string s containing '(', ')' and '*', return true if s is valid (where '*' can be '(', ')' or empty).", "examples": [ { "input": "s = \"(*))\"", "output": "true" } ], "constraints": [ "1 <= s.length <= 100" ], "leetcode_url": "https://leetcode.com/problems/valid-parenthesis-string/", "reference_solution": "class Solution:\n def checkValidString(self, s: str) -> bool:\n leftMin, leftMax = 0, 0\n for c in s:\n if c == \"(\":\n leftMin, leftMax = leftMin + 1, leftMax + 1\n elif c == \")\":\n leftMin, leftMax = leftMin - 1, leftMax - 1\n else:\n leftMin, leftMax = leftMin - 1, leftMax + 1\n if leftMax < 0: return False\n if leftMin < 0: leftMin = 0\n return leftMin == 0" }, { "id": "nc-57", "problem_number": 57, "name": "Insert Interval", "pattern": "Intervals", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n pass", "description": "Insert newInterval into intervals (sorted by start) and merge overlapping intervals.", "examples": [ { "input": "intervals = [[1,3],[6,9]], newInterval = [2,5]", "output": "[[1,5],[6,9]]" } ], "constraints": [ "0 <= intervals.length <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/insert-interval/", "reference_solution": "class Solution:\n def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n res = []\n for i in range(len(intervals)):\n if newInterval[1] < intervals[i][0]:\n res.append(newInterval)\n return res + intervals[i:]\n elif newInterval[0] > intervals[i][1]:\n res.append(intervals[i])\n else:\n newInterval = [min(newInterval[0], intervals[i][0]), max(newInterval[1], intervals[i][1])]\n res.append(newInterval)\n return res" }, { "id": "nc-56", "problem_number": 56, "name": "Merge Intervals", "pattern": "Intervals", "difficulty": "Medium", "time_complexity": "O(N log N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def merge(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n pass", "description": "Merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals.", "examples": [ { "input": "intervals = [[1,3],[2,6],[8,10],[15,18]]", "output": "[[1,6],[8,10],[15,18]]" } ], "constraints": [ "1 <= intervals.length <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/merge-intervals/", "reference_solution": "class Solution:\n def merge(self, intervals: list[list[int]]) -> list[list[int]]:\n intervals.sort(key=lambda i: i[0])\n output = [intervals[0]]\n for start, end in intervals[1:]:\n lastEnd = output[-1][1]\n if start <= lastEnd:\n output[-1][1] = max(lastEnd, end)\n else:\n output.append([start, end])\n return output" }, { "id": "nc-435", "problem_number": 435, "name": "Non-overlapping Intervals", "pattern": "Intervals", "difficulty": "Medium", "time_complexity": "O(N log N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int:\n pass", "description": "Return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.", "examples": [ { "input": "intervals = [[1,2],[2,3],[3,4],[1,3]]", "output": "1" } ], "constraints": [ "1 <= intervals.length <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/non-overlapping-intervals/", "reference_solution": "class Solution:\n def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int:\n intervals.sort()\n res = 0\n prevEnd = intervals[0][1]\n for start, end in intervals[1:]:\n if start >= prevEnd:\n prevEnd = end\n else:\n res += 1\n prevEnd = min(end, prevEnd)\n return res" }, { "id": "nc-252", "problem_number": 252, "name": "Meeting Rooms", "pattern": "Intervals", "difficulty": "Easy", "time_complexity": "O(N log N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def canAttendMeetings(self, intervals: list[list[int]]) -> bool:\n pass", "description": "Given an array of meeting time intervals, determine if a person could attend all meetings.", "examples": [ { "input": "intervals = [[0,30],[5,10],[15,20]]", "output": "false" } ], "constraints": [ "0 <= intervals.length <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/meeting-rooms/", "reference_solution": "class Solution:\n def canAttendMeetings(self, intervals: list[list[int]]) -> bool:\n intervals.sort(key=lambda i: i[0])\n for i in range(1, len(intervals)):\n if intervals[i][0] < intervals[i - 1][1]: return False\n return True" }, { "id": "nc-253", "problem_number": 253, "name": "Meeting Rooms II", "pattern": "Intervals", "difficulty": "Medium", "time_complexity": "O(N log N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def minMeetingRooms(self, intervals: list[list[int]]) -> int:\n pass", "description": "Given an array of meeting time intervals, find the minimum number of conference rooms required.", "examples": [ { "input": "intervals = [[0,30],[5,10],[15,20]]", "output": "2" } ], "constraints": [ "1 <= intervals.length <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/meeting-rooms-ii/", "reference_solution": "class Solution:\n def minMeetingRooms(self, intervals: list[list[int]]) -> int:\n start = sorted([i[0] for i in intervals])\n end = sorted([i[1] for i in intervals])\n res, count = 0, 0\n s, e = 0, 0\n while s < len(intervals):\n if start[s] < end[e]:\n count += 1\n s += 1\n else:\n count -= 1\n e += 1\n res = max(res, count)\n return res" }, { "id": "nc-1851", "problem_number": 1851, "name": "Minimum Interval to Include Each Query", "pattern": "Intervals", "difficulty": "Hard", "time_complexity": "O(N log N + Q log Q)", "space_complexity": "O(N + Q)", "starter_code": "class Solution:\n def minInterval(self, intervals: list[list[int]], queries: list[int]) -> list[int]:\n pass", "description": "For each query, find the size of the smallest interval that contains that query value.", "examples": [ { "input": "intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]", "output": "[3,3,1,4]" } ], "constraints": [ "1 <= intervals.length <= 10^5", "1 <= queries.length <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/minimum-interval-to-include-each-query/", "reference_solution": "import heapq\n\nclass Solution:\n def minInterval(self, intervals: list[list[int]], queries: list[int]) -> list[int]:\n intervals.sort()\n minHeap = []\n res = {}\n i = 0\n for q in sorted(queries):\n while i < len(intervals) and intervals[i][0] <= q:\n l, r = intervals[i]\n heapq.heappush(minHeap, (r - l + 1, r))\n i += 1\n while minHeap and minHeap[0][1] < q:\n heapq.heappop(minHeap)\n res[q] = minHeap[0][0] if minHeap else -1\n return [res[q] for q in queries]" }, { "id": "nc-48", "problem_number": 48, "name": "Rotate Image", "pattern": "Math & Geometry", "difficulty": "Medium", "time_complexity": "O(N^2)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def rotate(self, matrix: list[list[int]]) -> None:\n pass", "description": "Rotate the n x n 2D matrix clockwise by 90 degrees in-place.", "examples": [ { "input": "matrix = [[1,2,3],[4,5,6],[7,8,9]]", "output": "[[7,4,1],[8,5,2],[9,6,3]]" } ], "constraints": [ "n == matrix.length == matrix[i].length", "1 <= n <= 20" ], "leetcode_url": "https://leetcode.com/problems/rotate-image/", "reference_solution": "class Solution:\n def rotate(self, matrix: list[list[int]]) -> None:\n l, r = 0, len(matrix) - 1\n while l < r:\n for i in range(r - l):\n top, bottom = l, r\n topLeft = matrix[top][l + i]\n matrix[top][l + i] = matrix[bottom - i][l]\n matrix[bottom - i][l] = matrix[bottom][r - i]\n matrix[bottom][r - i] = matrix[top + i][r]\n matrix[top + i][r] = topLeft\n r -= 1\n l += 1" }, { "id": "nc-54", "problem_number": 54, "name": "Spiral Matrix", "pattern": "Math & Geometry", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def spiralOrder(self, matrix: list[list[int]]) -> list[int]:\n pass", "description": "Return all elements of the m x n matrix in spiral order.", "examples": [ { "input": "matrix = [[1,2,3],[4,5,6],[7,8,9]]", "output": "[1,2,3,6,9,8,7,4,5]" } ], "constraints": [ "m == matrix.length", "n == matrix[i].length", "1 <= m, n <= 10" ], "leetcode_url": "https://leetcode.com/problems/spiral-matrix/", "reference_solution": "class Solution:\n def spiralOrder(self, matrix: list[list[int]]) -> list[int]:\n res = []\n left, right = 0, len(matrix[0])\n top, bottom = 0, len(matrix)\n while left < right and top < bottom:\n for i in range(left, right): res.append(matrix[top][i])\n top += 1\n for i in range(top, bottom): res.append(matrix[i][right - 1])\n right -= 1\n if not (left < right and top < bottom): break\n for i in range(right - 1, left - 1, -1): res.append(matrix[bottom - 1][i])\n bottom -= 1\n for i in range(bottom - 1, top - 1, -1): res.append(matrix[i][left])\n left += 1\n return res" }, { "id": "nc-73", "problem_number": 73, "name": "Set Matrix Zeroes", "pattern": "Math & Geometry", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def setZeroes(self, matrix: list[list[int]]) -> None:\n pass", "description": "Given an m x n integer matrix, if an element is 0, set its entire row and column to 0's in place.", "examples": [ { "input": "matrix = [[1,1,1],[1,0,1],[1,1,1]]", "output": "[[1,0,1],[0,0,0],[1,0,1]]" } ], "constraints": [ "m == matrix.length", "n == matrix[0].length", "1 <= m, n <= 200" ], "leetcode_url": "https://leetcode.com/problems/set-matrix-zeroes/", "reference_solution": "class Solution:\n def setZeroes(self, matrix: list[list[int]]) -> None:\n ROWS, COLS = len(matrix), len(matrix[0])\n rowZero = False\n for r in range(ROWS):\n for c in range(COLS):\n if matrix[r][c] == 0:\n matrix[0][c] = 0\n if r > 0: matrix[r][0] = 0\n else: rowZero = True\n for r in range(1, ROWS):\n for c in range(1, COLS):\n if matrix[0][c] == 0 or matrix[r][0] == 0:\n matrix[r][c] = 0\n if matrix[0][0] == 0:\n for r in range(ROWS): matrix[r][0] = 0\n if rowZero:\n for c in range(COLS): matrix[0][c] = 0" }, { "id": "nc-202", "problem_number": 202, "name": "Happy Number", "pattern": "Math & Geometry", "difficulty": "Easy", "time_complexity": "O(log N)", "space_complexity": "O(log N)", "starter_code": "class Solution:\n def isHappy(self, n: int) -> bool:\n pass", "description": "Determine if a number n is happy by continually replacing it with the sum of the squares of its digits.", "examples": [ { "input": "n = 19", "output": "true" } ], "constraints": [ "1 <= n <= 2^31 - 1" ], "leetcode_url": "https://leetcode.com/problems/happy-number/", "reference_solution": "class Solution:\n def isHappy(self, n: int) -> bool:\n visit = set()\n while n not in visit:\n visit.add(n)\n n = sum(int(digit) ** 2 for digit in str(n))\n if n == 1: return True\n return False" }, { "id": "nc-66", "problem_number": 66, "name": "Plus One", "pattern": "Math & Geometry", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def plusOne(self, digits: list[int]) -> list[int]:\n pass", "description": "Increment the large integer represented by an array of digits by one.", "examples": [ { "input": "digits = [1,2,3]", "output": "[1,2,4]" } ], "constraints": [ "1 <= digits.length <= 100" ], "leetcode_url": "https://leetcode.com/problems/plus-one/", "reference_solution": "class Solution:\n def plusOne(self, digits: list[int]) -> list[int]:\n for i in reversed(range(len(digits))):\n if digits[i] == 9: digits[i] = 0\n else:\n digits[i] += 1\n return digits\n return [1] + digits" }, { "id": "nc-50", "problem_number": 50, "name": "Pow(x, n)", "pattern": "Math & Geometry", "difficulty": "Medium", "time_complexity": "O(log N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def myPow(self, x: float, n: int) -> float:\n pass", "description": "Implement pow(x, n), which calculates x raised to the power n.", "examples": [ { "input": "x = 2.00000, n = 10", "output": "1024.00000" } ], "constraints": [ "-100.0 < x < 100.0", "-2^31 <= n <= 2^31-1" ], "leetcode_url": "https://leetcode.com/problems/powx-n/", "reference_solution": "class Solution:\n def myPow(self, x: float, n: int) -> float:\n def helper(x, n):\n if x == 0: return 0\n if n == 0: return 1\n res = helper(x * x, n // 2)\n return x * res if n % 2 else res\n res = helper(x, abs(n))\n return res if n >= 0 else 1 / res" }, { "id": "nc-43", "problem_number": 43, "name": "Multiply Strings", "pattern": "Math & Geometry", "difficulty": "Medium", "time_complexity": "O(M * N)", "space_complexity": "O(M + N)", "starter_code": "class Solution:\n def multiply(self, num1: str, num2: str) -> str:\n pass", "description": "Given two non-negative integers num1 and num2 represented as strings, return their product as a string.", "examples": [ { "input": "num1 = \"2\", num2 = \"3\"", "output": "\"6\"" } ], "constraints": [ "1 <= num1.length, num2.length <= 200" ], "leetcode_url": "https://leetcode.com/problems/multiply-strings/", "reference_solution": "class Solution:\n def multiply(self, num1: str, num2: str) -> str:\n if \"0\" in [num1, num2]: return \"0\"\n res = [0] * (len(num1) + len(num2))\n num1, num2 = num1[::-1], num2[::-1]\n for i1 in range(len(num1)):\n for i2 in range(len(num2)):\n digit = int(num1[i1]) * int(num2[i2])\n res[i1 + i2] += digit\n res[i1 + i2 + 1] += res[i1 + i2] // 10\n res[i1 + i2] = res[i1 + i2] % 10\n res, beg = res[::-1], 0\n while beg < len(res) and res[beg] == 0: beg += 1\n return \"\".join(map(str, res[beg:]))" }, { "id": "nc-2013", "problem_number": 2013, "name": "Detect Squares", "pattern": "Math & Geometry", "difficulty": "Medium", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class DetectSquares:\n def __init__(self):\n pass\n def add(self, point: list[int]) -> None:\n pass\n def count(self, point: list[int]) -> int:\n pass", "description": "Design a data structure that adds points and counts axis-aligned squares with a given query point.", "examples": [ { "input": "[\"DetectSquares\",\"add\",\"add\",\"add\",\"count\",\"count\",\"add\",\"count\"]", "output": "[null,null,null,null,1,0,null,2]" } ], "constraints": [ "point.length == 2", "0 <= x, y <= 1000" ], "leetcode_url": "https://leetcode.com/problems/detect-squares/", "reference_solution": "from collections import defaultdict\n\nclass DetectSquares:\n def __init__(self):\n self.ptsCount = defaultdict(int)\n self.pts = []\n def add(self, point: list[int]) -> None:\n self.ptsCount[tuple(point)] += 1\n self.pts.append(point)\n def count(self, point: list[int]) -> int:\n res = 0\n px, py = point\n for x, y in self.pts:\n if (abs(py - y) != abs(px - x)) or x == px or y == py: continue\n res += self.ptsCount[(x, py)] * self.ptsCount[(px, y)]\n return res" }, { "id": "nc-136", "problem_number": 136, "name": "Single Number", "pattern": "Bit Manipulation", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def singleNumber(self, nums: list[int]) -> int:\n pass", "description": "Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.", "examples": [ { "input": "nums = [2,2,1]", "output": "1" } ], "constraints": [ "1 <= nums.length <= 3 * 10^4" ], "leetcode_url": "https://leetcode.com/problems/single-number/", "reference_solution": "class Solution:\n def singleNumber(self, nums: list[int]) -> int:\n res = 0\n for n in nums: res ^= n\n return res" }, { "id": "nc-191", "problem_number": 191, "name": "Number of 1 Bits", "pattern": "Bit Manipulation", "difficulty": "Easy", "time_complexity": "O(1)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def hammingWeight(self, n: int) -> int:\n pass", "description": "Return the number of set bits (Hamming weight) that the integer n has.", "examples": [ { "input": "n = 11", "output": "3" } ], "constraints": [ "1 <= n <= 2^31 - 1" ], "leetcode_url": "https://leetcode.com/problems/number-of-1-bits/", "reference_solution": "class Solution:\n def hammingWeight(self, n: int) -> int:\n res = 0\n while n:\n n &= (n - 1)\n res += 1\n return res" }, { "id": "nc-338", "problem_number": 338, "name": "Counting Bits", "pattern": "Bit Manipulation", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(N)", "starter_code": "class Solution:\n def countBits(self, n: int) -> list[int]:\n pass", "description": "Given an integer n, return an array ans of length n + 1 such that ans[i] is the number of 1's in the binary representation of i.", "examples": [ { "input": "n = 5", "output": "[0,1,1,2,1,2]" } ], "constraints": [ "0 <= n <= 10^5" ], "leetcode_url": "https://leetcode.com/problems/counting-bits/", "reference_solution": "class Solution:\n def countBits(self, n: int) -> list[int]:\n dp = [0] * (n + 1)\n offset = 1\n for i in range(1, n + 1):\n if offset * 2 == i: offset = i\n dp[i] = 1 + dp[i - offset]\n return dp" }, { "id": "nc-190", "problem_number": 190, "name": "Reverse Bits", "pattern": "Bit Manipulation", "difficulty": "Easy", "time_complexity": "O(1)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def reverseBits(self, n: int) -> int:\n pass", "description": "Reverse bits of a given 32 bits unsigned integer.", "examples": [ { "input": "n = 00000010100101000001111010011100", "output": "964176192 (00111001011110000010100101000000)" } ], "constraints": [ "The input must be a binary string of length 32" ], "leetcode_url": "https://leetcode.com/problems/reverse-bits/", "reference_solution": "class Solution:\n def reverseBits(self, n: int) -> int:\n res = 0\n for i in range(32):\n bit = (n >> i) & 1\n res |= (bit << (31 - i))\n return res" }, { "id": "nc-268", "problem_number": 268, "name": "Missing Number", "pattern": "Bit Manipulation", "difficulty": "Easy", "time_complexity": "O(N)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def missingNumber(self, nums: list[int]) -> int:\n pass", "description": "Given an array nums containing n distinct numbers in range [0, n], return the only number in the range that is missing.", "examples": [ { "input": "nums = [3,0,1]", "output": "2" } ], "constraints": [ "n == nums.length", "1 <= n <= 10^4" ], "leetcode_url": "https://leetcode.com/problems/missing-number/", "reference_solution": "class Solution:\n def missingNumber(self, nums: list[int]) -> int:\n res = len(nums)\n for i in range(len(nums)):\n res += (i - nums[i])\n return res" }, { "id": "nc-371", "problem_number": 371, "name": "Sum of Two Integers", "pattern": "Bit Manipulation", "difficulty": "Medium", "time_complexity": "O(1)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def getSum(self, a: int, b: int) -> int:\n pass", "description": "Given two integers a and b, return the sum of the two integers without using the operators + and -.", "examples": [ { "input": "a = 1, b = 2", "output": "3" } ], "constraints": [ "-1000 <= a, b <= 1000" ], "leetcode_url": "https://leetcode.com/problems/sum-of-two-integers/", "reference_solution": "class Solution:\n def getSum(self, a: int, b: int) -> int:\n mask = 0xFFFFFFFF\n while (b & mask) != 0:\n carry = (a & b) << 1\n a = a ^ b\n b = carry\n return (a & mask) if b > 0 else a" }, { "id": "nc-7", "problem_number": 7, "name": "Reverse Integer", "pattern": "Bit Manipulation", "difficulty": "Medium", "time_complexity": "O(log X)", "space_complexity": "O(1)", "starter_code": "class Solution:\n def reverse(self, x: int) -> int:\n pass", "description": "Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes overflow, return 0.", "examples": [ { "input": "x = 123", "output": "321" } ], "constraints": [ "-2^31 <= x <= 2^31 - 1" ], "leetcode_url": "https://leetcode.com/problems/reverse-integer/", "reference_solution": "class Solution:\n def reverse(self, x: int) -> int:\n sign = -1 if x < 0 else 1\n x = abs(x)\n res = int(str(x)[::-1]) * sign\n return res if -2**31 <= res <= 2**31 - 1 else 0" } ];
// Canonical 150 LeetCode / NeetCode DSA Review Dataset
// Pre-seeded with rich descriptions, examples, constraints, starter code, and reference solutions.
// Zero-cold-start, instant O(1) offline and guest-mode support.
export interface CatalogExample {
input: string;
output: string;
explanation?: string;
}
export interface CatalogProblem {
id: string;
problem_number: number;
name: string;
pattern: string;
difficulty: 'Easy' | 'Medium' | 'Hard';
time_complexity: string;
space_complexity: string;
starter_code: string;
description: string;
examples: CatalogExample[];
constraints: string[];
leetcode_url: string;
reference_solution?: string;
}
export const NEETCODE_150_DATA: CatalogProblem[] = [
{
"id": "nc-217",
"problem_number": 217,
"name": "Contains Duplicate",
"pattern": "Arrays & Hashing",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def containsDuplicate(self, nums: list[int]) -> bool:\n pass",
"description": "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.",
"examples": [
{
"input": "nums = [1,2,3,1]",
"output": "true"
},
{
"input": "nums = [1,2,3,4]",
"output": "false"
}
],
"constraints": [
"1 <= nums.length <= 10^5",
"-10^9 <= nums[i] <= 10^9"
],
"leetcode_url": "https://leetcode.com/problems/contains-duplicate/",
"reference_solution": "class Solution:\n def containsDuplicate(self, nums: list[int]) -> bool:\n seen = set()\n for n in nums:\n if n in seen:\n return True\n seen.add(n)\n return False"
},
{
"id": "nc-242",
"problem_number": 242,
"name": "Valid Anagram",
"pattern": "Arrays & Hashing",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n pass",
"description": "Given two strings s and t, return true if t is an anagram of s, and false otherwise.",
"examples": [
{
"input": "s = \"anagram\", t = \"nagaram\"",
"output": "true"
},
{
"input": "s = \"rat\", t = \"car\"",
"output": "false"
}
],
"constraints": [
"1 <= s.length, t.length <= 5 * 10^4",
"s and t consist of lowercase English letters."
],
"leetcode_url": "https://leetcode.com/problems/valid-anagram/",
"reference_solution": "class Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n if len(s) != len(t):\n return False\n counts = {}\n for char in s:\n counts[char] = counts.get(char, 0) + 1\n for char in t:\n if char not in counts or counts[char] == 0:\n return False\n counts[char] -= 1\n return True"
},
{
"id": "nc-1",
"problem_number": 1,
"name": "Two Sum",
"pattern": "Arrays & Hashing",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def twoSum(self, nums: list[int], target: int) -> list[int]:\n pass",
"description": "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.",
"examples": [
{
"input": "nums = [2,7,11,15], target = 9",
"output": "[0,1]"
}
],
"constraints": [
"2 <= nums.length <= 10^4",
"-10^9 <= nums[i] <= 10^9",