Created
          July 11, 2025 10:38 
        
      - 
      
- 
        Save argaghulamahmad/cb291fb814a042834178886e11c69c7b to your computer and use it in GitHub Desktop. 
      This file has been truncated, but you can view the full file.
    
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | { | |
| "version": "1.0", | |
| "timestamp": 1752229082482, | |
| "exportDate": "2025-07-11T10:18:02.482Z", | |
| "totalCollections": 5, | |
| "totalSnippets": 3637, | |
| "collections": [ | |
| { | |
| "name": "Leet Code Must Learn - Chat GPT", | |
| "description": "", | |
| "color": "#14B8A6", | |
| "timestamp": 1752223423902, | |
| "snippetCount": 32, | |
| "id": 2 | |
| }, | |
| { | |
| "name": "Getting Started", | |
| "description": "Default collection with sample code snippets to help you get started", | |
| "color": "#3B82F6", | |
| "timestamp": 1752218065669, | |
| "snippetCount": 3, | |
| "id": 3 | |
| }, | |
| { | |
| "name": "Walk CC Solutions", | |
| "description": "", | |
| "color": "#EF4444", | |
| "timestamp": 1752218288496, | |
| "snippetCount": 3230, | |
| "id": 4 | |
| }, | |
| { | |
| "name": "Top 150 Interview Questions - Leet Code Explore", | |
| "description": "", | |
| "color": "#d0b3b8", | |
| "timestamp": 1752223412882, | |
| "snippetCount": 186, | |
| "id": 5 | |
| }, | |
| { | |
| "name": "Data Structures and Algorithms - Leet Code Explore", | |
| "description": "", | |
| "color": "#6a6ce2", | |
| "timestamp": 1752223386601, | |
| "snippetCount": 186, | |
| "id": 6 | |
| } | |
| ], | |
| "snippets": [ | |
| { | |
| "code": "class Solution:\n def twoSum(self, nums: list[int], target: int) -> list[int]:\n numToIndex = {}\n\n for i, num in enumerate(nums):\n if target - num in numToIndex:\n return numToIndex[target - num], i\n numToIndex[num] = i\n", | |
| "title": "1. Two Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065670, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 4 | |
| }, | |
| { | |
| "code": "class Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n dummy = ListNode(0)\n curr = dummy\n carry = 0\n\n while carry or l1 or l2:\n if l1:\n carry += l1.val\n l1 = l1.next\n if l2:\n carry += l2.val\n l2 = l2.next\n curr.next = ListNode(carry % 10)\n carry //= 10\n curr = curr.next\n\n return dummy.next\n", | |
| "title": "2. Add Two Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065679, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 5 | |
| }, | |
| { | |
| "code": "class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n ans = 0\n count = collections.Counter()\n\n l = 0\n for r, c in enumerate(s):\n count[c] += 1\n while count[c] > 1:\n count[s[l]] -= 1\n l += 1\n ans = max(ans, r - l + 1)\n\n return ans\n", | |
| "title": "3. Longest Substring Without Repeating Characters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065680, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 6 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestPalindrome(self, s: str) -> str:\n if not s:\n return ''\n\n # (start, end) indices of the longest palindrome in s\n indices = [0, 0]\n\n def extend(s: str, i: int, j: int) -> tuple[int, int]:\n \"\"\"\n Returns the (start, end) indices of the longest palindrome extended from\n the substring s[i..j].\n \"\"\"\n while i >= 0 and j < len(s):\n if s[i] != s[j]:\n break\n i -= 1\n j += 1\n return i + 1, j - 1\n\n for i in range(len(s)):\n l1, r1 = extend(s, i, i)\n if r1 - l1 > indices[1] - indices[0]:\n indices = l1, r1\n if i + 1 < len(s) and s[i] == s[i + 1]:\n l2, r2 = extend(s, i, i + 1)\n if r2 - l2 > indices[1] - indices[0]:\n indices = l2, r2\n\n return s[indices[0]:indices[1] + 1]\n", | |
| "title": "5. Longest Palindromic Substring", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065680, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 7 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxArea(self, height: list[int]) -> int:\n ans = 0\n l = 0\n r = len(height) - 1\n\n while l < r:\n minHeight = min(height[l], height[r])\n ans = max(ans, minHeight * (r - l))\n if height[l] < height[r]:\n l += 1\n else:\n r -= 1\n\n return ans\n", | |
| "title": "11. Container With Most Water", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065680, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 8 | |
| }, | |
| { | |
| "code": "class Solution:\n def threeSum(self, nums: list[int]) -> list[list[int]]:\n if len(nums) < 3:\n return []\n\n ans = []\n\n nums.sort()\n\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n # Choose nums[i] as the first number in the triplet, then search the\n # remaining numbers in [i + 1, n - 1].\n l = i + 1\n r = len(nums) - 1\n while l < r:\n summ = nums[i] + nums[l] + nums[r]\n if summ == 0:\n ans.append((nums[i], nums[l], nums[r]))\n l += 1\n r -= 1\n while nums[l] == nums[l - 1] and l < r:\n l += 1\n while nums[r] == nums[r + 1] and l < r:\n r -= 1\n elif summ < 0:\n l += 1\n else:\n r -= 1\n\n return ans\n", | |
| "title": "15. 3Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065681, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 9 | |
| }, | |
| { | |
| "code": "class Solution:\n def isValid(self, s: str) -> bool:\n stack = []\n\n for c in s:\n if c == '(':\n stack.append(')')\n elif c == '{':\n stack.append('}')\n elif c == '[':\n stack.append(']')\n elif not stack or stack.pop() != c:\n return False\n\n return not stack\n", | |
| "title": "20. Valid Parentheses", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065681, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 10 | |
| }, | |
| { | |
| "code": "class Solution:\n def mergeTwoLists(\n self,\n list1: ListNode | None,\n list2: ListNode | None,\n ) -> ListNode | None:\n if not list1 or not list2:\n return list1 if list1 else list2\n if list1.val > list2.val:\n list1, list2 = list2, list1\n list1.next = self.mergeTwoLists(list1.next, list2)\n return list1\n", | |
| "title": "21. Merge Two Sorted Lists", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065681, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 11 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeDuplicates(self, nums: list[int]) -> int:\n i = 0\n\n for num in nums:\n if i < 1 or num > nums[i - 1]:\n nums[i] = num\n i += 1\n\n return i\n", | |
| "title": "26. Remove Duplicates from Sorted Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065682, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 12 | |
| }, | |
| { | |
| "code": "class Solution:\n def search(self, nums: list[int], target: int) -> int:\n l = 0\n r = len(nums) - 1\n\n while l <= r:\n m = (l + r) // 2\n if nums[m] == target:\n return m\n if nums[l] <= nums[m]: # nums[l..m] are sorted.\n if nums[l] <= target < nums[m]:\n r = m - 1\n else:\n l = m + 1\n else: # nums[m..n - 1] are sorted.\n if nums[m] < target <= nums[r]:\n l = m + 1\n else:\n r = m - 1\n\n return -1\n", | |
| "title": "33. Search in Rotated Sorted Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065682, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 13 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxSubArray(self, nums: list[int]) -> int:\n # dp[i] := the maximum sum subarray ending in i\n dp = [0] * len(nums)\n\n dp[0] = nums[0]\n for i in range(1, len(nums)):\n dp[i] = max(nums[i], dp[i - 1] + nums[i])\n\n return max(dp)\n", | |
| "title": "53. Maximum Subarray", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065683, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 14 | |
| }, | |
| { | |
| "code": "class Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n # dp[i][j] := the number of unique paths from (0, 0) to (i, j)\n dp = [[1] * n for _ in range(m)]\n\n for i in range(1, m):\n for j in range(1, n):\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\n\n return dp[-1][-1]\n", | |
| "title": "62. Unique Paths", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065683, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 15 | |
| }, | |
| { | |
| "code": "class Solution:\n def climbStairs(self, n: int) -> int:\n # dp[i] := the number of ways to climb to the i-th stair\n dp = [1, 1] + [0] * (n - 1)\n\n for i in range(2, n + 1):\n dp[i] = dp[i - 1] + dp[i - 2]\n\n return dp[n]\n", | |
| "title": "70. Climbing Stairs", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065683, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 16 | |
| }, | |
| { | |
| "code": "class Solution:\n def subsets(self, nums: list[int]) -> list[list[int]]:\n ans = []\n\n def dfs(s: int, path: list[int]) -> None:\n ans.append(path)\n\n for i in range(s, len(nums)):\n dfs(i + 1, path + [nums[i]])\n\n dfs(0, [])\n return ans\n", | |
| "title": "78. Subsets", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065684, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 17 | |
| }, | |
| { | |
| "code": "class Solution:\n def isValidBST(self, root: TreeNode | None) -> bool:\n def isValidBST(root: TreeNode | None,\n minNode: TreeNode | None, maxNode: TreeNode | None) -> bool:\n if not root:\n return True\n if minNode and root.val <= minNode.val:\n return False\n if maxNode and root.val >= maxNode.val:\n return False\n\n return (isValidBST(root.left, minNode, root) and\n isValidBST(root.right, root, maxNode))\n\n return isValidBST(root, None, None)\n", | |
| "title": "98. Validate Binary Search Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065684, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 18 | |
| }, | |
| { | |
| "code": "class Solution:\n def isSymmetric(self, root: TreeNode | None) -> bool:\n def isSymmetric(p: TreeNode | None, q: TreeNode | None) -> bool:\n if not p or not q:\n return p == q\n return (p.val == q.val and\n isSymmetric(p.left, q.right) and\n isSymmetric(p.right, q.left))\n\n return isSymmetric(root, root)\n", | |
| "title": "101. Symmetric Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065684, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 19 | |
| }, | |
| { | |
| "code": "class Solution:\n def levelOrder(self, root: TreeNode | None) -> list[list[int]]:\n if not root:\n return []\n\n ans = []\n q = collections.deque([root])\n\n while q:\n currLevel = []\n for _ in range(len(q)):\n node = q.popleft()\n currLevel.append(node.val)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n ans.append(currLevel)\n\n return ans\n", | |
| "title": "102. Binary Tree Level Order Traversal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065685, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 20 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxDepth(self, root: TreeNode | None) -> int:\n if not root:\n return 0\n return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))\n", | |
| "title": "104. Maximum Depth of Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065686, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 21 | |
| }, | |
| { | |
| "code": "class Solution:\n def ladderLength(\n self,\n beginWord: str,\n endWord: str,\n wordList: list[str],\n ) -> int:\n wordSet = set(wordList)\n if endWord not in wordSet:\n return 0\n\n q = collections.deque([beginWord])\n\n step = 1\n while q:\n for _ in range(len(q)):\n wordList = list(q.popleft())\n for i, cache in enumerate(wordList):\n for c in string.ascii_lowercase:\n wordList[i] = c\n word = ''.join(wordList)\n if word == endWord:\n return step + 1\n if word in wordSet:\n q.append(word)\n wordSet.remove(word)\n wordList[i] = cache\n step += 1\n\n return 0\n", | |
| "title": "127. Word Ladder", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065686, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 22 | |
| }, | |
| { | |
| "code": "class Solution:\n def cloneGraph(self, node: 'Node') -> 'Node':\n if not node:\n return None\n\n q = collections.deque([node])\n map = {node: Node(node.val)}\n\n while q:\n u = q.popleft()\n for v in u.neighbors:\n if v not in map:\n map[v] = Node(v.val)\n q.append(v)\n map[u].neighbors.append(map[v])\n\n return map[node]\n", | |
| "title": "133. Clone Graph", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065686, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 23 | |
| }, | |
| { | |
| "code": "class Solution:\n def wordBreak(self, s: str, wordDict: list[str]) -> bool:\n wordSet = set(wordDict)\n\n @functools.lru_cache(None)\n def wordBreak(s: str) -> bool:\n \"\"\"Returns True if s can be segmented.\"\"\"\n if s in wordSet:\n return True\n return any(s[:i] in wordSet and wordBreak(s[i:]) for i in range(len(s)))\n\n return wordBreak(s)\n", | |
| "title": "139. Word Break", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065687, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 24 | |
| }, | |
| { | |
| "code": "class Solution:\n def rob(self, nums: list[int]) -> int:\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n\n # dp[i]:= max money of robbing nums[0..i]\n dp = [0] * len(nums)\n dp[0] = nums[0]\n dp[1] = max(nums[0], nums[1])\n\n for i in range(2, len(nums)):\n dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])\n\n return dp[-1]\n", | |
| "title": "198. House Robber", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065687, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 25 | |
| }, | |
| { | |
| "code": "class Solution:\n def numIslands(self, grid: list[list[str]]) -> int:\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(grid)\n n = len(grid[0])\n\n def bfs(r, c):\n q = collections.deque([(r, c)])\n grid[r][c] = '2' # Mark '2' as visited.\n while q:\n i, j = q.popleft()\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if grid[x][y] != '1':\n continue\n q.append((x, y))\n grid[x][y] = '2' # Mark '2' as visited.\n\n ans = 0\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == '1':\n bfs(i, j)\n ans += 1\n\n return ans\n", | |
| "title": "200. Number of Islands", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065687, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 26 | |
| }, | |
| { | |
| "code": "from enum import Enum\n\n\nclass State(Enum):\n INIT = 0\n VISITING = 1\n VISITED = 2\n\n\nclass Solution:\n def canFinish(self, numCourses: int, prerequisites: list[list[int]]) -> bool:\n graph = [[] for _ in range(numCourses)]\n states = [State.INIT] * numCourses\n\n for v, u in prerequisites:\n graph[u].append(v)\n\n def hasCycle(u: int) -> bool:\n if states[u] == State.VISITING:\n return True\n if states[u] == State.VISITED:\n return False\n states[u] = State.VISITING\n if any(hasCycle(v) for v in graph[u]):\n return True\n states[u] = State.VISITED\n return False\n\n return not any(hasCycle(i) for i in range(numCourses))\n", | |
| "title": "207. Course Schedule", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065688, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 27 | |
| }, | |
| { | |
| "code": "class Solution:\n def lowestCommonAncestor(\n self,\n root: 'TreeNode',\n p: 'TreeNode',\n q: 'TreeNode',\n ) -> 'TreeNode':\n if root.val > max(p.val, q.val):\n return self.lowestCommonAncestor(root.left, p, q)\n if root.val < min(p.val, q.val):\n return self.lowestCommonAncestor(root.right, p, q)\n return root\n", | |
| "title": "235. Lowest Common Ancestor of a Binary Search Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065688, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 28 | |
| }, | |
| { | |
| "code": "class Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n if len(s) != len(t):\n return False\n\n count = collections.Counter(s)\n count.subtract(collections.Counter(t))\n return all(freq == 0 for freq in count.values())\n", | |
| "title": "242. Valid Anagram", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065689, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 29 | |
| }, | |
| { | |
| "code": "class Solution:\n def missingNumber(self, nums: list[int]) -> int:\n ans = len(nums)\n\n for i, num in enumerate(nums):\n ans ^= i ^ num\n\n return ans\n", | |
| "title": "268. Missing Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065689, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 30 | |
| }, | |
| { | |
| "code": "class Solution:\n def moveZeroes(self, nums: list[int]) -> None:\n j = 0\n for num in nums:\n if num != 0:\n nums[j] = num\n j += 1\n\n for i in range(j, len(nums)):\n nums[i] = 0\n", | |
| "title": "283. Move Zeroes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065689, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 31 | |
| }, | |
| { | |
| "code": "class Solution:\n def lengthOfLIS(self, nums: list[int]) -> int:\n if not nums:\n return 0\n\n # dp[i] := the length of LIS ending in nums[i]\n dp = [1] * len(nums)\n\n for i in range(1, len(nums)):\n for j in range(i):\n if nums[j] < nums[i]:\n dp[i] = max(dp[i], dp[j] + 1)\n\n return max(dp)\n", | |
| "title": "300. Longest Increasing Subsequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065690, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 32 | |
| }, | |
| { | |
| "code": "class Solution:\n def coinChange(self, coins: list[int], amount: int) -> int:\n # dp[i] := the minimum number Of coins to make up i\n dp = [0] + [amount + 1] * amount\n\n for coin in coins:\n for i in range(coin, amount + 1):\n dp[i] = min(dp[i], dp[i - coin] + 1)\n\n return -1 if dp[amount] == amount + 1 else dp[amount]\n", | |
| "title": "322. Coin Change", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065690, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 33 | |
| }, | |
| { | |
| "code": "class Solution:\n def topKFrequent(self, nums: list[int], k: int) -> list[int]:\n ans = []\n bucket = [[] for _ in range(len(nums) + 1)]\n\n for num, freq in collections.Counter(nums).items():\n bucket[freq].append(num)\n\n for b in reversed(bucket):\n ans += b\n if len(ans) == k:\n return ans\n", | |
| "title": "347. Top K Frequent Elements", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065690, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 34 | |
| }, | |
| { | |
| "code": "class UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> bool:\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return False\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n return True\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def findRedundantConnection(self, edges: list[list[int]]) -> list[int]:\n uf = UnionFind(len(edges) + 1)\n\n for edge in edges:\n u, v = edge\n if not uf.unionByRank(u, v):\n return edge\n", | |
| "title": "684. Redundant Connection", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218065690, | |
| "isFavorite": false, | |
| "collectionId": 2, | |
| "id": 35 | |
| }, | |
| { | |
| "code": "def max_sum_subarray(arr, k):\n max_sum = 0\n window_sum = 0\n window_start = 0\n\n for window_end in range(len(arr)):\n window_sum += arr[window_end]\n if window_end >= k - 1:\n max_sum = max(max_sum, window_sum)\n window_sum -= arr[window_start]\n window_start += 1\n return max_sum", | |
| "title": "Sliding Window - Max Sum Subarray", | |
| "notes": "The Sliding Window pattern is used to perform a required operation on a specific window size of a given array or linked list, such as finding the maximum sum of a subarray of a certain size.", | |
| "language": "python", | |
| "timestamp": 1752218065691, | |
| "isFavorite": false, | |
| "collectionId": 3, | |
| "id": 36 | |
| }, | |
| { | |
| "code": "def is_palindrome(s):\n left, right = 0, len(s) - 1\n while left < right:\n if s[left] != s[right]:\n return False\n left += 1\n right -= 1\n return True", | |
| "title": "Two Pointers - Palindrome Check", | |
| "notes": "The Two Pointers pattern uses two pointers to iterate through a data structure until one or both of the pointers hit a certain condition. It's often used for searching pairs in a sorted array or checking for palindromes.", | |
| "language": "python", | |
| "timestamp": 1752218065691, | |
| "isFavorite": false, | |
| "collectionId": 3, | |
| "id": 37 | |
| }, | |
| { | |
| "code": "def binary_search(arr, target):\n low, high = 0, len(arr) - 1\n while low <= high:\n mid = (low + high) // 2\n if arr[mid] == target:\n return mid\n elif arr[mid] < target:\n low = mid + 1\n else:\n high = mid - 1\n return -1", | |
| "title": "Binary Search - Find Element", | |
| "notes": "Binary Search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.", | |
| "language": "python", | |
| "timestamp": 1752218065692, | |
| "isFavorite": false, | |
| "collectionId": 3, | |
| "id": 38 | |
| }, | |
| { | |
| "code": "class Solution:\n def twoSum(self, nums: list[int], target: int) -> list[int]:\n numToIndex = {}\n\n for i, num in enumerate(nums):\n if target - num in numToIndex:\n return numToIndex[target - num], i\n numToIndex[num] = i\n", | |
| "title": "1. Two Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 39 | |
| }, | |
| { | |
| "code": "class Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n dummy = ListNode(0)\n curr = dummy\n carry = 0\n\n while carry or l1 or l2:\n if l1:\n carry += l1.val\n l1 = l1.next\n if l2:\n carry += l2.val\n l2 = l2.next\n curr.next = ListNode(carry % 10)\n carry //= 10\n curr = curr.next\n\n return dummy.next\n", | |
| "title": "2. Add Two Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 40 | |
| }, | |
| { | |
| "code": "class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n ans = 0\n # The substring s[j + 1..i] has no repeating characters.\n j = -1\n # lastSeen[c] := the index of the last time c appeared\n lastSeen = {}\n\n for i, c in enumerate(s):\n # Update j to lastSeen[c], so the window must start from j + 1.\n j = max(j, lastSeen.get(c, -1))\n ans = max(ans, i - j)\n lastSeen[c] = i\n\n return ans\n", | |
| "title": "3. Longest Substring Without Repeating Characters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 41 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float:\n n1 = len(nums1)\n n2 = len(nums2)\n if n1 > n2:\n return self.findMedianSortedArrays(nums2, nums1)\n\n l = 0\n r = n1\n\n while l <= r:\n partition1 = (l + r) // 2\n partition2 = (n1 + n2 + 1) // 2 - partition1\n maxLeft1 = -2**31 if partition1 == 0 else nums1[partition1 - 1]\n maxLeft2 = -2**31 if partition2 == 0 else nums2[partition2 - 1]\n minRight1 = 2**31 - 1 if partition1 == n1 else nums1[partition1]\n minRight2 = 2**31 - 1 if partition2 == n2 else nums2[partition2]\n if maxLeft1 <= minRight2 and maxLeft2 <= minRight1:\n return (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) * 0.5 if (n1 + n2) % 2 == 0 else max(maxLeft1, maxLeft2)\n elif maxLeft1 > minRight2:\n r = partition1 - 1\n else:\n l = partition1 + 1\n", | |
| "title": "4. Median of Two Sorted Arrays", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 42 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestPalindrome(self, s: str) -> str:\n t = '#'.join('@' + s + '$')\n p = self._manacher(t)\n maxPalindromeLength, bestCenter = max((extend, i)\n for i, extend in enumerate(p))\n l = (bestCenter - maxPalindromeLength) // 2\n r = (bestCenter + maxPalindromeLength) // 2\n return s[l:r]\n\n def _manacher(self, t: str) -> list[int]:\n \"\"\"\n Returns an array `p` s.t. `p[i]` is the length of the longest palindrome\n centered at `t[i]`, where `t` is a string with delimiters and sentinels.\n \"\"\"\n p = [0] * len(t)\n center = 0\n for i in range(1, len(t) - 1):\n rightBoundary = center + p[center]\n mirrorIndex = center - (i - center)\n if rightBoundary > i:\n p[i] = min(rightBoundary - i, p[mirrorIndex])\n # Try to expand the palindrome centered at i.\n while t[i + 1 + p[i]] == t[i - 1 - p[i]]:\n p[i] += 1\n # If a palindrome centered at i expands past `rightBoundary`, adjust\n # the center based on the expanded palindrome.\n if i + p[i] > rightBoundary:\n center = i\n return p\n", | |
| "title": "5. Longest Palindromic Substring", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 43 | |
| }, | |
| { | |
| "code": "class Solution:\n def convert(self, s: str, numRows: int) -> str:\n rows = [''] * numRows\n k = 0\n direction = (numRows == 1) - 1\n\n for c in s:\n rows[k] += c\n if k == 0 or k == numRows - 1:\n direction *= -1\n k += direction\n\n return ''.join(rows)\n", | |
| "title": "6. ZigZag Conversion", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 44 | |
| }, | |
| { | |
| "code": "class Solution:\n def reverse(self, x: int) -> int:\n ans = 0\n sign = -1 if x < 0 else 1\n x *= sign\n\n while x:\n ans = ans * 10 + x % 10\n x //= 10\n\n return 0 if ans < -2**31 or ans > 2**31 - 1 else sign * ans\n", | |
| "title": "7. Reverse Integer", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 45 | |
| }, | |
| { | |
| "code": "class Solution:\n def myAtoi(self, s: str) -> int:\n s = s.strip()\n if not s:\n return 0\n\n sign = -1 if s[0] == '-' else 1\n if s[0] in {'-', '+'}:\n s = s[1:]\n\n num = 0\n\n for c in s:\n if not c.isdigit():\n break\n num = num * 10 + int(c)\n if sign * num <= -2**31:\n return -2**31\n if sign * num >= 2**31 - 1:\n return 2**31 - 1\n\n return sign * num\n", | |
| "title": "8. String to Integer (atoi)", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 46 | |
| }, | |
| { | |
| "code": "class Solution:\n def isPalindrome(self, x: int) -> bool:\n if x < 0:\n return False\n\n rev = 0\n y = x\n\n while y:\n rev = rev * 10 + y % 10\n y //= 10\n\n return rev == x\n", | |
| "title": "9. Palindrome Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 47 | |
| }, | |
| { | |
| "code": "class Solution:\n def isMatch(self, s: str, p: str) -> bool:\n m = len(s)\n n = len(p)\n # dp[i][j] := True if s[0..i) matches p[0..j)\n dp = [[False] * (n + 1) for _ in range(m + 1)]\n dp[0][0] = True\n\n def isMatch(i: int, j: int) -> bool:\n return j >= 0 and p[j] == '.' or s[i] == p[j]\n\n for j, c in enumerate(p):\n if c == '*' and dp[0][j - 1]:\n dp[0][j + 1] = True\n\n for i in range(m):\n for j in range(n):\n if p[j] == '*':\n # The minimum index of '*' is 1.\n noRepeat = dp[i + 1][j - 1]\n doRepeat = isMatch(i, j - 1) and dp[i][j + 1]\n dp[i + 1][j + 1] = noRepeat or doRepeat\n elif isMatch(i, j):\n dp[i + 1][j + 1] = dp[i][j]\n\n return dp[m][n]\n", | |
| "title": "10. Regular Expression Matching", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 48 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxArea(self, height: list[int]) -> int:\n ans = 0\n l = 0\n r = len(height) - 1\n\n while l < r:\n minHeight = min(height[l], height[r])\n ans = max(ans, minHeight * (r - l))\n if height[l] < height[r]:\n l += 1\n else:\n r -= 1\n\n return ans\n", | |
| "title": "11. Container With Most Water", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 49 | |
| }, | |
| { | |
| "code": "class Solution:\n def intToRoman(self, num: int) -> str:\n M = ['', 'M', 'MM', 'MMM']\n C = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']\n X = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']\n I = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']\n return M[num // 1000] + C[num % 1000 // 100] + X[num % 100 // 10] + I[num % 10]\n", | |
| "title": "12. Integer to Roman", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 50 | |
| }, | |
| { | |
| "code": "class Solution:\n def romanToInt(self, s: str) -> int:\n ans = 0\n roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50,\n 'C': 100, 'D': 500, 'M': 1000}\n\n for a, b in zip(s, s[1:]):\n if roman[a] < roman[b]:\n ans -= roman[a]\n else:\n ans += roman[a]\n\n return ans + roman[s[-1]]\n", | |
| "title": "13. Roman to Integer", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 51 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestCommonPrefix(self, strs: list[str]) -> str:\n if not strs:\n return ''\n\n for i in range(len(strs[0])):\n for j in range(1, len(strs)):\n if i == len(strs[j]) or strs[j][i] != strs[0][i]:\n return strs[0][:i]\n\n return strs[0]\n", | |
| "title": "14. Longest Common Prefix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 52 | |
| }, | |
| { | |
| "code": "class Solution:\n def threeSum(self, nums: list[int]) -> list[list[int]]:\n if len(nums) < 3:\n return []\n\n ans = []\n\n nums.sort()\n\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n # Choose nums[i] as the first number in the triplet, then search the\n # remaining numbers in [i + 1, n - 1].\n l = i + 1\n r = len(nums) - 1\n while l < r:\n summ = nums[i] + nums[l] + nums[r]\n if summ == 0:\n ans.append((nums[i], nums[l], nums[r]))\n l += 1\n r -= 1\n while nums[l] == nums[l - 1] and l < r:\n l += 1\n while nums[r] == nums[r + 1] and l < r:\n r -= 1\n elif summ < 0:\n l += 1\n else:\n r -= 1\n\n return ans\n", | |
| "title": "15. 3Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 53 | |
| }, | |
| { | |
| "code": "class Solution:\n def threeSumClosest(self, nums: list[int], target: int) -> int:\n ans = nums[0] + nums[1] + nums[2]\n\n nums.sort()\n\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n # Choose nums[i] as the first number in the triplet, then search the\n # remaining numbers in [i + 1, n - 1].\n l = i + 1\n r = len(nums) - 1\n while l < r:\n summ = nums[i] + nums[l] + nums[r]\n if summ == target:\n return summ\n if abs(summ - target) < abs(ans - target):\n ans = summ\n if summ < target:\n l += 1\n else:\n r -= 1\n\n return ans\n", | |
| "title": "16. 3Sum Closest", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 54 | |
| }, | |
| { | |
| "code": "class Solution:\n def letterCombinations(self, digits: str) -> list[str]:\n if not digits:\n return []\n\n ans = ['']\n digitToLetters = ['', '', 'abc', 'def', 'ghi',\n 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']\n\n for d in digits:\n temp = []\n for s in ans:\n for c in digitToLetters[int(d)]:\n temp.append(s + c)\n ans = temp\n\n return ans\n", | |
| "title": "17. Letter Combinations of a Phone Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 55 | |
| }, | |
| { | |
| "code": "class Solution:\n def fourSum(self, nums: list[int], target: int):\n ans = []\n\n def nSum(\n l: int, r: int, target: int, n: int, path: list[int],\n ans: list[list[int]]) -> None:\n \"\"\"Finds n numbers that add up to the target in [l, r].\"\"\"\n if r - l + 1 < n or n < 2 or target < nums[l] * n or target > nums[r] * n:\n return\n if n == 2:\n while l < r:\n summ = nums[l] + nums[r]\n if summ == target:\n ans.append(path + [nums[l], nums[r]])\n l += 1\n while nums[l] == nums[l - 1] and l < r:\n l += 1\n elif summ < target:\n l += 1\n else:\n r -= 1\n return\n\n for i in range(l, r + 1):\n if i > l and nums[i] == nums[i - 1]:\n continue\n\n nSum(i + 1, r, target - nums[i], n - 1, path + [nums[i]], ans)\n\n nums.sort()\n nSum(0, len(nums) - 1, target, 4, [], ans)\n return ans\n", | |
| "title": "18. 4Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 56 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n slow = head\n fast = head\n\n for _ in range(n):\n fast = fast.next\n if not fast:\n return head.next\n\n while fast.next:\n slow = slow.next\n fast = fast.next\n slow.next = slow.next.next\n\n return head\n", | |
| "title": "19. Remove Nth Node From End of List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 57 | |
| }, | |
| { | |
| "code": "class Solution:\n def isValid(self, s: str) -> bool:\n stack = []\n\n for c in s:\n if c == '(':\n stack.append(')')\n elif c == '{':\n stack.append('}')\n elif c == '[':\n stack.append(']')\n elif not stack or stack.pop() != c:\n return False\n\n return not stack\n", | |
| "title": "20. Valid Parentheses", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 58 | |
| }, | |
| { | |
| "code": "class Solution:\n def mergeTwoLists(\n self,\n list1: ListNode | None,\n list2: ListNode | None,\n ) -> ListNode | None:\n if not list1 or not list2:\n return list1 if list1 else list2\n if list1.val > list2.val:\n list1, list2 = list2, list1\n list1.next = self.mergeTwoLists(list1.next, list2)\n return list1\n", | |
| "title": "21. Merge Two Sorted Lists", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 59 | |
| }, | |
| { | |
| "code": "class Solution:\n def generateParenthesis(self, n):\n ans = []\n\n def dfs(l: int, r: int, s: list[str]) -> None:\n if l == 0 and r == 0:\n ans.append(''.join(s))\n if l > 0:\n s.append('(')\n dfs(l - 1, r, s)\n s.pop()\n if l < r:\n s.append(')')\n dfs(l, r - 1, s)\n s.pop()\n\n dfs(n, n, [])\n return ans\n", | |
| "title": "22. Generate Parentheses", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 60 | |
| }, | |
| { | |
| "code": "from queue import PriorityQueue\n\n\nclass Solution:\n def mergeKLists(self, lists: list[ListNode]) -> ListNode:\n dummy = ListNode(0)\n curr = dummy\n pq = PriorityQueue()\n\n for i, lst in enumerate(lists):\n if lst:\n pq.put((lst.val, i, lst))\n\n while not pq.empty():\n _, i, minNode = pq.get()\n if minNode.next:\n pq.put((minNode.next.val, i, minNode.next))\n curr.next = minNode\n curr = curr.next\n\n return dummy.next\n", | |
| "title": "23. Merge k Sorted Lists", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 61 | |
| }, | |
| { | |
| "code": "class Solution:\n def swapPairs(self, head: ListNode) -> ListNode:\n def getLength(head: ListNode) -> int:\n length = 0\n while head:\n length += 1\n head = head.next\n return length\n\n length = getLength(head)\n dummy = ListNode(0, head)\n prev = dummy\n curr = head\n\n for _ in range(length // 2):\n next = curr.next\n curr.next = next.next\n next.next = prev.next\n prev.next = next\n prev = curr\n curr = curr.next\n\n return dummy.next\n", | |
| "title": "24. Swap Nodes in Pairs", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 62 | |
| }, | |
| { | |
| "code": "class Solution:\n def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n if not head or k == 1:\n return head\n\n def getLength(head: ListNode) -> int:\n length = 0\n while head:\n length += 1\n head = head.next\n return length\n\n length = getLength(head)\n dummy = ListNode(0, head)\n prev = dummy\n curr = head\n\n for _ in range(length // k):\n for _ in range(k - 1):\n next = curr.next\n curr.next = next.next\n next.next = prev.next\n prev.next = next\n prev = curr\n curr = curr.next\n\n return dummy.next\n", | |
| "title": "25. Reverse Nodes in k-Group", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 63 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeDuplicates(self, nums: list[int]) -> int:\n i = 0\n\n for num in nums:\n if i < 1 or num > nums[i - 1]:\n nums[i] = num\n i += 1\n\n return i\n", | |
| "title": "26. Remove Duplicates from Sorted Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 64 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeElement(self, nums: list[int], val: int) -> int:\n i = 0\n\n for num in nums:\n if num != val:\n nums[i] = num\n i += 1\n\n return i\n", | |
| "title": "27. Remove Element", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 65 | |
| }, | |
| { | |
| "code": "class Solution:\n def strStr(self, haystack: str, needle: str) -> int:\n m = len(haystack)\n n = len(needle)\n\n for i in range(m - n + 1):\n if haystack[i:i + n] == needle:\n return i\n\n return -1\n", | |
| "title": "28. Implement strStr()", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 66 | |
| }, | |
| { | |
| "code": "class Solution:\n def divide(self, dividend: int, divisor: int) -> int:\n # -2^{31} / -1 = 2^31 will overflow, so return 2^31 - 1.\n if dividend == -2**31 and divisor == -1:\n return 2**31 - 1\n\n sign = -1 if (dividend > 0) ^ (divisor > 0) else 1\n ans = 0\n dvd = abs(dividend)\n dvs = abs(divisor)\n\n while dvd >= dvs:\n k = 1\n while k * 2 * dvs <= dvd:\n k <<= 1\n dvd -= k * dvs\n ans += k\n\n return sign * ans\n", | |
| "title": "29. Divide Two Integers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 67 | |
| }, | |
| { | |
| "code": "class Solution:\n def findSubstring(self, s: str, words: list[str]) -> list[int]:\n if len(s) == 0 or words == []:\n return []\n\n k = len(words)\n n = len(words[0])\n ans = []\n count = collections.Counter(words)\n\n for i in range(len(s) - k * n + 1):\n seen = collections.defaultdict(int)\n j = 0\n while j < k:\n word = s[i + j * n: i + j * n + n]\n seen[word] += 1\n if seen[word] > count[word]:\n break\n j += 1\n if j == k:\n ans.append(i)\n\n return ans\n", | |
| "title": "30. Substring with Concatenation of All Words", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 68 | |
| }, | |
| { | |
| "code": "class Solution:\n def nextPermutation(self, nums: list[int]) -> None:\n n = len(nums)\n\n # From back to front, find the first number < nums[i + 1].\n i = n - 2\n while i >= 0:\n if nums[i] < nums[i + 1]:\n break\n i -= 1\n\n # From back to front, find the first number > nums[i], swap it with nums[i].\n if i >= 0:\n for j in range(n - 1, i, -1):\n if nums[j] > nums[i]:\n nums[i], nums[j] = nums[j], nums[i]\n break\n\n def reverse(nums: list[int], l: int, r: int) -> None:\n while l < r:\n nums[l], nums[r] = nums[r], nums[l]\n l += 1\n r -= 1\n\n # Reverse nums[i + 1..n - 1].\n reverse(nums, i + 1, len(nums) - 1)\n", | |
| "title": "31. Next Permutation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 69 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestValidParentheses(self, s: str) -> int:\n s2 = ')' + s\n # dp[i] := the length of the longest valid parentheses in the substring\n # s2[1..i]\n dp = [0] * len(s2)\n\n for i in range(1, len(s2)):\n if s2[i] == ')' and s2[i - dp[i - 1] - 1] == '(':\n dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2\n\n return max(dp)\n", | |
| "title": "32. Longest Valid Parentheses", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 70 | |
| }, | |
| { | |
| "code": "class Solution:\n def search(self, nums: list[int], target: int) -> int:\n l = 0\n r = len(nums) - 1\n\n while l <= r:\n m = (l + r) // 2\n if nums[m] == target:\n return m\n if nums[l] <= nums[m]: # nums[l..m] are sorted.\n if nums[l] <= target < nums[m]:\n r = m - 1\n else:\n l = m + 1\n else: # nums[m..n - 1] are sorted.\n if nums[m] < target <= nums[r]:\n l = m + 1\n else:\n r = m - 1\n\n return -1\n", | |
| "title": "33. Search in Rotated Sorted Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 71 | |
| }, | |
| { | |
| "code": "class Solution:\n def searchRange(self, nums: list[int], target: int) -> list[int]:\n l = bisect_left(nums, target)\n if l == len(nums) or nums[l] != target:\n return -1, -1\n r = bisect_right(nums, target) - 1\n return l, r\n", | |
| "title": "34. Find First and Last Position of Element in Sorted Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 72 | |
| }, | |
| { | |
| "code": "class Solution:\n def searchInsert(self, nums: list[int], target: int) -> int:\n l = 0\n r = len(nums)\n\n while l < r:\n m = (l + r) // 2\n if nums[m] == target:\n return m\n if nums[m] < target:\n l = m + 1\n else:\n r = m\n\n return l\n", | |
| "title": "35. Search Insert Position", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 73 | |
| }, | |
| { | |
| "code": "class Solution:\n def isValidSudoku(self, board: list[list[str]]) -> bool:\n seen = set()\n\n for i in range(9):\n for j in range(9):\n c = board[i][j]\n if c == '.':\n continue\n if (c + '@row ' + str(i) in seen or\n c + '@col ' + str(j) in seen or\n c + '@box ' + str(i // 3) + str(j // 3) in seen):\n return False\n seen.add(c + '@row ' + str(i))\n seen.add(c + '@col ' + str(j))\n seen.add(c + '@box ' + str(i // 3) + str(j // 3))\n\n return True\n", | |
| "title": "36. Valid Sudoku", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 74 | |
| }, | |
| { | |
| "code": "class Solution:\n def solveSudoku(self, board: list[list[str]]) -> None:\n def isValid(row: int, col: int, c: str) -> bool:\n for i in range(9):\n if (board[i][col] == c or\n board[row][i] == c or\n board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == c):\n return False\n return True\n\n def solve(s: int) -> bool:\n if s == 81:\n return True\n\n i = s // 9\n j = s % 9\n\n if board[i][j] != '.':\n return solve(s + 1)\n\n for c in string.digits[1:]:\n if isValid(i, j, c):\n board[i][j] = c\n if solve(s + 1):\n return True\n board[i][j] = '.'\n\n return False\n\n solve(0)\n", | |
| "title": "37. Sudoku Solver", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 75 | |
| }, | |
| { | |
| "code": "class Solution:\n def countAndSay(self, n: int) -> str:\n ans = '1'\n\n for _ in range(n - 1):\n nxt = ''\n i = 0\n while i < len(ans):\n count = 1\n while i + 1 < len(ans) and ans[i] == ans[i + 1]:\n count += 1\n i += 1\n nxt += str(count) + ans[i]\n i += 1\n ans = nxt\n\n return ans\n", | |
| "title": "38. Count and Say", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 76 | |
| }, | |
| { | |
| "code": "class Solution:\n def combinationSum(self, candidates: list[int],\n target: int) -> list[list[int]]:\n ans = []\n\n def dfs(s: int, target: int, path: list[int]) -> None:\n if target < 0:\n return\n if target == 0:\n ans.append(path.clone())\n return\n\n for i in range(s, len(candidates)):\n path.append(candidates[i])\n dfs(i, target - candidates[i], path)\n path.pop()\n\n candidates.sort()\n dfs(0, target, [])\n return ans\n", | |
| "title": "39. Combination Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 77 | |
| }, | |
| { | |
| "code": "class Solution:\n def combinationSum2(self, candidates: list[int],\n target: int) -> list[list[int]]:\n ans = []\n\n def dfs(s: int, target: int, path: list[int]) -> None:\n if target < 0:\n return\n if target == 0:\n ans.append(path.copy())\n return\n\n for i in range(s, len(candidates)):\n if i > s and candidates[i] == candidates[i - 1]:\n continue\n path.append(candidates[i])\n dfs(i + 1, target - candidates[i], path)\n path.pop()\n\n candidates.sort()\n dfs(0, target, [])\n return ans\n", | |
| "title": "40. Combination Sum II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 78 | |
| }, | |
| { | |
| "code": "class Solution:\n def firstMissingPositive(self, nums: list[int]) -> int:\n n = len(nums)\n\n # Correct slot:\n # nums[i] = i + 1\n # nums[i] - 1 = i\n # nums[nums[i] - 1] = nums[i]\n for i in range(n):\n while nums[i] > 0 and nums[i] <= n and nums[nums[i] - 1] != nums[i]:\n nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]\n\n for i, num in enumerate(nums):\n if num != i + 1:\n return i + 1\n\n return n + 1\n", | |
| "title": "41. First Missing Positive", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 79 | |
| }, | |
| { | |
| "code": "class Solution:\n def trap(self, height: list[int]) -> int:\n if not height:\n return 0\n\n ans = 0\n l = 0\n r = len(height) - 1\n maxL = height[l]\n maxR = height[r]\n\n while l < r:\n if maxL < maxR:\n ans += maxL - height[l]\n l += 1\n maxL = max(maxL, height[l])\n else:\n ans += maxR - height[r]\n r -= 1\n maxR = max(maxR, height[r])\n\n return ans\n", | |
| "title": "42. Trapping Rain Water", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 80 | |
| }, | |
| { | |
| "code": "class Solution:\n def multiply(self, num1: str, num2: str) -> str:\n s = [0] * (len(num1) + len(num2))\n\n for i in reversed(range(len(num1))):\n for j in reversed(range(len(num2))):\n mult = int(num1[i]) * int(num2[j])\n summ = mult + s[i + j + 1]\n s[i + j] += summ // 10\n s[i + j + 1] = summ % 10\n\n for i, c in enumerate(s):\n if c != 0:\n break\n\n return ''.join(map(str, s[i:]))\n", | |
| "title": "43. Multiply Strings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 81 | |
| }, | |
| { | |
| "code": "class Solution:\n def isMatch(self, s: str, p: str) -> bool:\n m = len(s)\n n = len(p)\n # dp[i][j] := True if s[0..i) matches p[0..j)\n dp = [[False] * (n + 1) for _ in range(m + 1)]\n dp[0][0] = True\n\n def isMatch(i: int, j: int) -> bool:\n return i >= 0 and p[j] == '?' or s[i] == p[j]\n\n for j, c in enumerate(p):\n if c == '*':\n dp[0][j + 1] = dp[0][j]\n\n for i in range(m):\n for j in range(n):\n if p[j] == '*':\n matchEmpty = dp[i + 1][j]\n matchSome = dp[i][j + 1]\n dp[i + 1][j + 1] = matchEmpty or matchSome\n elif isMatch(i, j):\n dp[i + 1][j + 1] = dp[i][j]\n\n return dp[m][n]\n", | |
| "title": "44. Wildcard Matching", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 82 | |
| }, | |
| { | |
| "code": "class Solution:\n def jump(self, nums: list[int]) -> int:\n ans = 0\n end = 0\n farthest = 0\n\n # Start an implicit BFS.\n for i in range(len(nums) - 1):\n farthest = max(farthest, i + nums[i])\n if farthest >= len(nums) - 1:\n ans += 1\n break\n if i == end: # Visited all the items on the current level.\n ans += 1 # Increment the level.\n end = farthest # Make the queue size for the next level.\n\n return ans\n", | |
| "title": "45. Jump Game II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 83 | |
| }, | |
| { | |
| "code": "class Solution:\n def permute(self, nums: list[int]) -> list[list[int]]:\n ans = []\n used = [False] * len(nums)\n\n def dfs(path: list[int]) -> None:\n if len(path) == len(nums):\n ans.append(path.copy())\n return\n\n for i, num in enumerate(nums):\n if used[i]:\n continue\n used[i] = True\n path.append(num)\n dfs(path)\n path.pop()\n used[i] = False\n\n dfs([])\n return ans\n", | |
| "title": "46. Permutations", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 84 | |
| }, | |
| { | |
| "code": "class Solution:\n def permuteUnique(self, nums: list[int]) -> list[list[int]]:\n ans = []\n used = [False] * len(nums)\n\n def dfs(path: list[int]) -> None:\n if len(path) == len(nums):\n ans.append(path.copy())\n return\n\n for i, num in enumerate(nums):\n if used[i]:\n continue\n if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:\n continue\n used[i] = True\n path.append(num)\n dfs(path)\n path.pop()\n used[i] = False\n\n nums.sort()\n dfs([])\n return ans\n", | |
| "title": "47. Permutations II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 85 | |
| }, | |
| { | |
| "code": "class Solution:\n def rotate(self, matrix: list[list[int]]) -> None:\n for mn in range(len(matrix) // 2):\n mx = len(matrix) - mn - 1\n for i in range(mn, mx):\n offset = i - mn\n top = matrix[mn][i]\n matrix[mn][i] = matrix[mx - offset][mn]\n matrix[mx - offset][mn] = matrix[mx][mx - offset]\n matrix[mx][mx - offset] = matrix[i][mx]\n matrix[i][mx] = top\n", | |
| "title": "48. Rotate Image", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 86 | |
| }, | |
| { | |
| "code": "class Solution:\n def groupAnagrams(self, strs: list[str]) -> list[list[str]]:\n dict = collections.defaultdict(list)\n\n for str in strs:\n key = ''.join(sorted(str))\n dict[key].append(str)\n\n return dict.values()\n", | |
| "title": "49. Group Anagrams", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 87 | |
| }, | |
| { | |
| "code": "class Solution:\n def myPow(self, x: float, n: int) -> float:\n if n == 0:\n return 1\n if n < 0:\n return 1 / self.myPow(x, -n)\n if n % 2 == 1:\n return x * self.myPow(x, n - 1)\n return self.myPow(x * x, n // 2)\n", | |
| "title": "50. Pow(x, n)", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 88 | |
| }, | |
| { | |
| "code": "class Solution:\n def solveNQueens(self, n: int) -> list[list[str]]:\n ans = []\n cols = [False] * n\n diag1 = [False] * (2 * n - 1)\n diag2 = [False] * (2 * n - 1)\n\n def dfs(i: int, board: list[int]) -> None:\n if i == n:\n ans.append(board)\n return\n\n for j in range(n):\n if cols[j] or diag1[i + j] or diag2[j - i + n - 1]:\n continue\n cols[j] = diag1[i + j] = diag2[j - i + n - 1] = True\n dfs(i + 1, board + ['.' * j + 'Q' + '.' * (n - j - 1)])\n cols[j] = diag1[i + j] = diag2[j - i + n - 1] = False\n\n dfs(0, [])\n return ans\n", | |
| "title": "51. N-Queens", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 89 | |
| }, | |
| { | |
| "code": "class Solution:\n def totalNQueens(self, n: int) -> int:\n ans = 0\n cols = [False] * n\n diag1 = [False] * (2 * n - 1)\n diag2 = [False] * (2 * n - 1)\n\n def dfs(i: int) -> None:\n nonlocal ans\n if i == n:\n ans += 1\n return\n\n for j in range(n):\n if cols[j] or diag1[i + j] or diag2[j - i + n - 1]:\n continue\n cols[j] = diag1[i + j] = diag2[j - i + n - 1] = True\n dfs(i + 1)\n cols[j] = diag1[i + j] = diag2[j - i + n - 1] = False\n\n dfs(0)\n return ans\n", | |
| "title": "52. N-Queens II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 90 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxSubArray(self, nums: list[int]) -> int:\n # dp[i] := the maximum sum subarray ending in i\n dp = [0] * len(nums)\n\n dp[0] = nums[0]\n for i in range(1, len(nums)):\n dp[i] = max(nums[i], dp[i - 1] + nums[i])\n\n return max(dp)\n", | |
| "title": "53. Maximum Subarray_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 91 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxSubArray(self, nums: list[int]) -> int:\n ans = -math.inf\n summ = 0\n\n for num in nums:\n summ = max(num, summ + num)\n ans = max(ans, summ)\n\n return ans\n", | |
| "title": "53. Maximum Subarray", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 92 | |
| }, | |
| { | |
| "code": "class Solution:\n def spiralOrder(self, matrix: list[list[int]]) -> list[int]:\n if not matrix:\n return []\n\n m = len(matrix)\n n = len(matrix[0])\n ans = []\n r1 = 0\n c1 = 0\n r2 = m - 1\n c2 = n - 1\n\n # Repeatedly add matrix[r1..r2][c1..c2] to `ans`.\n while len(ans) < m * n:\n j = c1\n while j <= c2 and len(ans) < m * n:\n ans.append(matrix[r1][j])\n j += 1\n i = r1 + 1\n while i <= r2 - 1 and len(ans) < m * n:\n ans.append(matrix[i][c2])\n i += 1\n j = c2\n while j >= c1 and len(ans) < m * n:\n ans.append(matrix[r2][j])\n j -= 1\n i = r2 - 1\n while i >= r1 + 1 and len(ans) < m * n:\n ans.append(matrix[i][c1])\n i -= 1\n r1 += 1\n c1 += 1\n r2 -= 1\n c2 -= 1\n\n return ans\n", | |
| "title": "54. Spiral Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 93 | |
| }, | |
| { | |
| "code": "class Solution:\n def canJump(self, nums: list[int]) -> bool:\n i = 0\n reach = 0\n\n while i < len(nums) and i <= reach:\n reach = max(reach, i + nums[i])\n i += 1\n\n return i == len(nums)\n", | |
| "title": "55. Jump Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 94 | |
| }, | |
| { | |
| "code": "class Solution:\n def merge(self, intervals: list[list[int]]) -> list[list[int]]:\n ans = []\n\n for interval in sorted(intervals):\n if not ans or ans[-1][1] < interval[0]:\n ans.append(interval)\n else:\n ans[-1][1] = max(ans[-1][1], interval[1])\n\n return ans\n", | |
| "title": "56. Merge Intervals", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 95 | |
| }, | |
| { | |
| "code": "class Solution:\n def insert(self, intervals: list[list[int]],\n newInterval: list[int]) -> list[list[int]]:\n n = len(intervals)\n ans = []\n i = 0\n\n while i < n and intervals[i][1] < newInterval[0]:\n ans.append(intervals[i])\n i += 1\n\n # Merge overlapping intervals.\n while i < n and intervals[i][0] <= newInterval[1]:\n newInterval[0] = min(newInterval[0], intervals[i][0])\n newInterval[1] = max(newInterval[1], intervals[i][1])\n i += 1\n\n ans.append(newInterval)\n\n while i < n:\n ans.append(intervals[i])\n i += 1\n\n return ans\n", | |
| "title": "57. Insert Interval", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 96 | |
| }, | |
| { | |
| "code": "class Solution:\n def lengthOfLastWord(self, s: str) -> int:\n i = len(s) - 1\n\n while i >= 0 and s[i] == ' ':\n i -= 1\n lastIndex = i\n while i >= 0 and s[i] != ' ':\n i -= 1\n\n return lastIndex - i\n", | |
| "title": "58. Length of Last Word", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 97 | |
| }, | |
| { | |
| "code": "class Solution:\n def generateMatrix(self, n: int) -> list[list[int]]:\n ans = [[0] * n for _ in range(n)]\n count = 1\n\n for mn in range(n // 2):\n mx = n - mn - 1\n for i in range(mn, mx):\n ans[mn][i] = count\n count += 1\n for i in range(mn, mx):\n ans[i][mx] = count\n count += 1\n for i in range(mx, mn, -1):\n ans[mx][i] = count\n count += 1\n for i in range(mx, mn, -1):\n ans[i][mn] = count\n count += 1\n\n if n % 2 == 1:\n ans[n // 2][n // 2] = count\n\n return ans\n", | |
| "title": "59. Spiral Matrix II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 98 | |
| }, | |
| { | |
| "code": "class Solution:\n def getPermutation(self, n: int, k: int) -> str:\n ans = ''\n nums = [i + 1 for i in range(n)]\n fact = [1] * (n + 1) # fact[i] := i!\n\n for i in range(2, n + 1):\n fact[i] = fact[i - 1] * i\n\n k -= 1 # 0-indexed\n\n for i in reversed(range(n)):\n j = k // fact[i]\n k %= fact[i]\n ans += str(nums[j])\n nums.pop(j)\n\n return ans\n", | |
| "title": "60. Permutation Sequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 99 | |
| }, | |
| { | |
| "code": "class Solution:\n def rotateRight(self, head: ListNode, k: int) -> ListNode:\n if not head or not head.next or k == 0:\n return head\n\n tail = head\n length = 1\n while tail.next:\n tail = tail.next\n length += 1\n tail.next = head # Circle the list.\n\n t = length - k % length\n for _ in range(t):\n tail = tail.next\n newHead = tail.next\n tail.next = None\n\n return newHead\n", | |
| "title": "61. Rotate List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 100 | |
| }, | |
| { | |
| "code": "class Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n dp = [1] * n\n\n for _ in range(1, m):\n for j in range(1, n):\n dp[j] += dp[j - 1]\n\n return dp[n - 1]\n", | |
| "title": "62. Unique Paths", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 101 | |
| }, | |
| { | |
| "code": "class Solution:\n def uniquePathsWithObstacles(self, obstacleGrid: list[list[int]]) -> int:\n m = len(obstacleGrid)\n n = len(obstacleGrid[0])\n dp = [0] * n\n dp[0] = 1\n\n for i in range(m):\n for j in range(n):\n if obstacleGrid[i][j]:\n dp[j] = 0\n elif j > 0:\n dp[j] += dp[j - 1]\n\n return dp[n - 1]\n", | |
| "title": "63. Unique Paths II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 102 | |
| }, | |
| { | |
| "code": "class Solution:\n def minPathSum(self, grid: list[list[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n\n for i in range(m):\n for j in range(n):\n if i > 0 and j > 0:\n grid[i][j] += min(grid[i - 1][j], grid[i][j - 1])\n elif i > 0:\n grid[i][0] += grid[i - 1][0]\n elif j > 0:\n grid[0][j] += grid[0][j - 1]\n\n return grid[m - 1][n - 1]\n", | |
| "title": "64. Minimum Path Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 103 | |
| }, | |
| { | |
| "code": "class Solution:\n def isNumber(self, s: str) -> bool:\n s = s.strip()\n if not s:\n return False\n\n seenNum = False\n seenDot = False\n seenE = False\n\n for i, c in enumerate(s):\n if c == '.':\n if seenDot or seenE:\n return False\n seenDot = True\n elif c == 'e' or c == 'E':\n if seenE or not seenNum:\n return False\n seenE = True\n seenNum = False\n elif c in '+-':\n if i > 0 and s[i - 1] not in 'eE':\n return False\n seenNum = False\n else:\n if not c.isdigit():\n return False\n seenNum = True\n\n return seenNum\n", | |
| "title": "65. Valid Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 104 | |
| }, | |
| { | |
| "code": "class Solution:\n def plusOne(self, digits: list[int]) -> list[int]:\n for i, d in reversed(list(enumerate(digits))):\n if d < 9:\n digits[i] += 1\n return digits\n digits[i] = 0\n\n return [1] + digits\n", | |
| "title": "66. Plus One", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 105 | |
| }, | |
| { | |
| "code": "class Solution:\n def addBinary(self, a: str, b: str) -> str:\n ans = []\n carry = 0\n i = len(a) - 1\n j = len(b) - 1\n\n while i >= 0 or j >= 0 or carry:\n if i >= 0:\n carry += int(a[i])\n i -= 1\n if j >= 0:\n carry += int(b[j])\n j -= 1\n ans.append(str(carry % 2))\n carry //= 2\n\n return ''.join(reversed(ans))\n", | |
| "title": "67. Add Binary", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 106 | |
| }, | |
| { | |
| "code": "class Solution:\n def fullJustify(self, words: list[str], maxWidth: int) -> list[str]:\n ans = []\n row = []\n rowLetters = 0\n\n for word in words:\n # If we place the word in this row, it will exceed the maximum width.\n # Therefore, we cannot put the word in this row and have to pad spaces\n # for each word in this row.\n if rowLetters + len(word) + len(row) > maxWidth:\n for i in range(maxWidth - rowLetters):\n row[i % (len(row) - 1 or 1)] += ' '\n ans.append(''.join(row))\n row = []\n rowLetters = 0\n row.append(word)\n rowLetters += len(word)\n\n return ans + [' '.join(row).ljust(maxWidth)]\n", | |
| "title": "68. Text Justification", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 107 | |
| }, | |
| { | |
| "code": "class Solution:\n def mySqrt(self, x: int) -> int:\n return bisect.bisect_right(range(x + 1), x,\n key=lambda m: m * m) - 1\n", | |
| "title": "69. Sqrt(x)", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 108 | |
| }, | |
| { | |
| "code": "class Solution:\n def climbStairs(self, n: int) -> int:\n prev1 = 1 # dp[i - 1]\n prev2 = 1 # dp[i - 2]\n\n for _ in range(2, n + 1):\n dp = prev1 + prev2\n prev2 = prev1\n prev1 = dp\n\n return prev1\n", | |
| "title": "70. Climbing Stairs", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 109 | |
| }, | |
| { | |
| "code": "class Solution:\n def simplifyPath(self, path: str) -> str:\n stack = []\n\n for str in path.split('/'):\n if str in ('', '.'):\n continue\n if str == '..':\n if stack:\n stack.pop()\n else:\n stack.append(str)\n\n return '/' + '/'.join(stack)\n", | |
| "title": "71. Simplify Path", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 110 | |
| }, | |
| { | |
| "code": "class Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n m = len(word1)\n n = len(word2)\n # dp[i][j] := the minimum number of operations to convert word1[0..i) to\n # word2[0..j)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n for i in range(1, m + 1):\n dp[i][0] = i\n\n for j in range(1, n + 1):\n dp[0][j] = j\n\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if word1[i - 1] == word2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1]\n else:\n dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1\n\n return dp[m][n]\n", | |
| "title": "72. Edit Distance", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 111 | |
| }, | |
| { | |
| "code": "class Solution:\n def setZeroes(self, matrix: list[list[int]]) -> None:\n m = len(matrix)\n n = len(matrix[0])\n shouldFillFirstRow = 0 in matrix[0]\n shouldFillFirstCol = 0 in list(zip(*matrix))[0]\n\n # Store the information in the first row and the first column.\n for i in range(1, m):\n for j in range(1, n):\n if matrix[i][j] == 0:\n matrix[i][0] = 0\n matrix[0][j] = 0\n\n # Fill 0s for the matrix except the first row and the first column.\n for i in range(1, m):\n for j in range(1, n):\n if matrix[i][0] == 0 or matrix[0][j] == 0:\n matrix[i][j] = 0\n\n # Fill 0s for the first row if needed.\n if shouldFillFirstRow:\n matrix[0] = [0] * n\n\n # Fill 0s for the first column if needed.\n if shouldFillFirstCol:\n for row in matrix:\n row[0] = 0\n", | |
| "title": "73. Set Matrix Zeroes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 112 | |
| }, | |
| { | |
| "code": "class Solution:\n def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:\n if not matrix:\n return False\n\n m = len(matrix)\n n = len(matrix[0])\n l = 0\n r = m * n\n\n while l < r:\n mid = (l + r) // 2\n i = mid // n\n j = mid % n\n if matrix[i][j] == target:\n return True\n if matrix[i][j] < target:\n l = mid + 1\n else:\n r = mid\n\n return False\n", | |
| "title": "74. Search a 2D Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 113 | |
| }, | |
| { | |
| "code": "class Solution:\n def sortColors(self, nums: list[int]) -> None:\n l = 0 # The next 0 should be placed in l.\n r = len(nums) - 1 # THe next 2 should be placed in r.\n\n i = 0\n while i <= r:\n if nums[i] == 0:\n nums[i], nums[l] = nums[l], nums[i]\n i += 1\n l += 1\n elif nums[i] == 1:\n i += 1\n else:\n # We may swap a 0 to index i, but we're still not sure whether this 0\n # is placed in the correct index, so we can't move pointer i.\n nums[i], nums[r] = nums[r], nums[i]\n r -= 1\n", | |
| "title": "75. Sort Colors", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 114 | |
| }, | |
| { | |
| "code": "class Solution:\n def minWindow(self, s: str, t: str) -> str:\n count = collections.Counter(t)\n required = len(t)\n bestLeft = -1\n minLength = len(s) + 1\n\n l = 0\n for r, c in enumerate(s):\n count[c] -= 1\n if count[c] >= 0:\n required -= 1\n while required == 0:\n if r - l + 1 < minLength:\n bestLeft = l\n minLength = r - l + 1\n count[s[l]] += 1\n if count[s[l]] > 0:\n required += 1\n l += 1\n\n return '' if bestLeft == -1 else s[bestLeft: bestLeft + minLength]\n", | |
| "title": "76. Minimum Window Substring", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 115 | |
| }, | |
| { | |
| "code": "class Solution:\n def combine(self, n: int, k: int) -> list[list[int]]:\n ans = []\n\n def dfs(s: int, path: list[int]) -> None:\n if len(path) == k:\n ans.append(path.copy())\n return\n\n for i in range(s, n + 1):\n path.append(i)\n dfs(i + 1, path)\n path.pop()\n\n dfs(1, [])\n return ans\n", | |
| "title": "77. Combinations", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 116 | |
| }, | |
| { | |
| "code": "class Solution:\n def subsets(self, nums: list[int]) -> list[list[int]]:\n ans = []\n\n def dfs(s: int, path: list[int]) -> None:\n ans.append(path)\n\n for i in range(s, len(nums)):\n dfs(i + 1, path + [nums[i]])\n\n dfs(0, [])\n return ans\n", | |
| "title": "78. Subsets", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 117 | |
| }, | |
| { | |
| "code": "class Solution:\n def exist(self, board: list[list[str]], word: str) -> bool:\n m = len(board)\n n = len(board[0])\n\n def dfs(i: int, j: int, s: int) -> bool:\n if i < 0 or i == m or j < 0 or j == n:\n return False\n if board[i][j] != word[s] or board[i][j] == '*':\n return False\n if s == len(word) - 1:\n return True\n\n cache = board[i][j]\n board[i][j] = '*'\n isExist = (dfs(i + 1, j, s + 1) or\n dfs(i - 1, j, s + 1) or\n dfs(i, j + 1, s + 1) or\n dfs(i, j - 1, s + 1))\n board[i][j] = cache\n\n return isExist\n\n return any(dfs(i, j, 0)\n for i in range(m)\n for j in range(n))\n", | |
| "title": "79. Word Search", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 118 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeDuplicates(self, nums: list[int]) -> int:\n i = 0\n\n for num in nums:\n if i < 2 or num != nums[i - 2]:\n nums[i] = num\n i += 1\n\n return i\n", | |
| "title": "80. Remove Duplicates from Sorted Array II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 119 | |
| }, | |
| { | |
| "code": "class Solution:\n def search(self, nums: list[int], target: int) -> bool:\n l = 0\n r = len(nums) - 1\n\n while l <= r:\n m = (l + r) // 2\n if nums[m] == target:\n return True\n if nums[l] == nums[m] == nums[r]:\n l += 1\n r -= 1\n elif nums[l] <= nums[m]: # nums[l..m] are sorted\n if nums[l] <= target < nums[m]:\n r = m - 1\n else:\n l = m + 1\n else: # nums[m..n - 1] are sorted\n if nums[m] < target <= nums[r]:\n l = m + 1\n else:\n r = m - 1\n\n return False\n", | |
| "title": "81. Search in Rotated Sorted Array II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 120 | |
| }, | |
| { | |
| "code": "class Solution:\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n dummy = ListNode(0, head)\n prev = dummy\n\n while head:\n while head.next and head.val == head.next.val:\n head = head.next\n if prev.next == head:\n prev = prev.next\n else:\n prev.next = head.next\n head = head.next\n\n return dummy.next\n", | |
| "title": "82. Remove Duplicates from Sorted List II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 121 | |
| }, | |
| { | |
| "code": "class Solution:\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n curr = head\n\n while curr:\n while curr.next and curr.val == curr.next.val:\n curr.next = curr.next.next\n curr = curr.next\n\n return head\n", | |
| "title": "83. Remove Duplicates from Sorted List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 122 | |
| }, | |
| { | |
| "code": "class Solution:\n def largestRectangleArea(self, heights: list[int]) -> int:\n ans = 0\n stack = []\n\n for i in range(len(heights) + 1):\n while stack and (i == len(heights) or heights[stack[-1]] > heights[i]):\n h = heights[stack.pop()]\n w = i - stack[-1] - 1 if stack else i\n ans = max(ans, h * w)\n stack.append(i)\n\n return ans\n", | |
| "title": "84. Largest Rectangle in Histogram", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 123 | |
| }, | |
| { | |
| "code": "class Solution:\n def maximalRectangle(self, matrix: list[list[str]]) -> int:\n if not matrix:\n return 0\n\n ans = 0\n hist = [0] * len(matrix[0])\n\n def largestRectangleArea(heights: list[int]) -> int:\n ans = 0\n stack = []\n\n for i in range(len(heights) + 1):\n while stack and (i == len(heights) or heights[stack[-1]] > heights[i]):\n h = heights[stack.pop()]\n w = i - stack[-1] - 1 if stack else i\n ans = max(ans, h * w)\n stack.append(i)\n\n return ans\n\n for row in matrix:\n for i, num in enumerate(row):\n hist[i] = 0 if num == '0' else hist[i] + 1\n ans = max(ans, largestRectangleArea(hist))\n\n return ans\n", | |
| "title": "85. Maximal Rectangle", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 124 | |
| }, | |
| { | |
| "code": "class Solution:\n def partition(self, head: ListNode, x: int) -> ListNode:\n beforeHead = ListNode(0)\n afterHead = ListNode(0)\n before = beforeHead\n after = afterHead\n\n while head:\n if head.val < x:\n before.next = head\n before = head\n else:\n after.next = head\n after = head\n head = head.next\n\n after.next = None\n before.next = afterHead.next\n\n return beforeHead.next\n", | |
| "title": "86. Partition List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 125 | |
| }, | |
| { | |
| "code": "class Solution:\n @functools.lru_cache(None)\n def isScramble(self, s1: str, s2: str) -> bool:\n if s1 == s2:\n return True\n if collections.Counter(s1) != collections.Counter(s2):\n return False\n\n for i in range(1, len(s1)):\n if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]):\n return True\n if (self.isScramble(s1[:i], s2[len(s2) - i:]) and\n self.isScramble(s1[i:], s2[: len(s2) - i])):\n return True\n\n return False\n", | |
| "title": "87. Scramble String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 126 | |
| }, | |
| { | |
| "code": "class Solution:\n def merge(self, nums1: list[int], m: int, nums2: list[int], n: int) -> None:\n i = m - 1 # nums1's index (the actual nums)\n j = n - 1 # nums2's index\n k = m + n - 1 # nums1's index (the next filled position)\n\n while j >= 0:\n if i >= 0 and nums1[i] > nums2[j]:\n nums1[k] = nums1[i]\n k -= 1\n i -= 1\n else:\n nums1[k] = nums2[j]\n k -= 1\n j -= 1\n", | |
| "title": "88. Merge Sorted Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 127 | |
| }, | |
| { | |
| "code": "class Solution:\n def grayCode(self, n: int) -> list[int]:\n ans = [0]\n\n for i in range(n):\n for j in reversed(range(len(ans))):\n ans.append(ans[j] | 1 << i)\n\n return ans\n", | |
| "title": "89. Gray Code", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 128 | |
| }, | |
| { | |
| "code": "class Solution:\n def subsetsWithDup(self, nums: list[int]) -> list[list[int]]:\n ans = []\n\n def dfs(s: int, path: list[int]) -> None:\n ans.append(path)\n if s == len(nums):\n return\n\n for i in range(s, len(nums)):\n if i > s and nums[i] == nums[i - 1]:\n continue\n dfs(i + 1, path + [nums[i]])\n\n nums.sort()\n dfs(0, [])\n return ans\n", | |
| "title": "90. Subsets II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 129 | |
| }, | |
| { | |
| "code": "class Solution:\n def numDecodings(self, s: str) -> int:\n n = len(s)\n # dp[i] := the number of ways to decode s[i..n)\n dp = [0] * n + [1]\n\n def isValid(a: str, b=None) -> bool:\n if b:\n return a == '1' or a == '2' and b < '7'\n return a != '0'\n\n if isValid(s[-1]):\n dp[n - 1] = 1\n\n for i in reversed(range(n - 1)):\n if isValid(s[i]):\n dp[i] += dp[i + 1]\n if isValid(s[i], s[i + 1]):\n dp[i] += dp[i + 2]\n\n return dp[0]\n", | |
| "title": "91. Decode Ways", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 130 | |
| }, | |
| { | |
| "code": "class Solution:\n def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:\n if not head and m == n:\n return head\n\n dummy = ListNode(0, head)\n prev = dummy\n\n for _ in range(m - 1):\n prev = prev.next # Point to the node before the sublist [m, n].\n\n tail = prev.next # Be the tail of the sublist [m, n].\n\n # Reverse the sublist [m, n] one by one.\n for _ in range(n - m):\n cache = tail.next\n tail.next = cache.next\n cache.next = prev.next\n prev.next = cache\n\n return dummy.next\n", | |
| "title": "92. Reverse Linked List II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 131 | |
| }, | |
| { | |
| "code": "class Solution:\n def restoreIpAddresses(self, s: str) -> list[str]:\n ans = []\n\n def dfs(start: int, path: list[int]) -> None:\n if len(path) == 4 and start == len(s):\n ans.append(path[0] + '.' + path[1] + '.' + path[2] + '.' + path[3])\n return\n if len(path) == 4 or start == len(s):\n return\n\n for length in range(1, 4):\n if start + length > len(s):\n return # out-of-bounds\n if length > 1 and s[start] == '0':\n return # leading '0'\n num = s[start: start + length]\n if int(num) > 255:\n return\n dfs(start + length, path + [num])\n\n dfs(0, [])\n return ans\n", | |
| "title": "93. Restore IP Addresses", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 132 | |
| }, | |
| { | |
| "code": "class Solution:\n def inorderTraversal(self, root: TreeNode | None) -> list[int]:\n ans = []\n stack = []\n\n while root or stack:\n while root:\n stack.append(root)\n root = root.left\n root = stack.pop()\n ans.append(root.val)\n root = root.right\n\n return ans\n", | |
| "title": "94. Binary Tree Inorder Traversal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 133 | |
| }, | |
| { | |
| "code": "class Solution:\n def generateTrees(self, n: int) -> list[TreeNode]:\n if n == 0:\n return []\n\n def generateTrees(mn: int, mx: int) -> list[int | None]:\n if mn > mx:\n return [None]\n\n ans = []\n\n for i in range(mn, mx + 1):\n for left in generateTrees(mn, i - 1):\n for right in generateTrees(i + 1, mx):\n ans.append(TreeNode(i))\n ans[-1].left = left\n ans[-1].right = right\n\n return ans\n\n return generateTrees(1, n)\n", | |
| "title": "95. Unique Binary Search Trees II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 134 | |
| }, | |
| { | |
| "code": "class Solution:\n def numTrees(self, n: int) -> int:\n # dp[i] := the number of unique BST's that store values 1..i\n dp = [1, 1] + [0] * (n - 1)\n\n for i in range(2, n + 1):\n for j in range(i):\n dp[i] += dp[j] * dp[i - j - 1]\n\n return dp[n]\n", | |
| "title": "96. Unique Binary Search Trees", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 135 | |
| }, | |
| { | |
| "code": "class Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n m = len(s1)\n n = len(s2)\n if m + n != len(s3):\n return False\n\n dp = [False] * (n + 1)\n\n for i in range(m + 1):\n for j in range(n + 1):\n if i == 0 and j == 0:\n dp[j] = True\n elif i == 0:\n dp[j] = dp[j - 1] and s2[j - 1] == s3[j - 1]\n elif j == 0:\n dp[j] = dp[j] and s1[i - 1] == s3[i - 1]\n else:\n dp[j] = (dp[j] and s1[i - 1] == s3[i + j - 1] or\n dp[j - 1] and s2[j - 1] == s3[i + j - 1])\n\n return dp[n]\n", | |
| "title": "97. Interleaving String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 136 | |
| }, | |
| { | |
| "code": "class Solution:\n def isValidBST(self, root: TreeNode | None) -> bool:\n stack = []\n pred = None\n\n while root or stack:\n while root:\n stack.append(root)\n root = root.left\n root = stack.pop()\n if pred and pred.val >= root.val:\n return False\n pred = root\n root = root.right\n\n return True\n", | |
| "title": "98. Validate Binary Search Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 137 | |
| }, | |
| { | |
| "code": "class Solution:\n def recoverTree(self, root: TreeNode | None) -> None:\n def swap(x: TreeNode | None, y: TreeNode | None) -> None:\n temp = x.val\n x.val = y.val\n y.val = temp\n\n def inorder(root: TreeNode | None) -> None:\n if not root:\n return\n\n inorder(root.left)\n\n if self.pred and root.val < self.pred.val:\n self.y = root\n if not self.x:\n self.x = self.pred\n else:\n return\n self.pred = root\n\n inorder(root.right)\n\n inorder(root)\n swap(self.x, self.y)\n\n pred = None\n x = None # the first wrong node\n y = None # the second wrong node\n", | |
| "title": "99. Recover Binary Search Tree_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 138 | |
| }, | |
| { | |
| "code": "class Solution:\n def recoverTree(self, root: TreeNode | None) -> None:\n pred = None\n x = None # the first wrong node\n y = None # the second wrong node\n stack = []\n\n while root or stack:\n while root:\n stack.append(root)\n root = root.left\n root = stack.pop()\n if pred and root.val < pred.val:\n y = root\n if not x:\n x = pred\n pred = root\n root = root.right\n\n def swap(x: TreeNode | None, y: TreeNode | None) -> None:\n temp = x.val\n x.val = y.val\n y.val = temp\n\n swap(x, y)\n", | |
| "title": "99. Recover Binary Search Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 139 | |
| }, | |
| { | |
| "code": "class Solution:\n def isSameTree(self, p: TreeNode | None, q: TreeNode | None) -> bool:\n if not p or not q:\n return p == q\n return (p.val == q.val and\n self.isSameTree(p.left, q.left) and\n self.isSameTree(p.right, q.right))\n", | |
| "title": "100. Same Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 140 | |
| }, | |
| { | |
| "code": "class Solution:\n def isSymmetric(self, root: TreeNode | None) -> bool:\n def isSymmetric(p: TreeNode | None, q: TreeNode | None) -> bool:\n if not p or not q:\n return p == q\n return (p.val == q.val and\n isSymmetric(p.left, q.right) and\n isSymmetric(p.right, q.left))\n\n return isSymmetric(root, root)\n", | |
| "title": "101. Symmetric Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 141 | |
| }, | |
| { | |
| "code": "class Solution:\n def levelOrder(self, root: TreeNode | None) -> list[list[int]]:\n if not root:\n return []\n\n ans = []\n q = collections.deque([root])\n\n while q:\n currLevel = []\n for _ in range(len(q)):\n node = q.popleft()\n currLevel.append(node.val)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n ans.append(currLevel)\n\n return ans\n", | |
| "title": "102. Binary Tree Level Order Traversal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 142 | |
| }, | |
| { | |
| "code": "class Solution:\n def zigzagLevelOrder(self, root: TreeNode | None) -> list[list[int]]:\n if not root:\n return []\n\n ans = []\n q = collections.deque([root])\n isLeftToRight = True\n\n while q:\n size = len(q)\n currLevel = [0] * size\n for i in range(size):\n node = q.popleft()\n index = i if isLeftToRight else size - i - 1\n currLevel[index] = node.val\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n ans.append(currLevel)\n isLeftToRight = not isLeftToRight\n\n return ans\n", | |
| "title": "103. Binary Tree Zigzag Level Order Traversal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 143 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxDepth(self, root: TreeNode | None) -> int:\n if not root:\n return 0\n return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))\n", | |
| "title": "104. Maximum Depth of Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 144 | |
| }, | |
| { | |
| "code": "class Solution:\n def buildTree(\n self,\n preorder: list[int],\n inorder: list[int],\n ) -> TreeNode | None:\n inToIndex = {num: i for i, num in enumerate(inorder)}\n\n def build(\n preStart: int,\n preEnd: int,\n inStart: int,\n inEnd: int,\n ) -> TreeNode | None:\n if preStart > preEnd:\n return None\n\n rootVal = preorder[preStart]\n rootInIndex = inToIndex[rootVal]\n leftSize = rootInIndex - inStart\n\n root = TreeNode(rootVal)\n root.left = build(preStart + 1, preStart + leftSize,\n inStart, rootInIndex - 1)\n root.right = build(preStart + leftSize + 1,\n preEnd, rootInIndex + 1, inEnd)\n return root\n\n return build(0, len(preorder) - 1, 0, len(inorder) - 1)\n", | |
| "title": "105. Construct Binary Tree from Preorder and Inorder Traversal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 145 | |
| }, | |
| { | |
| "code": "class Solution:\n def buildTree(\n self,\n inorder: list[int],\n postorder: list[int],\n ) -> TreeNode | None:\n inToIndex = {num: i for i, num in enumerate(inorder)}\n\n def build(\n inStart: int,\n inEnd: int,\n postStart: int,\n postEnd: int,\n ) -> TreeNode | None:\n if inStart > inEnd:\n return None\n\n rootVal = postorder[postEnd]\n rootInIndex = inToIndex[rootVal]\n leftSize = rootInIndex - inStart\n\n root = TreeNode(rootVal)\n root.left = build(inStart, rootInIndex - 1, postStart,\n postStart + leftSize - 1)\n root.right = build(rootInIndex + 1, inEnd, postStart + leftSize,\n postEnd - 1)\n return root\n\n return build(0, len(inorder) - 1, 0, len(postorder) - 1)\n", | |
| "title": "106. Construct Binary Tree from Inorder and Postorder Traversal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 146 | |
| }, | |
| { | |
| "code": "class Solution:\n def levelOrderBottom(self, root: TreeNode | None) -> list[list[int]]:\n if not root:\n return []\n\n ans = []\n q = collections.deque([root])\n\n while q:\n currLevel = []\n for _ in range(len(q)):\n node = q.popleft()\n currLevel.append(node.val)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n ans.append(currLevel)\n\n return ans[::-1]\n", | |
| "title": "107. Binary Tree Level Order Traversal II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 147 | |
| }, | |
| { | |
| "code": "class Solution:\n def sortedArrayToBST(self, nums: list[int]) -> TreeNode | None:\n def build(l: int, r: int) -> TreeNode | None:\n if l > r:\n return None\n m = (l + r) // 2\n return TreeNode(nums[m],\n build(l, m - 1),\n build(m + 1, r))\n\n return build(0, len(nums) - 1)\n", | |
| "title": "108. Convert Sorted Array to Binary Search Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 148 | |
| }, | |
| { | |
| "code": "class Solution:\n def sortedListToBST(self, head: ListNode) -> TreeNode:\n def findMid(head: ListNode) -> ListNode:\n prev = None\n slow = head\n fast = head\n\n while fast and fast.next:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n prev.next = None\n\n return slow\n\n if not head:\n return None\n if not head.next:\n return TreeNode(head.val)\n\n mid = findMid(head)\n root = TreeNode(mid.val)\n root.left = self.sortedListToBST(head)\n root.right = self.sortedListToBST(mid.next)\n return root\n", | |
| "title": "109. Convert Sorted List to Binary Search Tree_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 149 | |
| }, | |
| { | |
| "code": "class Solution:\n def sortedListToBST(self, head: ListNode | None) -> TreeNode | None:\n arr = []\n\n # Construct the array.\n curr = head\n while curr:\n arr.append(curr.val)\n curr = curr.next\n\n def helper(l: int, r: int) -> TreeNode | None:\n if l > r:\n return None\n m = (l + r) // 2\n root = TreeNode(arr[m])\n root.left = helper(l, m - 1)\n root.right = helper(m + 1, r)\n return root\n\n return helper(0, len(arr) - 1)\n", | |
| "title": "109. Convert Sorted List to Binary Search Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 150 | |
| }, | |
| { | |
| "code": "class Solution:\n def isBalanced(self, root: TreeNode | None) -> bool:\n if not root:\n return True\n\n def maxDepth(root: TreeNode | None) -> int:\n if not root:\n return 0\n return 1 + max(maxDepth(root.left), maxDepth(root.right))\n\n return (abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 and\n self.isBalanced(root.left) and\n self.isBalanced(root.right))\n", | |
| "title": "110. Balanced Binary Tree_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312225, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 151 | |
| }, | |
| { | |
| "code": "class Solution:\n def isBalanced(self, root: TreeNode | None) -> bool:\n ans = True\n\n def maxDepth(root: TreeNode | None) -> int:\n \"\"\"Returns the height of root and sets ans to false if root unbalanced.\"\"\"\n nonlocal ans\n if not root or not ans:\n return 0\n left = maxDepth(root.left)\n right = maxDepth(root.right)\n if abs(left - right) > 1:\n ans = False\n return max(left, right) + 1\n\n maxDepth(root)\n return ans\n", | |
| "title": "110. Balanced Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 152 | |
| }, | |
| { | |
| "code": "class Solution:\n def minDepth(self, root: TreeNode | None) -> int:\n if not root:\n return 0\n\n q = collections.deque([root])\n\n step = 1\n while q:\n for _ in range(len(q)):\n node = q.popleft()\n if not node.left and not node.right:\n return step\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n step += 1\n", | |
| "title": "111. Minimum Depth of Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 153 | |
| }, | |
| { | |
| "code": "class Solution:\n def hasPathSum(self, root: TreeNode, summ: int) -> bool:\n if not root:\n return False\n if root.val == summ and not root.left and not root.right:\n return True\n return (self.hasPathSum(root.left, summ - root.val) or\n self.hasPathSum(root.right, summ - root.val))\n", | |
| "title": "112. Path Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 154 | |
| }, | |
| { | |
| "code": "class Solution:\n def pathSum(self, root: TreeNode, summ: int) -> list[list[int]]:\n ans = []\n\n def dfs(root: TreeNode, summ: int, path: list[int]) -> None:\n if not root:\n return\n if root.val == summ and not root.left and not root.right:\n ans.append(path + [root.val])\n return\n\n dfs(root.left, summ - root.val, path + [root.val])\n dfs(root.right, summ - root.val, path + [root.val])\n\n dfs(root, summ, [])\n return ans\n", | |
| "title": "113. Path Sum II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 155 | |
| }, | |
| { | |
| "code": "class Solution:\n def flatten(self, root: TreeNode | None) -> None:\n if not root:\n return\n\n self.flatten(root.left)\n self.flatten(root.right)\n\n left = root.left # flattened left\n right = root.right # flattened right\n\n root.left = None\n root.right = left\n\n # Connect the original right subtree to the end of the new right subtree.\n rightmost = root\n while rightmost.right:\n rightmost = rightmost.right\n rightmost.right = right\n", | |
| "title": "114. Flatten Binary Tree to Linked List_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 156 | |
| }, | |
| { | |
| "code": "class Solution:\n def flatten(self, root: TreeNode | None) -> None:\n if not root:\n return\n\n stack = [root]\n\n while stack:\n root = stack.pop()\n if root.right:\n stack.append(root.right)\n if root.left:\n stack.append(root.left)\n if stack:\n root.right = stack[-1]\n root.left = None\n", | |
| "title": "114. Flatten Binary Tree to Linked List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 157 | |
| }, | |
| { | |
| "code": "class Solution:\n def numDistinct(self, s: str, t: str) -> int:\n m = len(s)\n n = len(t)\n dp = [1] + [0] * n\n\n for i in range(1, m + 1):\n for j in range(n, 1 - 1, -1):\n if s[i - 1] == t[j - 1]:\n dp[j] += dp[j - 1]\n\n return dp[n]\n", | |
| "title": "115. Distinct Subsequences", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 158 | |
| }, | |
| { | |
| "code": "class Solution:\n def connect(self, root: 'Node') -> 'Node':\n node = root # the node that is above the current needling\n\n while node and node.left:\n dummy = Node(0) # a dummy node before needling\n # Needle the children of the node.\n needle = dummy\n while node:\n needle.next = node.left\n needle = needle.next\n needle.next = node.right\n needle = needle.next\n node = node.next\n node = dummy.next # Move the node to the next level.\n\n return root\n", | |
| "title": "116. Populating Next Right Pointers in Each Node", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 159 | |
| }, | |
| { | |
| "code": "class Solution:\n def connect(self, root: 'Node') -> 'Node':\n node = root # the node that is above the current needling\n\n while node:\n dummy = Node(0) # a dummy node before needling\n # Needle the children of the node.\n needle = dummy\n while node:\n if node.left: # Needle the left child.\n needle.next = node.left\n needle = needle.next\n if node.right: # Needle the right child.\n needle.next = node.right\n needle = needle.next\n node = node.next\n node = dummy.next # Move the node to the next level.\n\n return root\n", | |
| "title": "117. Populating Next Right Pointers in Each Node II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 160 | |
| }, | |
| { | |
| "code": "class Solution:\n def generate(self, numRows: int) -> list[list[int]]:\n ans = []\n\n for i in range(numRows):\n ans.append([1] * (i + 1))\n\n for i in range(2, numRows):\n for j in range(1, len(ans[i]) - 1):\n ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j]\n\n return ans\n", | |
| "title": "118. Pascal's Triangle", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 161 | |
| }, | |
| { | |
| "code": "class Solution:\n def getRow(self, rowIndex: int) -> list[int]:\n ans = [1] * (rowIndex + 1)\n\n for i in range(2, rowIndex + 1):\n for j in range(1, i):\n ans[i - j] += ans[i - j - 1]\n\n return ans\n", | |
| "title": "119. Pascal's Triangle II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 162 | |
| }, | |
| { | |
| "code": "class Solution:\n def minimumTotal(self, triangle: list[list[int]]) -> int:\n for i in range(len(triangle) - 2, -1, -1):\n for j in range(i + 1):\n triangle[i][j] += min(triangle[i + 1][j],\n triangle[i + 1][j + 1])\n\n return triangle[0][0]\n", | |
| "title": "120. Triangle", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 163 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxProfit(self, prices: list[int]) -> int:\n sellOne = 0\n holdOne = -math.inf\n\n for price in prices:\n sellOne = max(sellOne, holdOne + price)\n holdOne = max(holdOne, -price)\n\n return sellOne\n", | |
| "title": "121. Best Time to Buy and Sell Stock", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 164 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxProfit(self, prices: list[int]) -> int:\n sell = 0\n hold = -math.inf\n\n for price in prices:\n sell = max(sell, hold + price)\n hold = max(hold, sell - price)\n\n return sell\n", | |
| "title": "122. Best Time to Buy and Sell Stock II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 165 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxProfit(self, prices: list[int]) -> int:\n sellTwo = 0\n holdTwo = -math.inf\n sellOne = 0\n holdOne = -math.inf\n\n for price in prices:\n sellTwo = max(sellTwo, holdTwo + price)\n holdTwo = max(holdTwo, sellOne - price)\n sellOne = max(sellOne, holdOne + price)\n holdOne = max(holdOne, -price)\n\n return sellTwo\n", | |
| "title": "123. Best Time to Buy and Sell Stock III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 166 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxPathSum(self, root: TreeNode | None) -> int:\n ans = -math.inf\n\n def maxPathSumDownFrom(root: TreeNode | None) -> int:\n \"\"\"\n Returns the maximum path sum starting from the current root, where\n root.val is always included.\n \"\"\"\n nonlocal ans\n if not root:\n return 0\n\n l = max(0, maxPathSumDownFrom(root.left))\n r = max(0, maxPathSumDownFrom(root.right))\n ans = max(ans, root.val + l + r)\n return root.val + max(l, r)\n\n maxPathSumDownFrom(root)\n return ans\n", | |
| "title": "124. Binary Tree Maximum Path Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 167 | |
| }, | |
| { | |
| "code": "class Solution:\n def isPalindrome(self, s: str) -> bool:\n l = 0\n r = len(s) - 1\n\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\n return True\n", | |
| "title": "125. Valid Palindrome", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 168 | |
| }, | |
| { | |
| "code": "class Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: list[str]) -> list[list[str]]:\n wordSet = set(wordList)\n if endWord not in wordList:\n return []\n\n # {\"hit\": [\"hot\"], \"hot\": [\"dot\", \"lot\"], ...}\n graph: dict[str, list[str]] = collections.defaultdict(list)\n\n # Build the graph from the beginWord to the endWord.\n if not self._bfs(beginWord, endWord, wordSet, graph):\n return []\n\n ans = []\n self._dfs(graph, beginWord, endWord, [beginWord], ans)\n return ans\n\n def _bfs(\n self,\n beginWord: str,\n endWord: str,\n wordSet: set[str],\n graph: dict[str, list[str]],\n ) -> bool:\n currentLevelWords = {beginWord}\n\n while currentLevelWords:\n for word in currentLevelWords:\n wordSet.discard(word)\n nextLevelWords = set()\n reachEndWord = False\n for parent in currentLevelWords:\n for child in self._getChildren(parent, wordSet):\n if child in wordSet:\n nextLevelWords.add(child)\n graph[parent].append(child)\n if child == endWord:\n reachEndWord = True\n if reachEndWord:\n return True\n currentLevelWords = nextLevelWords\n\n return False\n\n def _getChildren(self, parent: str, wordSet: set[str]) -> list[str]:\n children = []\n s = list(parent)\n\n for i, cache in enumerate(s):\n for c in string.ascii_lowercase:\n if c == cache:\n continue\n s[i] = c\n child = ''.join(s)\n if child in wordSet:\n children.append(child)\n s[i] = cache\n\n return children\n\n def _dfs(\n self,\n graph: dict[str, list[str]],\n word: str,\n endWord: str,\n path: list[str],\n ans: list[list[str]],\n ) -> None:\n if word == endWord:\n ans.append(path.copy())\n return\n\n for child in graph.get(word, []):\n path.append(child)\n self._dfs(graph, child, endWord, path, ans)\n path.pop()\n", | |
| "title": "126. Word Ladder II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 169 | |
| }, | |
| { | |
| "code": "class Solution:\n def ladderLength(\n self,\n beginWord: str,\n endWord: str,\n wordList: list[str],\n ) -> int:\n wordSet = set(wordList)\n if endWord not in wordSet:\n return 0\n\n q = collections.deque([beginWord])\n\n step = 1\n while q:\n for _ in range(len(q)):\n wordList = list(q.popleft())\n for i, cache in enumerate(wordList):\n for c in string.ascii_lowercase:\n wordList[i] = c\n word = ''.join(wordList)\n if word == endWord:\n return step + 1\n if word in wordSet:\n q.append(word)\n wordSet.remove(word)\n wordList[i] = cache\n step += 1\n\n return 0\n", | |
| "title": "127. Word Ladder", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 170 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestConsecutive(self, nums: list[int]) -> int:\n ans = 0\n seen = set(nums)\n\n for num in seen:\n # `num` is the start of a sequence.\n if num - 1 in seen:\n continue\n length = 0\n while num in seen:\n num += 1\n length += 1\n ans = max(ans, length)\n\n return ans\n", | |
| "title": "128. Longest Consecutive Sequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 171 | |
| }, | |
| { | |
| "code": "class Solution:\n def sumNumbers(self, root: TreeNode | None) -> int:\n ans = 0\n\n def dfs(root: TreeNode | None, path: int) -> None:\n nonlocal ans\n if not root:\n return\n if not root.left and not root.right:\n ans += path * 10 + root.val\n return\n\n dfs(root.left, path * 10 + root.val)\n dfs(root.right, path * 10 + root.val)\n\n dfs(root, 0)\n return ans\n", | |
| "title": "129. Sum Root to Leaf Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 172 | |
| }, | |
| { | |
| "code": "class Solution:\n def solve(self, board: list[list[str]]) -> None:\n if not board:\n return\n\n m = len(board)\n n = len(board[0])\n\n def dfs(i: int, j: int) -> None:\n \"\"\"Marks the grids with 'O' that stretch from the four sides to '*'.\"\"\"\n if i < 0 or i == m or j < 0 or j == n:\n return\n if board[i][j] != 'O':\n return\n board[i][j] = '*'\n dfs(i + 1, j)\n dfs(i - 1, j)\n dfs(i, j + 1)\n dfs(i, j - 1)\n\n for i in range(m):\n for j in range(n):\n if i * j == 0 or i == m - 1 or j == n - 1:\n dfs(i, j)\n\n for row in board:\n for i, c in enumerate(row):\n row[i] = 'O' if c == '*' else 'X'\n", | |
| "title": "130. Surrounded Regions", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 173 | |
| }, | |
| { | |
| "code": "class Solution:\n def partition(self, s: str) -> list[list[str]]:\n ans = []\n\n def isPalindrome(s: str) -> bool:\n return s == s[::-1]\n\n def dfs(s: str, j: int, path: list[str], ans: list[list[str]]) -> None:\n if j == len(s):\n ans.append(path)\n return\n\n for i in range(j, len(s)):\n if isPalindrome(s[j: i + 1]):\n dfs(s, i + 1, path + [s[j: i + 1]], ans)\n\n dfs(s, 0, [], ans)\n return ans\n", | |
| "title": "131. Palindrome Partitioning", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 174 | |
| }, | |
| { | |
| "code": "class Solution:\n def minCut(self, s: str) -> int:\n n = len(s)\n # isPalindrome[i][j] := True if s[i..j] is a palindrome\n isPalindrome = [[True] * n for _ in range(n)]\n # dp[i] := the minimum cuts needed for a palindrome partitioning of s[0..i]\n dp = [n] * n\n\n for l in range(2, n + 1):\n i = 0\n for j in range(l - 1, n):\n isPalindrome[i][j] = s[i] == s[j] and isPalindrome[i + 1][j - 1]\n i += 1\n\n for i in range(n):\n if isPalindrome[0][i]:\n dp[i] = 0\n continue\n\n # Try all the possible partitions.\n for j in range(i):\n if isPalindrome[j + 1][i]:\n dp[i] = min(dp[i], dp[j] + 1)\n\n return dp[-1]\n", | |
| "title": "132. Palindrome Partitioning II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 175 | |
| }, | |
| { | |
| "code": "class Solution:\n def cloneGraph(self, node: 'Node') -> 'Node':\n if not node:\n return None\n if node in self.map:\n return self.map[node]\n\n newNode = Node(node.val, [])\n self.map[node] = newNode\n\n for neighbor in node.neighbors:\n self.map[node].neighbors.append(self.cloneGraph(neighbor))\n\n return newNode\n\n map = {}\n", | |
| "title": "133. Clone Graph", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 176 | |
| }, | |
| { | |
| "code": "class Solution:\n def canCompleteCircuit(self, gas: list[int], cost: list[int]) -> int:\n ans = 0\n net = 0\n summ = 0\n\n # Try to start from each index.\n for i in range(len(gas)):\n net += gas[i] - cost[i]\n summ += gas[i] - cost[i]\n if summ < 0:\n summ = 0\n ans = i + 1 # Start from the next index.\n\n return -1 if net < 0 else ans\n", | |
| "title": "134. Gas Station", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 177 | |
| }, | |
| { | |
| "code": "class Solution:\n def candy(self, ratings: list[int]) -> int:\n n = len(ratings)\n\n ans = 0\n l = [1] * n\n r = [1] * n\n\n for i in range(1, n):\n if ratings[i] > ratings[i - 1]:\n l[i] = l[i - 1] + 1\n\n for i in range(n - 2, -1, -1):\n if ratings[i] > ratings[i + 1]:\n r[i] = r[i + 1] + 1\n\n for a, b in zip(l, r):\n ans += max(a, b)\n\n return ans\n", | |
| "title": "135. Candy", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 178 | |
| }, | |
| { | |
| "code": "class Solution:\n def singleNumber(self, nums: list[int]) -> int:\n return functools.reduce(operator.xor, nums, 0)\n", | |
| "title": "136. Single Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 179 | |
| }, | |
| { | |
| "code": "class Solution:\n def singleNumber(self, nums: list[int]) -> int:\n ones = 0\n twos = 0\n\n for num in nums:\n ones ^= (num & ~twos)\n twos ^= (num & ~ones)\n\n return ones\n", | |
| "title": "137. Single Number II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 180 | |
| }, | |
| { | |
| "code": "class Solution:\n def copyRandomList(self, head: 'Node') -> 'Node':\n if not head:\n return None\n if head in self.map:\n return self.map[head]\n\n newNode = Node(head.val)\n self.map[head] = newNode\n newNode.next = self.copyRandomList(head.next)\n newNode.random = self.copyRandomList(head.random)\n return newNode\n\n map = {}\n", | |
| "title": "138. Copy List with Random Pointer", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 181 | |
| }, | |
| { | |
| "code": "class Solution:\n def wordBreak(self, s: str, wordDict: list[str]) -> bool:\n n = len(s)\n maxLength = len(max(wordDict, key=len))\n wordSet = set(wordDict)\n # dp[i] := True if s[0..i) can be segmented\n dp = [True] + [False] * n\n\n for i in range(1, n + 1):\n for j in range(i - 1, -1, -1):\n if i - j > maxLength:\n break\n # s[0..j) can be segmented and s[j..i) is in the wordSet, so s[0..i)\n # can be segmented.\n if dp[j] and s[j:i] in wordSet:\n dp[i] = True\n break\n\n return dp[n]\n", | |
| "title": "139. Word Break_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 182 | |
| }, | |
| { | |
| "code": "class Solution:\n def wordBreak(self, s: str, wordDict: list[str]) -> bool:\n wordSet = set(wordDict)\n\n @functools.lru_cache(None)\n def wordBreak(s: str) -> bool:\n \"\"\"Returns True if s can be segmented.\"\"\"\n if s in wordSet:\n return True\n return any(s[:i] in wordSet and wordBreak(s[i:]) for i in range(len(s)))\n\n return wordBreak(s)\n", | |
| "title": "139. Word Break_3", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 183 | |
| }, | |
| { | |
| "code": "class Solution:\n def wordBreak(self, s: str, wordDict: list[str]) -> bool:\n wordSet = set(wordDict)\n\n @functools.lru_cache(None)\n def wordBreak(i: int) -> bool:\n \"\"\"Returns True if s[i..n) can be segmented.\"\"\"\n if i == len(s):\n return True\n return any(s[i:j] in wordSet and wordBreak(j)\n for j in range(i + 1, len(s) + 1))\n\n return wordBreak(0)\n", | |
| "title": "139. Word Break", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 184 | |
| }, | |
| { | |
| "code": "class Solution:\n def wordBreak(self, s: str, wordDict: list[str]) -> list[str]:\n wordSet = set(wordDict)\n\n @functools.lru_cache(None)\n def wordBreak(s: str) -> list[str]:\n ans = []\n\n # 1 <= len(prefix) < len(s)\n for i in range(1, len(s)):\n prefix = s[:i]\n suffix = s[i:]\n if prefix in wordSet:\n for word in wordBreak(suffix):\n ans.append(prefix + ' ' + word)\n\n # `wordSet` contains the whole string s, so don't add any space.\n if s in wordSet:\n ans.append(s)\n\n return ans\n\n return wordBreak(s)\n", | |
| "title": "140. Word Break II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 185 | |
| }, | |
| { | |
| "code": "class Solution:\n def hasCycle(self, head: ListNode) -> bool:\n slow = head\n fast = head\n\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n return True\n\n return False\n", | |
| "title": "141. Linked List Cycle", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 186 | |
| }, | |
| { | |
| "code": "class Solution:\n def detectCycle(self, head: ListNode) -> ListNode:\n slow = head\n fast = head\n\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n slow = head\n while slow != fast:\n slow = slow.next\n fast = fast.next\n return slow\n\n return None\n", | |
| "title": "142. Linked List Cycle II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 187 | |
| }, | |
| { | |
| "code": "class Solution:\n def reorderList(self, head: ListNode) -> None:\n def findMid(head: ListNode):\n prev = None\n slow = head\n fast = head\n\n while fast and fast.next:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n prev.next = None\n\n return slow\n\n def reverse(head: ListNode) -> ListNode:\n prev = None\n curr = head\n\n while curr:\n next = curr.next\n curr.next = prev\n prev = curr\n curr = next\n\n return prev\n\n def merge(l1: ListNode, l2: ListNode) -> None:\n while l2:\n next = l1.next\n l1.next = l2\n l1 = l2\n l2 = next\n\n if not head or not head.next:\n return\n\n mid = findMid(head)\n reversed = reverse(mid)\n merge(head, reversed)\n", | |
| "title": "143. Reorder List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 188 | |
| }, | |
| { | |
| "code": "class Solution:\n def preorderTraversal(self, root: TreeNode | None) -> list[int]:\n if not root:\n return []\n\n ans = []\n stack = [root]\n\n while stack:\n node = stack.pop()\n ans.append(node.val)\n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\n\n return ans\n", | |
| "title": "144. Binary Tree Preorder Traversal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 189 | |
| }, | |
| { | |
| "code": "class Solution:\n def postorderTraversal(self, root: TreeNode | None) -> list[int]:\n if not root:\n return []\n\n ans = []\n stack = [root]\n\n while stack:\n node = stack.pop()\n ans.append(node.val)\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n\n return ans[::-1]\n", | |
| "title": "145. Binary Tree Postorder Traversal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 190 | |
| }, | |
| { | |
| "code": "class Node:\n def __init__(self, key: int, value: int):\n self.key = key\n self.value = value\n self.prev = None\n self.next = None\n\n\nclass LRUCache:\n def __init__(self, capacity: int):\n self.capacity = capacity\n self.keyToNode = {}\n self.head = Node(-1, -1)\n self.tail = Node(-1, -1)\n self.join(self.head, self.tail)\n\n def get(self, key: int) -> int:\n if key not in self.keyToNode:\n return -1\n\n node = self.keyToNode[key]\n self.remove(node)\n self.moveToHead(node)\n return node.value\n\n def put(self, key: int, value: int) -> None:\n if key in self.keyToNode:\n node = self.keyToNode[key]\n node.value = value\n self.remove(node)\n self.moveToHead(node)\n return\n\n if len(self.keyToNode) == self.capacity:\n lastNode = self.tail.prev\n del self.keyToNode[lastNode.key]\n self.remove(lastNode)\n\n self.moveToHead(Node(key, value))\n self.keyToNode[key] = self.head.next\n\n def join(self, node1: Node, node2: Node):\n node1.next = node2\n node2.prev = node1\n\n def moveToHead(self, node: Node):\n self.join(node, self.head.next)\n self.join(self.head, node)\n\n def remove(self, node: Node):\n self.join(node.prev, node.next)\n", | |
| "title": "146. LRU Cache", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 191 | |
| }, | |
| { | |
| "code": "class Solution:\n def insertionSortList(self, head: ListNode | None) -> ListNode | None:\n dummy = ListNode(0)\n prev = dummy # the last and thus largest of the sorted list\n\n while head: # the current inserting node\n next = head.next # Cache the next inserting node.\n if prev.val >= head.val:\n prev = dummy # Move `prev` to the front.\n while prev.next and prev.next.val < head.val:\n prev = prev.next\n head.next = prev.next\n prev.next = head\n head = next # Update the current inserting node.\n\n return dummy.next\n", | |
| "title": "147. Insertion Sort List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 192 | |
| }, | |
| { | |
| "code": "class Solution:\n def sortList(self, head: ListNode) -> ListNode:\n def split(head: ListNode, k: int) -> ListNode:\n while k > 1 and head:\n head = head.next\n k -= 1\n rest = head.next if head else None\n if head:\n head.next = None\n return rest\n\n def merge(l1: ListNode, l2: ListNode) -> tuple:\n dummy = ListNode(0)\n tail = dummy\n\n while l1 and l2:\n if l1.val > l2.val:\n l1, l2 = l2, l1\n tail.next = l1\n l1 = l1.next\n tail = tail.next\n tail.next = l1 if l1 else l2\n while tail.next:\n tail = tail.next\n\n return dummy.next, tail\n\n length = 0\n curr = head\n while curr:\n length += 1\n curr = curr.next\n\n dummy = ListNode(0, head)\n\n k = 1\n while k < length:\n curr = dummy.next\n tail = dummy\n while curr:\n l = curr\n r = split(l, k)\n curr = split(r, k)\n mergedHead, mergedTail = merge(l, r)\n tail.next = mergedHead\n tail = mergedTail\n k *= 2\n\n return dummy.next\n", | |
| "title": "148. Sort List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 193 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxPoints(self, points: list[list[int]]) -> int:\n ans = 0\n\n def gcd(a: int, b: int) -> int:\n return a if b == 0 else gcd(b, a % b)\n\n def getSlope(p: list[int], q: list[int]) -> tuple[int, int]:\n dx = p[0] - q[0]\n dy = p[1] - q[1]\n if dx == 0:\n return (0, p[0])\n if dy == 0:\n return (p[1], 0)\n d = gcd(dx, dy)\n return (dx // d, dy // d)\n\n for i, p in enumerate(points):\n slopeCount = collections.defaultdict(int)\n samePoints = 1\n maxPoints = 0 # the maximum number of points with the same slope\n for j in range(i + 1, len(points)):\n q = points[j]\n if p == q:\n samePoints += 1\n else:\n slope = getSlope(p, q)\n slopeCount[slope] += 1\n maxPoints = max(maxPoints, slopeCount[slope])\n ans = max(ans, samePoints + maxPoints)\n\n return ans\n", | |
| "title": "149. Max Points on a Line", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 194 | |
| }, | |
| { | |
| "code": "class Solution:\n def evalRPN(self, tokens: list[str]) -> int:\n stack = []\n op = {\n '+': lambda a, b: a + b,\n '-': lambda a, b: a - b,\n '*': lambda a, b: a * b,\n '/': lambda a, b: int(a / b),\n }\n\n for token in tokens:\n if token in op:\n b = stack.pop()\n a = stack.pop()\n stack.append(op[token](a, b))\n else:\n stack.append(int(token))\n\n return stack.pop()\n", | |
| "title": "150. Evaluate Reverse Polish Notation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 195 | |
| }, | |
| { | |
| "code": "class Solution:\n def reverseWords(self, s: str) -> str:\n return ' '.join(reversed(s.split()))\n", | |
| "title": "151. Reverse Words in a String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 196 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxProduct(self, nums: list[int]) -> int:\n ans = nums[0]\n dpMin = nums[0] # the minimum so far\n dpMax = nums[0] # the maximum so far\n\n for i in range(1, len(nums)):\n num = nums[i]\n prevMin = dpMin # dpMin[i - 1]\n prevMax = dpMax # dpMax[i - 1]\n if num < 0:\n dpMin = min(prevMax * num, num)\n dpMax = max(prevMin * num, num)\n else:\n dpMin = min(prevMin * num, num)\n dpMax = max(prevMax * num, num)\n\n ans = max(ans, dpMax)\n\n return ans\n", | |
| "title": "152. Maximum Product Subarray", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 197 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMin(self, nums: list[int]) -> int:\n l = 0\n r = len(nums) - 1\n\n while l < r:\n m = (l + r) // 2\n if nums[m] < nums[r]:\n r = m\n else:\n l = m + 1\n\n return nums[l]\n", | |
| "title": "153. Find Minimum in Rotated Sorted Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 198 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMin(self, nums: list[int]) -> int:\n l = 0\n r = len(nums) - 1\n\n while l < r:\n m = (l + r) // 2\n if nums[m] == nums[r]:\n r -= 1\n elif nums[m] < nums[r]:\n r = m\n else:\n l = m + 1\n\n return nums[l]\n", | |
| "title": "154. Find Minimum in Rotated Sorted Array II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 199 | |
| }, | |
| { | |
| "code": "class MinStack:\n def __init__(self):\n self.stack = []\n\n def push(self, x: int) -> None:\n mn = x if not self.stack else min(self.stack[-1][1], x)\n self.stack.append([x, mn])\n\n def pop(self) -> None:\n self.stack.pop()\n\n def top(self) -> int:\n return self.stack[-1][0]\n\n def getMin(self) -> int:\n return self.stack[-1][1]\n", | |
| "title": "155. Min Stack", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 200 | |
| }, | |
| { | |
| "code": "class Solution:\n def upsideDownBinaryTree(self, root: TreeNode | None) -> TreeNode | None:\n prevRoot = None\n prevRightChild = None\n\n while root:\n nextRoot = root.left # Cache the next root.\n root.left = prevRightChild\n prevRightChild = root.right\n root.right = prevRoot\n prevRoot = root # Record the previous root.\n root = nextRoot # Update the root.\n\n return prevRoot\n", | |
| "title": "156. Binary Tree Upside Down", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 201 | |
| }, | |
| { | |
| "code": "\"\"\"\nThe read4 API is already defined for you.\n def read4(buf4: list[str]) -> int:\n\n# Below is an example of how the read4 API can be called.\nfile = File(\"abcdefghijk\") # File is \"abcdefghijk\", initially file pointer (fp) points to 'a'\nbuf4 = [' '] * 4 # Create buffer with enough space to store characters\nread4(buf4) # Read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'\nread4(buf4) # Read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'\nread4(buf4) # Read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file\n\"\"\"\n\n\nclass Solution:\n def read(self, buf: list[str], n: int) -> int:\n buf4 = [' '] * 4\n i4 = 0 # buf4's index\n n4 = 0 # buf4's size\n i = 0 # buf's index\n\n while i < n:\n if i4 == n4: # All the characters in the buf4 are consumed.\n i4 = 0 # Reset the buf4's index.\n n4 = read4(buf4) # Read <= 4 characters from the file to the buf4.\n if n4 == 0: # Reach the EOF.\n return i\n buf[i] = buf4[i4]\n i += 1\n i4 += 1\n\n return i\n", | |
| "title": "157. Read N Characters Given Read4", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 202 | |
| }, | |
| { | |
| "code": "# The read4 API is already defined for you.\n# Def read4(buf4: list[str]) -> int:\n\nclass Solution:\n def read(self, buf: list[str], n: int) -> int:\n i = 0 # buf's index\n\n while i < n:\n if self.i4 == self.n4: # All the characters in the buf4 are consumed.\n self.i4 = 0 # Reset the buf4's index.\n # Read <= 4 characters from the file to the buf4.\n self.n4 = read4(self.buf4)\n if self.n4 == 0: # Reach the EOF.\n return i\n buf[i] = self.buf4[self.i4]\n i += 1\n self.i4 += 1\n\n return i\n\n buf4 = [' '] * 4\n i4 = 0 # buf4's index\n n4 = 0 # buf4's size\n", | |
| "title": "158. Read N Characters Given Read4 II - Call multiple times", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 203 | |
| }, | |
| { | |
| "code": "class Solution:\n def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:\n ans = 0\n distinct = 0\n count = [0] * 128\n\n l = 0\n for r, c in enumerate(s):\n count[ord(c)] += 1\n if count[ord(c)] == 1:\n distinct += 1\n while distinct == 3:\n count[ord(s[l])] -= 1\n if count[ord(s[l])] == 0:\n distinct -= 1\n l += 1\n ans = max(ans, r - l + 1)\n\n return ans\n", | |
| "title": "159. Longest Substring with At Most Two Distinct Characters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 204 | |
| }, | |
| { | |
| "code": "class Solution:\n def getIntersectionNode(\n self,\n headA: ListNode,\n headB: ListNode,\n ) -> ListNode | None:\n a = headA\n b = headB\n\n while a != b:\n a = a.next if a else headB\n b = b.next if b else headA\n\n return a\n", | |
| "title": "160. Intersection of Two Linked Lists", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 205 | |
| }, | |
| { | |
| "code": "class Solution:\n def isOneEditDistance(self, s: str, t: str) -> bool:\n m = len(s)\n n = len(t)\n if m > n: # Make sure that |s| <= |t|.\n return self.isOneEditDistance(t, s)\n\n for i in range(m):\n if s[i] != t[i]:\n if m == n:\n return s[i + 1:] == t[i + 1:] # Replace s[i] with t[i].\n return s[i:] == t[i + 1:] # Delete t[i].\n\n return m + 1 == n # Delete t[-1].\n", | |
| "title": "161. One Edit Distance", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 206 | |
| }, | |
| { | |
| "code": "class Solution:\n def findPeakElement(self, nums: list[int]) -> int:\n l = 0\n r = len(nums) - 1\n\n while l < r:\n m = (l + r) // 2\n if nums[m] >= nums[m + 1]:\n r = m\n else:\n l = m + 1\n\n return l\n", | |
| "title": "162. Find Peak Element", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 207 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMissingRanges(\n self,\n nums: list[int],\n lower: int,\n upper: int,\n ) -> list[list[int]]:\n def getRange(lo: int, hi: int) -> list[int]:\n if lo == hi:\n return [lo, lo]\n return [lo, hi]\n\n if not nums:\n return [getRange(lower, upper)]\n\n ans = []\n\n if nums[0] > lower:\n ans.append(getRange(lower, nums[0] - 1))\n\n for prev, curr in zip(nums, nums[1:]):\n if curr > prev + 1:\n ans.append(getRange(prev + 1, curr - 1))\n\n if nums[-1] < upper:\n ans.append(getRange(nums[-1] + 1, upper))\n\n return ans\n", | |
| "title": "163. Missing Ranges", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 208 | |
| }, | |
| { | |
| "code": "class Bucket:\n def __init__(self, mn: int, mx: int):\n self.mn = mn\n self.mx = mx\n\n\nclass Solution:\n def maximumGap(self, nums: list[int]) -> int:\n if len(nums) < 2:\n return 0\n\n mn = min(nums)\n mx = max(nums)\n if mn == mx:\n return 0\n\n gap = math.ceil((mx - mn) / (len(nums) - 1))\n bucketSize = (mx - mn) // gap + 1\n buckets = [Bucket(math.inf, -math.inf) for _ in range(bucketSize)]\n\n for num in nums:\n i = (num - mn) // gap\n buckets[i].mn = min(buckets[i].mn, num)\n buckets[i].mx = max(buckets[i].mx, num)\n\n ans = 0\n prevMax = mn\n\n for bucket in buckets:\n if bucket.mn == math.inf:\n continue # empty bucket\n ans = max(ans, bucket.mn - prevMax)\n prevMax = bucket.mx\n\n return ans\n", | |
| "title": "164. Maximum Gap", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 209 | |
| }, | |
| { | |
| "code": "class Solution:\n def compareVersion(self, version1: str, version2: str) -> int:\n levels1 = version1.split('.')\n levels2 = version2.split('.')\n length = max(len(levels1), len(levels2))\n\n for i in range(length):\n v1 = int(levels1[i]) if i < len(levels1) else 0\n v2 = int(levels2[i]) if i < len(levels2) else 0\n if v1 < v2:\n return -1\n if v1 > v2:\n return 1\n\n return 0\n", | |
| "title": "165. Compare Version Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 210 | |
| }, | |
| { | |
| "code": "class Solution:\n def fractionToDecimal(self, numerator: int, denominator: int) -> str:\n if numerator == 0:\n return '0'\n\n ans = ''\n\n if (numerator < 0) ^ (denominator < 0):\n ans += '-'\n\n numerator = abs(numerator)\n denominator = abs(denominator)\n ans += str(numerator // denominator)\n\n if numerator % denominator == 0:\n return ans\n\n ans += '.'\n dict = {}\n\n remainder = numerator % denominator\n while remainder:\n if remainder in dict:\n ans = ans[:dict[remainder]] + '(' + ans[dict[remainder]:] + ')'\n break\n dict[remainder] = len(ans)\n remainder *= 10\n ans += str(remainder // denominator)\n remainder %= denominator\n\n return ans\n", | |
| "title": "166. Fraction to Recurring Decimal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 211 | |
| }, | |
| { | |
| "code": "class Solution:\n def twoSum(self, numbers: list[int], target: int) -> list[int]:\n l = 0\n r = len(numbers) - 1\n\n while l < r:\n summ = numbers[l] + numbers[r]\n if summ == target:\n return [l + 1, r + 1]\n if summ < target:\n l += 1\n else:\n r -= 1\n", | |
| "title": "167. Two Sum II - Input array is sorted", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 212 | |
| }, | |
| { | |
| "code": "class Solution:\n def convertToTitle(self, n: int) -> str:\n return (self.convertToTitle((n - 1) // 26) + chr(ord('A') + (n - 1) % 26)\n if n\n else '')\n", | |
| "title": "168. Excel Sheet Column Title", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 213 | |
| }, | |
| { | |
| "code": "class Solution:\n def majorityElement(self, nums: list[int]) -> int:\n ans = None\n count = 0\n\n for num in nums:\n if count == 0:\n ans = num\n count += (1 if num == ans else -1)\n\n return ans\n", | |
| "title": "169. Majority Element", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 214 | |
| }, | |
| { | |
| "code": "class TwoSum:\n def __init__(self):\n self.count = collections.Counter()\n\n def add(self, number: int) -> None:\n self.count[number] += 1\n\n def find(self, value: int) -> bool:\n for key, freq in self.count.items():\n remain = value - key\n if key == remain and freq > 1:\n return True\n if key != remain and remain in self.count:\n return True\n\n return False\n", | |
| "title": "170. Two Sum III - Data structure design", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 215 | |
| }, | |
| { | |
| "code": "class Solution:\n def titleToNumber(self, columnTitle: str) -> int:\n return functools.reduce(lambda subtotal, c:\n subtotal * 26 + ord(c) - ord('@'), columnTitle, 0)\n", | |
| "title": "171. Excel Sheet Column Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 216 | |
| }, | |
| { | |
| "code": "class Solution:\n def trailingZeroes(self, n: int) -> int:\n return 0 if n == 0 else n // 5 + self.trailingZeroes(n // 5)\n", | |
| "title": "172. Factorial Trailing Zeroes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 217 | |
| }, | |
| { | |
| "code": "class BSTIterator:\n def __init__(self, root: TreeNode | None):\n self.stack = []\n self._pushLeftsUntilNull(root)\n\n def next(self) -> int:\n root = self.stack.pop()\n self._pushLeftsUntilNull(root.right)\n return root.val\n\n def hasNext(self) -> bool:\n return self.stack\n\n def _pushLeftsUntilNull(self, root: TreeNode | None) -> None:\n while root:\n self.stack.append(root)\n root = root.left\n", | |
| "title": "173. Binary Search Tree Iterator", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 218 | |
| }, | |
| { | |
| "code": "class Solution:\n def calculateMinimumHP(self, dungeon: list[list[int]]) -> int:\n m = len(dungeon)\n n = len(dungeon[0])\n dp = [math.inf] * (n + 1)\n dp[n - 1] = 1\n\n for i in reversed(range(m)):\n for j in reversed(range(n)):\n dp[j] = min(dp[j], dp[j + 1]) - dungeon[i][j]\n dp[j] = max(dp[j], 1)\n\n return dp[0]\n", | |
| "title": "174. Dungeon Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 219 | |
| }, | |
| { | |
| "code": "SELECT\n Person.firstName,\n Person.lastName,\n Address.city,\n Address.state\nFROM Person\nLEFT JOIN Address\n USING (personId);\n", | |
| "title": "175. Combine Two Tables", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 220 | |
| }, | |
| { | |
| "code": "WITH\n RankedEmployees AS (\n SELECT *, DENSE_RANK() OVER(ORDER BY salary DESC) AS `rank`\n FROM Employee\n )\nSELECT MAX(salary) AS SecondHighestSalary\nFROM RankedEmployees\nWHERE `rank` = 2;\n", | |
| "title": "176. Second Highest Salary", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 221 | |
| }, | |
| { | |
| "code": "CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT\nBEGIN\n RETURN (\n WITH\n RankedEmployees AS (\n SELECT *, DENSE_RANK() OVER(ORDER BY salary DESC) AS `rank`\n FROM Employee\n )\n SELECT MAX(salary) AS SecondHighestSalary\n FROM RankedEmployees\n WHERE `rank` = N\n );\nEND\n", | |
| "title": "177. Nth Highest Salary", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 222 | |
| }, | |
| { | |
| "code": "SELECT\n score,\n DENSE_RANK() OVER(ORDER BY score DESC) AS `rank`\nFROM Scores;\n", | |
| "title": "178. Rank Scores", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 223 | |
| }, | |
| { | |
| "code": "class LargerStrKey(str):\n def __lt__(x: str, y: str) -> bool:\n return x + y > y + x\n\n\nclass Solution:\n def largestNumber(self, nums: list[int]) -> str:\n return ''.join(sorted(map(str, nums), key=LargerStrKey)).lstrip('0') or '0'\n", | |
| "title": "179. Largest Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 224 | |
| }, | |
| { | |
| "code": "WITH\n LogsNeighbors AS (\n SELECT\n *,\n LAG(num) OVER(ORDER BY id) AS prev_num,\n LEAD(num) OVER(ORDER BY id) AS next_num\n FROM LOGS\n )\nSELECT DISTINCT num AS ConsecutiveNums\nFROM LogsNeighbors\nWHERE\n num = prev_num\n AND num = next_num;\n", | |
| "title": "180. Consecutive Numbers", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 225 | |
| }, | |
| { | |
| "code": "SELECT Worker.name AS Employee\nFROM Employee AS Worker\nINNER JOIN Employee AS Manager\n ON (Worker.managerId = Manager.id)\nWHERE Worker.salary > Manager.salary;\n", | |
| "title": "181. Employees Earning More Than Their Managers", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 226 | |
| }, | |
| { | |
| "code": "SELECT email\nFROM Person\nGROUP BY 1\nHAVING COUNT(*) > 1;\n", | |
| "title": "182. Duplicate Emails", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 227 | |
| }, | |
| { | |
| "code": "SELECT Customers.name AS Customers\nFROM Customers\nLEFT JOIN Orders\n ON (Customers.id = Orders.customerId)\nWHERE Orders.id IS NULL;\n", | |
| "title": "183. Customers Who Never Order", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 228 | |
| }, | |
| { | |
| "code": "WITH\n EmployeesWithMaxSalaryInDepartment AS (\n SELECT\n Department.name AS department,\n Employee.name AS employee,\n Employee.salary,\n MAX(Employee.salary) OVER(\n PARTITION BY Employee.departmentId\n ) AS max_salary\n FROM Employee\n LEFT JOIN Department\n ON (Employee.departmentId = Department.id)\n )\nSELECT\n department AS Department,\n employee AS Employee,\n salary AS Salary\nFROM EmployeesWithMaxSalaryInDepartment\nWHERE salary = max_salary;\n", | |
| "title": "184. Department Highest Salary", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 229 | |
| }, | |
| { | |
| "code": "WITH\n EmployeesWithRankInDepartment AS (\n SELECT\n Department.name AS department,\n Employee.name AS employee,\n Employee.salary,\n DENSE_RANK() OVER(\n PARTITION BY Employee.departmentId\n ORDER BY Employee.salary DESC\n ) AS `rank`\n FROM Department\n INNER JOIN Employee\n ON (Department.id = Employee.departmentId )\n )\nSELECT\n department AS Department,\n employee AS Employee,\n salary AS Salary\nFROM EmployeesWithRankInDepartment\nWHERE `rank` <= 3;\n", | |
| "title": "185. Department Top Three Salaries", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 230 | |
| }, | |
| { | |
| "code": "class Solution:\n def reverseWords(self, s: list[str]) -> None:\n def reverse(l: int, r: int) -> None:\n while l < r:\n s[l], s[r] = s[r], s[l]\n l += 1\n r -= 1\n\n def reverseWords(n: int) -> None:\n i = 0\n j = 0\n\n while i < n:\n while i < j or (i < n and s[i] == ' '): # Skip the spaces.\n i += 1\n while j < i or (j < n and s[j] != ' '): # Skip the spaces.\n j += 1\n reverse(i, j - 1) # Reverse the word.\n\n reverse(0, len(s) - 1) # Reverse the whole string.\n reverseWords(len(s)) # Reverse each word.\n", | |
| "title": "186. Reverse Words in a String II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 231 | |
| }, | |
| { | |
| "code": "class Solution:\n def findRepeatedDnaSequences(self, s: str) -> list[str]:\n ans = set()\n seen = set()\n\n for i in range(len(s) - 9):\n seq = s[i:i + 10]\n if seq in seen:\n ans.add(seq)\n seen.add(seq)\n\n return list(ans)\n", | |
| "title": "187. Repeated DNA Sequences", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 232 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxProfit(self, k: int, prices: list[int]) -> int:\n if k >= len(prices) // 2:\n sell = 0\n hold = -math.inf\n\n for price in prices:\n sell = max(sell, hold + price)\n hold = max(hold, sell - price)\n\n return sell\n\n sell = [0] * (k + 1)\n hold = [-math.inf] * (k + 1)\n\n for price in prices:\n for i in range(k, 0, -1):\n sell[i] = max(sell[i], hold[i] + price)\n hold[i] = max(hold[i], sell[i - 1] - price)\n\n return sell[k]\n", | |
| "title": "188. Best Time to Buy and Sell Stock IV", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 233 | |
| }, | |
| { | |
| "code": "class Solution:\n def rotate(self, nums: list[int], k: int) -> None:\n k %= len(nums)\n self.reverse(nums, 0, len(nums) - 1)\n self.reverse(nums, 0, k - 1)\n self.reverse(nums, k, len(nums) - 1)\n\n def reverse(self, nums: list[int], l: int, r: int) -> None:\n while l < r:\n nums[l], nums[r] = nums[r], nums[l]\n l += 1\n r -= 1\n", | |
| "title": "189. Rotate Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 234 | |
| }, | |
| { | |
| "code": "class Solution:\n def reverseBits(self, n: int) -> int:\n ans = 0\n\n for i in range(32):\n if n >> i & 1:\n ans |= 1 << 31 - i\n\n return ans\n", | |
| "title": "190. Reverse Bits", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 235 | |
| }, | |
| { | |
| "code": "class Solution:\n def hammingWeight(self, n: int) -> int:\n return n.bit_count()\n", | |
| "title": "191. Number of 1 Bits", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 236 | |
| }, | |
| { | |
| "code": "DELETE P2\nFROM Person AS P1\nINNER JOIN Person AS P2\n ON (P1.email = P2.email)\nWHERE P1.id < P2.id;\n", | |
| "title": "196. Delete Duplicate Emails", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 237 | |
| }, | |
| { | |
| "code": "SELECT Today.id\nFROM Weather AS Today\nINNER JOIN Weather AS Yesterday\n ON (DATE_SUB(Today.recordDate, INTERVAL 1 DAY) = Yesterday.recordDate)\nWHERE Today.temperature > Yesterday.temperature;\n", | |
| "title": "197. Rising Temperature", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 238 | |
| }, | |
| { | |
| "code": "class Solution:\n def rob(self, nums: list[int]) -> int:\n prev1 = 0 # dp[i - 1]\n prev2 = 0 # dp[i - 2]\n\n for num in nums:\n dp = max(prev1, prev2 + num)\n prev2 = prev1\n prev1 = dp\n\n return prev1\n", | |
| "title": "198. House Robber", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 239 | |
| }, | |
| { | |
| "code": "class Solution:\n def rightSideView(self, root: TreeNode | None) -> list[int]:\n ans = []\n\n def dfs(root: TreeNode | None, depth: int) -> None:\n if not root:\n return\n\n if depth == len(ans):\n ans.append(root.val)\n dfs(root.right, depth + 1)\n dfs(root.left, depth + 1)\n\n dfs(root, 0)\n return ans\n", | |
| "title": "199. Binary Tree Right Side View", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 240 | |
| }, | |
| { | |
| "code": "class Solution:\n def numIslands(self, grid: list[list[str]]) -> int:\n m = len(grid)\n n = len(grid[0])\n\n def dfs(i: int, j: int) -> None:\n if i < 0 or i == m or j < 0 or j == n:\n return\n if grid[i][j] != '1':\n return\n\n grid[i][j] = '2' # Mark '2' as visited.\n dfs(i + 1, j)\n dfs(i - 1, j)\n dfs(i, j + 1)\n dfs(i, j - 1)\n\n ans = 0\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == '1':\n dfs(i, j)\n ans += 1\n\n return ans\n", | |
| "title": "200. Number of Islands", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 241 | |
| }, | |
| { | |
| "code": "class Solution:\n def rangeBitwiseAnd(self, m: int, n: int) -> int:\n return self.rangeBitwiseAnd(m >> 1, n >> 1) << 1 if m < n else m\n", | |
| "title": "201. Bitwise AND of Numbers Range", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 242 | |
| }, | |
| { | |
| "code": "class Solution:\n def isHappy(self, n: int) -> bool:\n def squaredSum(n: int) -> bool:\n summ = 0\n while n > 0:\n summ += pow(n % 10, 2)\n n //= 10\n return summ\n\n slow = squaredSum(n)\n fast = squaredSum(squaredSum(n))\n\n while slow != fast:\n slow = squaredSum(slow)\n fast = squaredSum(squaredSum(fast))\n\n return slow == 1\n", | |
| "title": "202. Happy Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 243 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeElements(self, head: ListNode, val: int) -> ListNode:\n dummy = ListNode(0, head)\n prev = dummy\n\n while head:\n if head.val != val:\n prev.next = head\n prev = prev.next\n head = head.next\n prev.next = None\n\n return dummy.next\n", | |
| "title": "203. Remove Linked List Elements", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 244 | |
| }, | |
| { | |
| "code": "class Solution:\n def countPrimes(self, n: int) -> int:\n if n <= 2:\n return 0\n return sum(self._sieveEratosthenes(n))\n\n def _sieveEratosthenes(self, n: int) -> list[bool]:\n isPrime = [True] * n\n isPrime[0] = False\n isPrime[1] = False\n for i in range(2, int(n**0.5) + 1):\n if isPrime[i]:\n for j in range(i * i, n, i):\n isPrime[j] = False\n return isPrime\n", | |
| "title": "204. Count Primes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 245 | |
| }, | |
| { | |
| "code": "class Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return [*map(s.index, s)] == [*map(t.index, t)]\n", | |
| "title": "205. Isomorphic Strings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 246 | |
| }, | |
| { | |
| "code": "class Solution:\n def reverseList(self, head: ListNode | None) -> ListNode | None:\n prev = None\n curr = head\n\n while curr:\n next = curr.next\n curr.next = prev\n prev = curr\n curr = next\n\n return prev\n", | |
| "title": "206. Reverse Linked List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 247 | |
| }, | |
| { | |
| "code": "from enum import Enum\n\n\nclass State(Enum):\n INIT = 0\n VISITING = 1\n VISITED = 2\n\n\nclass Solution:\n def canFinish(self, numCourses: int, prerequisites: list[list[int]]) -> bool:\n graph = [[] for _ in range(numCourses)]\n states = [State.INIT] * numCourses\n\n for v, u in prerequisites:\n graph[u].append(v)\n\n def hasCycle(u: int) -> bool:\n if states[u] == State.VISITING:\n return True\n if states[u] == State.VISITED:\n return False\n states[u] = State.VISITING\n if any(hasCycle(v) for v in graph[u]):\n return True\n states[u] = State.VISITED\n return False\n\n return not any(hasCycle(i) for i in range(numCourses))\n", | |
| "title": "207. Course Schedule", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 248 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: dict[str, TrieNode] = {}\n self.isWord = False\n\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n\n def insert(self, word: str) -> None:\n node: TrieNode = self.root\n for c in word:\n node = node.children.setdefault(c, TrieNode())\n node.isWord = True\n\n def search(self, word: str) -> bool:\n node = self._find(word)\n return node is not None and node.isWord\n\n def startsWith(self, prefix: str) -> bool:\n return self._find(prefix) is not None\n\n def _find(self, prefix: str) -> TrieNode | None:\n node: TrieNode = self.root\n for c in prefix:\n if c not in node.children:\n return None\n node = node.children[c]\n return node\n", | |
| "title": "208. Implement Trie (Prefix Tree)", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 249 | |
| }, | |
| { | |
| "code": "class Solution:\n def minSubArrayLen(self, target: int, nums: list[int]) -> int:\n ans = math.inf\n summ = 0\n j = 0\n\n for i, num in enumerate(nums):\n summ += num\n while summ >= target:\n ans = min(ans, i - j + 1)\n summ -= nums[j]\n j += 1\n\n return 0 if ans == math.inf else ans\n", | |
| "title": "209. Minimum Size Subarray Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 250 | |
| }, | |
| { | |
| "code": "class Solution:\n def findOrder(\n self,\n numCourses: int,\n prerequisites: list[list[int]],\n ) -> list[int]:\n ans = []\n graph = [[] for _ in range(numCourses)]\n inDegrees = [0] * numCourses\n q = collections.deque()\n\n # Build the graph.\n for v, u in prerequisites:\n graph[u].append(v)\n inDegrees[v] += 1\n\n # Perform topological sorting.\n q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0])\n\n while q:\n u = q.popleft()\n ans.append(u)\n for v in graph[u]:\n inDegrees[v] -= 1\n if inDegrees[v] == 0:\n q.append(v)\n\n return ans if len(ans) == numCourses else []\n", | |
| "title": "210. Course Schedule II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 251 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: dict[str, TrieNode] = {}\n self.isWord = False\n\n\nclass WordDictionary:\n def __init__(self):\n self.root = TrieNode()\n\n def addWord(self, word: str) -> None:\n node: TrieNode = self.root\n for c in word:\n node = node.children.setdefault(c, TrieNode())\n node.isWord = True\n\n def search(self, word: str) -> bool:\n return self._dfs(word, 0, self.root)\n\n def _dfs(self, word: str, s: int, node: TrieNode) -> bool:\n if s == len(word):\n return node.isWord\n if word[s] != '.':\n child: TrieNode = node.children.get(word[s], None)\n return self._dfs(word, s + 1, child) if child else False\n return any(self._dfs(word, s + 1, child) for child in node.children.values())\n", | |
| "title": "211. Add and Search Word - Data structure design", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 252 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: dict[str, TrieNode] = {}\n self.word: str | None = None\n\n\nclass Solution:\n def findWords(self, board: list[list[str]], words: list[str]) -> list[str]:\n m = len(board)\n n = len(board[0])\n ans = []\n root = TrieNode()\n\n def insert(word: str) -> None:\n node = root\n for c in word:\n node = node.children.setdefault(c, TrieNode())\n node.word = word\n\n for word in words:\n insert(word)\n\n def dfs(i: int, j: int, node: TrieNode) -> None:\n if i < 0 or i == m or j < 0 or j == n:\n return\n if board[i][j] == '*':\n return\n\n c = board[i][j]\n if c not in node.children:\n return\n\n child = node.children[c]\n if child.word:\n ans.append(child.word)\n child.word = None\n\n board[i][j] = '*'\n dfs(i + 1, j, child)\n dfs(i - 1, j, child)\n dfs(i, j + 1, child)\n dfs(i, j - 1, child)\n board[i][j] = c\n\n for i in range(m):\n for j in range(n):\n dfs(i, j, root)\n\n return ans\n", | |
| "title": "212. Word Search II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 253 | |
| }, | |
| { | |
| "code": "class Solution:\n def rob(self, nums: list[int]) -> int:\n if not nums:\n return 0\n if len(nums) < 2:\n return nums[0]\n\n def rob(l: int, r: int) -> int:\n dp1 = 0\n dp2 = 0\n\n for i in range(l, r + 1):\n temp = dp1\n dp1 = max(dp1, dp2 + nums[i])\n dp2 = temp\n\n return dp1\n\n return max(rob(0, len(nums) - 2),\n rob(1, len(nums) - 1))\n", | |
| "title": "213. House Robber II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 254 | |
| }, | |
| { | |
| "code": "class Solution:\n def shortestPalindrome(self, s: str) -> str:\n t = s[::-1]\n\n for i in range(len(t)):\n if s.startswith(t[i:]):\n return t[:i] + s\n\n return t + s\n", | |
| "title": "214. Shortest Palindrome", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 255 | |
| }, | |
| { | |
| "code": "class Solution:\n def findKthLargest(self, nums: list[int], k: int) -> int:\n minHeap = []\n\n for num in nums:\n heapq.heappush(minHeap, num)\n if len(minHeap) > k:\n heapq.heappop(minHeap)\n\n return minHeap[0]\n", | |
| "title": "215. Kth Largest Element in an Array_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 256 | |
| }, | |
| { | |
| "code": "class Solution:\n def findKthLargest(self, nums: list[int], k: int) -> int:\n def quickSelect(l: int, r: int, k: int) -> int:\n pivot = nums[r]\n\n nextSwapped = l\n for i in range(l, r):\n if nums[i] >= pivot:\n nums[nextSwapped], nums[i] = nums[i], nums[nextSwapped]\n nextSwapped += 1\n nums[nextSwapped], nums[r] = nums[r], nums[nextSwapped]\n\n count = nextSwapped - l + 1 # Number of nums >= pivot\n if count == k:\n return nums[nextSwapped]\n if count > k:\n return quickSelect(l, nextSwapped - 1, k)\n return quickSelect(nextSwapped + 1, r, k - count)\n\n return quickSelect(0, len(nums) - 1, k)\n", | |
| "title": "215. Kth Largest Element in an Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 257 | |
| }, | |
| { | |
| "code": "class Solution:\n def combinationSum3(self, k: int, n: int) -> list[list[int]]:\n ans = []\n\n def dfs(k: int, n: int, s: int, path: list[int]) -> None:\n if k == 0 and n == 0:\n ans.append(path)\n return\n if k == 0 or n < 0:\n return\n\n for i in range(s, 10):\n dfs(k - 1, n - i, i + 1, path + [i])\n\n dfs(k, n, 1, [])\n return ans\n", | |
| "title": "216. Combination Sum III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 258 | |
| }, | |
| { | |
| "code": "class Solution:\n def containsDuplicate(self, nums: list[int]) -> bool:\n return len(nums) != len(set(nums))\n", | |
| "title": "217. Contains Duplicate", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 259 | |
| }, | |
| { | |
| "code": "class Solution:\n def getSkyline(self, buildings: list[list[int]]) -> list[list[int]]:\n n = len(buildings)\n if n == 0:\n return []\n if n == 1:\n left, right, height = buildings[0]\n return [[left, height], [right, 0]]\n\n left = self.getSkyline(buildings[:n // 2])\n right = self.getSkyline(buildings[n // 2:])\n return self._merge(left, right)\n\n def _merge(self, left: list[list[int]],\n right: list[list[int]]) -> list[list[int]]:\n ans = []\n i = 0 # left's index\n j = 0 # right's index\n leftY = 0\n rightY = 0\n\n while i < len(left) and j < len(right):\n # Choose the powith smaller x\n if left[i][0] < right[j][0]:\n leftY = left[i][1] # Update the ongoing `leftY`.\n self._addPoint(ans, left[i][0], max(left[i][1], rightY))\n i += 1\n else:\n rightY = right[j][1] # Update the ongoing `rightY`.\n self._addPoint(ans, right[j][0], max(right[j][1], leftY))\n j += 1\n\n while i < len(left):\n self._addPoint(ans, left[i][0], left[i][1])\n i += 1\n\n while j < len(right):\n self._addPoint(ans, right[j][0], right[j][1])\n j += 1\n\n return ans\n\n def _addPoint(self, ans: list[list[int]], x: int, y: int) -> None:\n if ans and ans[-1][0] == x:\n ans[-1][1] = y\n return\n if ans and ans[-1][1] == y:\n return\n ans.append([x, y])\n", | |
| "title": "218. The Skyline Problem", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 260 | |
| }, | |
| { | |
| "code": "class Solution:\n def containsNearbyDuplicate(self, nums: list[int], k: int) -> bool:\n seen = set()\n\n for i, num in enumerate(nums):\n if i > k:\n seen.remove(nums[i - k - 1])\n if num in seen:\n return True\n seen.add(num)\n\n return False\n", | |
| "title": "219. Contains Duplicate II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 261 | |
| }, | |
| { | |
| "code": "class Solution:\n def containsNearbyAlmostDuplicate(\n self,\n nums: list[int],\n indexDiff: int,\n valueDiff: int,\n ) -> bool:\n if not nums or indexDiff <= 0 or valueDiff < 0:\n return False\n\n mn = min(nums)\n diff = valueDiff + 1 # In case that `valueDiff` equals 0.\n bucket = {}\n\n def getKey(num: int) -> int:\n return (num - mn) // diff\n\n for i, num in enumerate(nums):\n key = getKey(num)\n if key in bucket: # the current bucket\n return True\n # the left adjacent bucket\n if key - 1 in bucket and num - bucket[key - 1] < diff:\n return True\n # the right adjacent bucket\n if key + 1 in bucket and bucket[key + 1] - num < diff:\n return True\n bucket[key] = num\n if i >= indexDiff:\n del bucket[getKey(nums[i - indexDiff])]\n\n return False\n", | |
| "title": "220. Contains Duplicate III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 262 | |
| }, | |
| { | |
| "code": "class Solution:\n def maximalSquare(self, matrix: list[list[str]]) -> int:\n m = len(matrix)\n n = len(matrix[0])\n dp = [0] * n\n maxLength = 0\n prev = 0 # dp[i - 1][j - 1]\n\n for i in range(m):\n for j in range(n):\n cache = dp[j]\n if i == 0 or j == 0 or matrix[i][j] == '0':\n dp[j] = 1 if matrix[i][j] == '1' else 0\n else:\n dp[j] = min([prev, dp[j], dp[j - 1]]) + 1\n maxLength = max(maxLength, dp[j])\n prev = cache\n\n return maxLength * maxLength\n", | |
| "title": "221. Maximal Square", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 263 | |
| }, | |
| { | |
| "code": "class Solution:\n def countNodes(self, root: TreeNode | None) -> int:\n if not root:\n return 0\n\n left = root\n right = root\n heightL = 0\n heightR = 0\n\n while left:\n heightL += 1\n left = left.left\n\n while right:\n heightR += 1\n right = right.right\n\n if heightL == heightR: # `root` is a complete tree.\n return pow(2, heightL) - 1\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)\n", | |
| "title": "222. Count Complete Tree Nodes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 264 | |
| }, | |
| { | |
| "code": "class Solution:\n def computeArea(self,\n A: int, B: int, C: int, D: int,\n E: int, F: int, G: int, H: int) -> int:\n x = min(C, G) - max(A, E) if max(A, E) < min(C, G) else 0\n y = min(D, H) - max(B, F) if max(B, F) < min(D, H) else 0\n return (C - A) * (D - B) + (G - E) * (H - F) - x * y\n", | |
| "title": "223. Rectangle Area", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 265 | |
| }, | |
| { | |
| "code": "class Solution:\n def calculate(self, s: str) -> int:\n ans = 0\n num = 0\n sign = 1\n stack = [sign] # stack[-1]: the current environment's sign\n\n for c in s:\n if c.isdigit():\n num = num * 10 + int(c)\n elif c == '(':\n stack.append(sign)\n elif c == ')':\n stack.pop()\n elif c == '+' or c == '-':\n ans += sign * num\n sign = (1 if c == '+' else -1) * stack[-1]\n num = 0\n\n return ans + sign * num\n", | |
| "title": "224. Basic Calculator", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 266 | |
| }, | |
| { | |
| "code": "class MyStack:\n def __init__(self):\n self.q = collections.deque()\n\n def push(self, x: int) -> None:\n self.q.append(x)\n for _ in range(len(self.q) - 1):\n self.q.append(self.q.popleft())\n\n def pop(self) -> int:\n return self.q.popleft()\n\n def top(self) -> int:\n return self.q[0]\n\n def empty(self) -> bool:\n return not self.q\n", | |
| "title": "225. Implement Stack using Queues", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 267 | |
| }, | |
| { | |
| "code": "class Solution:\n def invertTree(self, root: TreeNode | None) -> TreeNode | None:\n if not root:\n return None\n\n left = root.left\n right = root.right\n root.left = self.invertTree(right)\n root.right = self.invertTree(left)\n return root\n", | |
| "title": "226. Invert Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 268 | |
| }, | |
| { | |
| "code": "class Solution:\n def calculate(self, s: str) -> int:\n ans = 0\n prevNum = 0\n currNum = 0\n op = '+'\n\n for i, c in enumerate(s):\n if c.isdigit():\n currNum = currNum * 10 + int(c)\n if not c.isdigit() and c != ' ' or i == len(s) - 1:\n if op == '+' or op == '-':\n ans += prevNum\n prevNum = (currNum if op == '+' else -currNum)\n elif op == '*':\n prevNum *= currNum\n elif op == '/':\n prevNum = int(prevNum / currNum)\n op = c\n currNum = 0\n\n return ans + prevNum\n", | |
| "title": "227. Basic Calculator II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 269 | |
| }, | |
| { | |
| "code": "class Solution:\n def summaryRanges(self, nums: list[int]) -> list[str]:\n ans = []\n\n i = 0\n while i < len(nums):\n begin = nums[i]\n while i < len(nums) - 1 and nums[i] == nums[i + 1] - 1:\n i += 1\n end = nums[i]\n if begin == end:\n ans.append(str(begin))\n else:\n ans.append(str(begin) + \"->\" + str(end))\n i += 1\n\n return ans\n", | |
| "title": "228. Summary Ranges", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 270 | |
| }, | |
| { | |
| "code": "class Solution:\n def majorityElement(self, nums: list[int]) -> list[int]:\n ans1 = 0\n ans2 = 1\n count1 = 0\n count2 = 0\n\n for num in nums:\n if num == ans1:\n count1 += 1\n elif num == ans2:\n count2 += 1\n elif count1 == 0:\n ans1 = num\n count1 = 1\n elif count2 == 0:\n ans2 = num\n count2 = 1\n else:\n count1 -= 1\n count2 -= 1\n\n return [ans for ans in (ans1, ans2) if nums.count(ans) > len(nums) // 3]\n", | |
| "title": "229. Majority Element II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 271 | |
| }, | |
| { | |
| "code": "class Solution:\n def kthSmallest(self, root: TreeNode | None, k: int) -> int:\n def countNodes(root: TreeNode | None) -> int:\n if not root:\n return 0\n return 1 + countNodes(root.left) + countNodes(root.right)\n\n leftCount = countNodes(root.left)\n\n if leftCount == k - 1:\n return root.val\n if leftCount >= k:\n return self.kthSmallest(root.left, k)\n return self.kthSmallest(root.right, k - 1 - leftCount) # leftCount < k\n", | |
| "title": "230. Kth Smallest Element in a BST_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 272 | |
| }, | |
| { | |
| "code": "class Solution:\n def kthSmallest(self, root: TreeNode | None, k: int) -> int:\n rank = 0\n ans = 0\n\n def traverse(root: TreeNode | None) -> None:\n nonlocal rank\n nonlocal ans\n if not root:\n return\n\n traverse(root.left)\n rank += 1\n if rank == k:\n ans = root.val\n return\n traverse(root.right)\n\n traverse(root)\n return ans\n", | |
| "title": "230. Kth Smallest Element in a BST", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 273 | |
| }, | |
| { | |
| "code": "class Solution:\n def isPowerOfTwo(self, n: int) -> bool:\n return n >= 0 and n.bit_count() == 1\n", | |
| "title": "231. Power of Two", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 274 | |
| }, | |
| { | |
| "code": "class MyQueue:\n def __init__(self):\n self.input = []\n self.output = []\n\n def push(self, x: int) -> None:\n self.input.append(x)\n\n def pop(self) -> int:\n self.peek()\n return self.output.pop()\n\n def peek(self) -> int:\n if not self.output:\n while self.input:\n self.output.append(self.input.pop())\n return self.output[-1]\n\n def empty(self) -> bool:\n return not self.input and not self.output\n", | |
| "title": "232. Implement Queue using Stacks", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 275 | |
| }, | |
| { | |
| "code": "class Solution:\n def countDigitOne(self, n: int) -> int:\n ans = 0\n\n pow10 = 1\n while pow10 <= n:\n divisor = pow10 * 10\n quotient = n // divisor\n remainder = n % divisor\n if quotient > 0:\n ans += quotient * pow10\n if remainder >= pow10:\n ans += min(remainder - pow10 + 1, pow10)\n pow10 *= 10\n\n return ans\n", | |
| "title": "233. Number of Digit One", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 276 | |
| }, | |
| { | |
| "code": "class Solution:\n def isPalindrome(self, head: ListNode) -> bool:\n def reverseList(head: ListNode) -> ListNode:\n prev = None\n curr = head\n while curr:\n next = curr.next\n curr.next = prev\n prev = curr\n curr = next\n return prev\n\n slow = head\n fast = head\n\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n\n if fast:\n slow = slow.next\n slow = reverseList(slow)\n\n while slow:\n if slow.val != head.val:\n return False\n slow = slow.next\n head = head.next\n\n return True\n", | |
| "title": "234. Palindrome Linked List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 277 | |
| }, | |
| { | |
| "code": "class Solution:\n def lowestCommonAncestor(\n self,\n root: 'TreeNode',\n p: 'TreeNode',\n q: 'TreeNode',\n ) -> 'TreeNode':\n if root.val > max(p.val, q.val):\n return self.lowestCommonAncestor(root.left, p, q)\n if root.val < min(p.val, q.val):\n return self.lowestCommonAncestor(root.right, p, q)\n return root\n", | |
| "title": "235. Lowest Common Ancestor of a Binary Search Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 278 | |
| }, | |
| { | |
| "code": "class Solution:\n def lowestCommonAncestor(\n self,\n root: TreeNode | None,\n p: TreeNode | None,\n q: TreeNode | None,\n ) -> TreeNode | None:\n q_ = collections.deque([root])\n parent = {root: None}\n ancestors = set() # p's ancestors\n\n # Iterate until we find both p and q.\n while p not in parent or q not in parent:\n root = q_.popleft()\n if root.left:\n parent[root.left] = root\n q_.append(root.left)\n if root.right:\n parent[root.right] = root\n q_.append(root.right)\n\n # Insert all the p's ancestors.\n while p:\n ancestors.add(p)\n p = parent[p] # `p` becomes None in the end.\n\n # Go up from q until we meet any of p's ancestors.\n while q not in ancestors:\n q = parent[q]\n\n return q\n", | |
| "title": "236. Lowest Common Ancestor of a Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 279 | |
| }, | |
| { | |
| "code": "class Solution:\n def deleteNode(self, node):\n node.val = node.next.val\n node.next = node.next.next\n", | |
| "title": "237. Delete Node in a Linked List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 280 | |
| }, | |
| { | |
| "code": "class Solution:\n def productExceptSelf(self, nums: list[int]) -> list[int]:\n n = len(nums)\n ans = [1] * n\n\n # Use ans as the prefix product array.\n for i in range(1, n):\n ans[i] = ans[i - 1] * nums[i - 1]\n\n suffix = 1 # suffix product\n for i, num in reversed(list(enumerate(nums))):\n ans[i] *= suffix\n suffix *= num\n\n return ans\n", | |
| "title": "238. Product of Array Except Self", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 281 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:\n ans = []\n maxQ = collections.deque()\n\n for i, num in enumerate(nums):\n while maxQ and maxQ[-1] < num:\n maxQ.pop()\n maxQ.append(num)\n if i >= k and nums[i - k] == maxQ[0]: # out-of-bounds\n maxQ.popleft()\n if i >= k - 1:\n ans.append(maxQ[0])\n\n return ans\n", | |
| "title": "239. Sliding Window Maximum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 282 | |
| }, | |
| { | |
| "code": "class Solution:\n def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:\n r = 0\n c = len(matrix[0]) - 1\n\n while r < len(matrix) and c >= 0:\n if matrix[r][c] == target:\n return True\n if target < matrix[r][c]:\n c -= 1\n else:\n r += 1\n\n return False\n", | |
| "title": "240. Search a 2D Matrix II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 283 | |
| }, | |
| { | |
| "code": "class Solution:\n @functools.lru_cache(None)\n def diffWaysToCompute(self, expression: str) -> list[int]:\n ans = []\n\n for i, c in enumerate(expression):\n if c in '+-*':\n for a in self.diffWaysToCompute(expression[:i]):\n for b in self.diffWaysToCompute(expression[i + 1:]):\n ans.append(eval(str(a) + c + str(b)))\n\n return ans or [int(expression)]\n", | |
| "title": "241. Different Ways to Add Parentheses", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 284 | |
| }, | |
| { | |
| "code": "class Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n if len(s) != len(t):\n return False\n\n count = collections.Counter(s)\n count.subtract(collections.Counter(t))\n return all(freq == 0 for freq in count.values())\n", | |
| "title": "242. Valid Anagram", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 285 | |
| }, | |
| { | |
| "code": "class Solution:\n def shortestDistance(\n self,\n wordsDict: list[str],\n word1: str,\n word2: str,\n ) -> int:\n ans = len(wordsDict)\n index1 = -1 # wordsdict[index1] == word1\n index2 = -1 # wordsdict[index2] == word2\n\n for i, word in enumerate(wordsDict):\n if word == word1:\n index1 = i\n if index2 != -1:\n ans = min(ans, index1 - index2)\n if word == word2:\n index2 = i\n if index1 != -1:\n ans = min(ans, index2 - index1)\n\n return ans\n", | |
| "title": "243. Shortest Word Distance", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 286 | |
| }, | |
| { | |
| "code": "class WordDistance:\n def __init__(self, wordsDict: list[str]):\n self.wordToIndices = collections.defaultdict(list)\n for i, word in enumerate(wordsDict):\n self.wordToIndices[word].append(i)\n\n def shortest(self, word1: str, word2: str) -> int:\n indices1 = self.wordToIndices[word1]\n indices2 = self.wordToIndices[word2]\n ans = math.inf\n\n i = 0\n j = 0\n while i < len(indices1) and j < len(indices2):\n ans = min(ans, abs(indices1[i] - indices2[j]))\n if indices1[i] < indices2[j]:\n i += 1\n else:\n j += 1\n\n return ans\n", | |
| "title": "244. Shortest Word Distance II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 287 | |
| }, | |
| { | |
| "code": "class Solution:\n def shortestWordDistance(\n self,\n wordsDict: list[str],\n word1: str,\n word2: str,\n ) -> int:\n isSame = word1 == word2\n ans = math.inf\n # If word1 == word2, index1 is the newest index.\n index1 = len(wordsDict)\n # If word1 == word2, index2 is the previous index.\n index2 = -len(wordsDict)\n\n for i, word in enumerate(wordsDict):\n if word == word1:\n if isSame:\n index2 = index1\n index1 = i\n elif word == word2:\n index2 = i\n ans = min(ans, abs(index1 - index2))\n\n return ans\n", | |
| "title": "245. Shortest Word Distance III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 288 | |
| }, | |
| { | |
| "code": "class Solution:\n def isStrobogrammatic(self, num: str) -> bool:\n rotated = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}\n l = 0\n r = len(num) - 1\n\n while l <= r:\n if num[r] not in rotated:\n return False\n if num[l] != rotated[num[r]]:\n return False\n l += 1\n r -= 1\n\n return True\n", | |
| "title": "246. Strobogrammatic Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 289 | |
| }, | |
| { | |
| "code": "class Solution:\n def findStrobogrammatic(self, n: int) -> list[str]:\n def helper(n: int, k: int) -> list[str]:\n if n == 0:\n return ['']\n if n == 1:\n return ['0', '1', '8']\n\n ans = []\n\n for inner in helper(n - 2, k):\n if n < k:\n ans.append('0' + inner + '0')\n ans.append('1' + inner + '1')\n ans.append('6' + inner + '9')\n ans.append('8' + inner + '8')\n ans.append('9' + inner + '6')\n\n return ans\n\n return helper(n, n)\n", | |
| "title": "247. Strobogrammatic Number II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 290 | |
| }, | |
| { | |
| "code": "class Solution:\n def strobogrammaticInRange(self, low: str, high: str) -> int:\n pairs = [['0', '0'], ['1', '1'], ['6', '9'], ['8', '8'], ['9', '6']]\n ans = 0\n\n def dfs(s: list[str], l: int, r: int) -> None:\n nonlocal ans\n if l > r:\n if len(s) == len(low) and ''.join(s) < low:\n return\n if len(s) == len(high) and ''.join(s) > high:\n return\n ans += 1\n return\n\n for leftDigit, rightDigit in pairs:\n if l == r and leftDigit != rightDigit:\n continue\n s[l] = leftDigit\n s[r] = rightDigit\n if len(s) > 1 and s[0] == '0':\n continue\n dfs(s, l + 1, r - 1)\n\n for n in range(len(low), len(high) + 1):\n dfs([' '] * n, 0, n - 1)\n\n return ans\n", | |
| "title": "248. Strobogrammatic Number III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 291 | |
| }, | |
| { | |
| "code": "class Solution:\n def groupStrings(self, strings: list[str]) -> list[list[str]]:\n keyToStrings = collections.defaultdict(list)\n\n def getKey(s: str) -> str:\n \"\"\"\n Returns the key of 's' by pairwise calculation of differences.\n e.g. getKey(\"abc\") -> \"1,1\" because diff(a, b) = 1 and diff(b, c) = 1.\n \"\"\"\n diffs = []\n\n for i in range(1, len(s)):\n diff = (ord(s[i]) - ord(s[i - 1]) + 26) % 26\n diffs.append(str(diff))\n\n return ','.join(diffs)\n\n for s in strings:\n keyToStrings[getKey(s)].append(s)\n\n return keyToStrings.values()\n", | |
| "title": "249. Group Shifted Strings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 292 | |
| }, | |
| { | |
| "code": "class Solution:\n def countUnivalSubtrees(self, root: TreeNode | None) -> int:\n ans = 0\n\n def isUnival(root: TreeNode | None, val: int) -> bool:\n nonlocal ans\n if not root:\n return True\n\n if isUnival(root.left, root.val) & isUnival(root.right, root.val):\n ans += 1\n return root.val == val\n\n return False\n\n isUnival(root, math.inf)\n return ans\n", | |
| "title": "250. Count Univalue Subtrees", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 293 | |
| }, | |
| { | |
| "code": "class Vector2D:\n def __init__(self, vec: list[list[int]]):\n self.vec = []\n self.i = 0\n\n for arr in vec:\n self.vec += arr\n\n def next(self) -> int:\n ans = self.vec[self.i]\n self.i += 1\n return ans\n\n def hasNext(self) -> bool:\n return self.i < len(self.vec)\n", | |
| "title": "251. Flatten 2D Vector", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 294 | |
| }, | |
| { | |
| "code": "class Solution:\n def canAttendMeetings(self, intervals: list[list[int]]) -> bool:\n intervals.sort()\n\n for i in range(1, len(intervals)):\n if intervals[i - 1][1] > intervals[i][0]:\n return False\n\n return True\n", | |
| "title": "252. Meeting Rooms", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 295 | |
| }, | |
| { | |
| "code": "class Solution:\n def minMeetingRooms(self, intervals: list[list[int]]) -> int:\n n = len(intervals)\n ans = 0\n starts = []\n ends = []\n\n for start, end in intervals:\n starts.append(start)\n ends.append(end)\n\n starts.sort()\n ends.sort()\n\n j = 0\n for i in range(n):\n if starts[i] < ends[j]:\n ans += 1\n else:\n j += 1\n\n return ans\n", | |
| "title": "253. Meeting Rooms II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 296 | |
| }, | |
| { | |
| "code": "class Solution:\n def getFactors(self, n: int) -> list[list[int]]:\n ans = []\n\n def dfs(n: int, s: int, path: list[int]) -> None:\n if n <= 1:\n if len(path) > 1:\n ans.append(path.copy())\n return\n\n for i in range(s, n + 1):\n if n % i == 0:\n path.append(i)\n dfs(n // i, i, path)\n path.pop()\n\n dfs(n, 2, []) # The minimum factor is 2.\n return ans\n", | |
| "title": "254. Factor Combinations", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 297 | |
| }, | |
| { | |
| "code": "class Solution:\n def verifyPreorder(self, preorder: list[int]) -> bool:\n i = 0\n\n def dfs(min: int, max: int) -> None:\n nonlocal i\n if i == len(preorder):\n return\n if preorder[i] < min or preorder[i] > max:\n return\n\n val = preorder[i]\n i += 1\n dfs(min, val)\n dfs(val, max)\n\n dfs(-math.inf, math.inf)\n return i == len(preorder)\n", | |
| "title": "255. Verify Preorder Sequence in Binary Search Tree_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 298 | |
| }, | |
| { | |
| "code": "class Solution:\n def verifyPreorder(self, preorder: list[int]) -> list[int]:\n low = -math.inf\n stack = []\n\n for p in preorder:\n if p < low:\n return False\n while stack and stack[-1] < p:\n low = stack.pop()\n stack.append(p)\n\n return True\n", | |
| "title": "255. Verify Preorder Sequence in Binary Search Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 299 | |
| }, | |
| { | |
| "code": "class Solution:\n def minCost(self, costs: list[list[int]]) -> list[list[int]]:\n for i in range(1, len(costs)):\n costs[i][0] += min(costs[i - 1][1], costs[i - 1][2])\n costs[i][1] += min(costs[i - 1][0], costs[i - 1][2])\n costs[i][2] += min(costs[i - 1][0], costs[i - 1][1])\n\n return min(costs[-1])\n", | |
| "title": "256. Paint House", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 300 | |
| }, | |
| { | |
| "code": "class Solution:\n def binaryTreePaths(self, root: TreeNode | None) -> list[str]:\n ans = []\n\n def dfs(root: TreeNode | None, path: list[str]) -> None:\n if not root:\n return\n if not root.left and not root.right:\n ans.append(''.join(path) + str(root.val))\n return\n\n path.append(str(root.val) + '->')\n dfs(root.left, path)\n dfs(root.right, path)\n path.pop()\n\n dfs(root, [])\n return ans\n", | |
| "title": "257. Binary Tree Paths", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 301 | |
| }, | |
| { | |
| "code": "class Solution:\n def addDigits(self, num: int) -> int:\n return 0 if num == 0 else 1 + (num - 1) % 9\n", | |
| "title": "258. Add Digits", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 302 | |
| }, | |
| { | |
| "code": "class Solution:\n def threeSumSmaller(self, nums: list[int], target: int) -> int:\n if len(nums) < 3:\n return 0\n\n ans = 0\n\n nums.sort()\n\n for i in range(len(nums) - 2):\n l = i + 1\n r = len(nums) - 1\n while l < r:\n if nums[i] + nums[l] + nums[r] < target:\n # (nums[i], nums[l], nums[r])\n # (nums[i], nums[l], nums[r - 1])\n # ...,\n # (nums[i], nums[l], nums[l + 1])\n ans += r - l\n l += 1\n else:\n r -= 1\n\n return ans\n", | |
| "title": "259. 3Sum Smaller", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 303 | |
| }, | |
| { | |
| "code": "class Solution:\n def singleNumber(self, nums: list[int]) -> list[int]:\n xors = functools.reduce(operator.xor, nums)\n lowbit = xors & -xors\n ans = [0, 0]\n\n # Seperate `nums` into two groups by `lowbit`.\n for num in nums:\n if num & lowbit:\n ans[0] ^= num\n else:\n ans[1] ^= num\n\n return ans\n", | |
| "title": "260. Single Number III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 304 | |
| }, | |
| { | |
| "code": "class UnionFind:\n def __init__(self, n: int):\n self.count = n\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n self.count -= 1\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def validTree(self, n: int, edges: list[list[int]]) -> bool:\n if n == 0 or len(edges) != n - 1:\n return False\n\n uf = UnionFind(n)\n\n for u, v in edges:\n uf.unionByRank(u, v)\n\n return uf.count == 1\n", | |
| "title": "261. Graph Valid Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 305 | |
| }, | |
| { | |
| "code": "SELECT\n Trips.request_at AS Day,\n ROUND(SUM(Trips.status != 'completed') / COUNT(*), 2) AS 'Cancellation Rate'\nFROM Trips\nINNER JOIN Users AS Clients\n ON (Trips.client_id = Clients.users_id)\nINNER JOIN Users AS Drivers\n ON (Trips.driver_id = Drivers.users_id)\nWHERE Clients.banned = 'No'\n AND Drivers.banned = 'No'\n AND Trips.request_at BETWEEN '2013-10-01' AND '2013-10-03'\nGROUP BY 1;\n", | |
| "title": "262. Trips and Users", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 306 | |
| }, | |
| { | |
| "code": "class Solution:\n def isUgly(self, n: int) -> bool:\n if n == 0:\n return False\n\n for prime in 2, 3, 5:\n while n % prime == 0:\n n //= prime\n\n return n == 1\n", | |
| "title": "263. Ugly Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 307 | |
| }, | |
| { | |
| "code": "class Solution:\n def nthUglyNumber(self, n: int) -> int:\n nums = [1]\n i2 = 0\n i3 = 0\n i5 = 0\n\n while len(nums) < n:\n next2 = nums[i2] * 2\n next3 = nums[i3] * 3\n next5 = nums[i5] * 5\n next = min(next2, next3, next5)\n if next == next2:\n i2 += 1\n if next == next3:\n i3 += 1\n if next == next5:\n i5 += 1\n nums.append(next)\n\n return nums[-1]\n", | |
| "title": "264. Ugly Number II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 308 | |
| }, | |
| { | |
| "code": "class Solution:\n def minCostII(self, costs: list[list[int]]) -> int:\n prevIndex = -1 # the previous minimum index\n prevMin1 = 0 # the minimum cost so far\n prevMin2 = 0 # the second minimum cost so far\n\n for cost in costs: # O(n)\n # the painted index that will achieve the minimum cost after painting the\n # current house\n index = -1\n # the minimum cost after painting the current house\n min1 = math.inf\n # the second minimum cost after painting the current house\n min2 = math.inf\n for i, cst in enumerate(cost): # O(k)\n theCost = cst + (prevMin2 if i == prevIndex else prevMin1)\n if theCost < min1:\n index = i\n min2 = min1\n min1 = theCost\n elif theCost < min2: # min1 <= theCost < min2\n min2 = theCost\n\n prevIndex = index\n prevMin1 = min1\n prevMin2 = min2\n\n return prevMin1\n", | |
| "title": "265. Paint House II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 309 | |
| }, | |
| { | |
| "code": "class Solution:\n def canPermutePalindrome(self, s: str) -> bool:\n seen = set()\n\n for c in s:\n if c in seen:\n seen.remove(c)\n else:\n seen.add(c)\n\n return len(seen) <= 1\n", | |
| "title": "266. Palindrome Permutation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 310 | |
| }, | |
| { | |
| "code": "class Solution:\n def generatePalindromes(self, s: str) -> list[str]:\n count = collections.Counter(s)\n\n # Count odd ones.\n odd = sum(value & 1 for value in count.values())\n\n # Can't form any palindrome.\n if odd > 1:\n return []\n\n ans = []\n candidates = []\n mid = ''\n\n # Get the mid and the candidates characters.\n for key, value in count.items():\n if value % 2 == 1:\n mid += key\n for _ in range(value // 2):\n candidates.append(key)\n\n def dfs(used: list[bool], path: list[str]) -> None:\n \"\"\"Generates all the unique palindromes from the candidates.\"\"\"\n if len(path) == len(candidates):\n ans.append(''.join(path) + mid + ''.join(reversed(path)))\n return\n\n for i, candidate in enumerate(candidates):\n if used[i]:\n continue\n if i > 0 and candidate == candidates[i - 1] and not used[i - 1]:\n continue\n used[i] = True\n path.append(candidate)\n dfs(used, path)\n path.pop()\n used[i] = False\n\n # Backtrack to generate the ans strings.\n dfs([False] * len(candidates), [])\n return ans\n", | |
| "title": "267. Palindrome Permutation II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 311 | |
| }, | |
| { | |
| "code": "class Solution:\n def missingNumber(self, nums: list[int]) -> int:\n ans = len(nums)\n\n for i, num in enumerate(nums):\n ans ^= i ^ num\n\n return ans\n", | |
| "title": "268. Missing Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 312 | |
| }, | |
| { | |
| "code": "class Solution:\n def alienOrder(self, words: list[str]) -> str:\n graph = {}\n inDegrees = [0] * 26\n\n self._buildGraph(graph, words, inDegrees)\n return self._topology(graph, inDegrees)\n\n def _buildGraph(\n self,\n graph: dict[str, set[str]],\n words: list[str],\n inDegrees: list[int],\n ) -> None:\n # Create a node for each character in each word.\n for word in words:\n for c in word:\n if c not in graph:\n graph[c] = set()\n\n for first, second in zip(words, words[1:]):\n length = min(len(first), len(second))\n for j in range(length):\n u = first[j]\n v = second[j]\n if u != v:\n if v not in graph[u]:\n graph[u].add(v)\n inDegrees[ord(v) - ord('a')] += 1\n break # The order of characters after this are meaningless.\n # First = 'ab', second = 'a' . invalid\n if j == length - 1 and len(first) > len(second):\n graph.clear()\n return\n\n def _topology(self, graph: dict[str, set[str]], inDegrees: list[int]) -> str:\n s = ''\n q = collections.deque()\n\n for c in graph:\n if inDegrees[ord(c) - ord('a')] == 0:\n q.append(c)\n\n while q:\n u = q.pop()\n s += u\n for v in graph[u]:\n inDegrees[ord(v) - ord('a')] -= 1\n if inDegrees[ord(v) - ord('a')] == 0:\n q.append(v)\n\n # Words = ['z', 'x', 'y', 'x']\n return s if len(s) == len(graph) else ''\n", | |
| "title": "269. Alien Dictionary", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 313 | |
| }, | |
| { | |
| "code": "class Solution:\n def closestValue(self, root: TreeNode | None, target: float) -> int:\n # If target < root.val, search the left subtree.\n if target < root.val and root.left:\n left = self.closestValue(root.left, target)\n if abs(left - target) <= abs(root.val - target):\n return left\n\n # If target > root.val, search the right subtree.\n if target > root.val and root.right:\n right = self.closestValue(root.right, target)\n if abs(right - target) < abs(root.val - target):\n return right\n\n return root.val\n", | |
| "title": "270. Closest Binary Search Tree Value", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 314 | |
| }, | |
| { | |
| "code": "class Codec:\n def encode(self, strs: list[str]) -> str:\n \"\"\"Encodes a list of strings to a single string.\"\"\"\n return ''.join(str(len(s)) + '/' + s for s in strs)\n\n def decode(self, s: str) -> list[str]:\n \"\"\"Decodes a single string to a list of strings.\"\"\"\n decoded = []\n\n i = 0\n while i < len(s):\n slash = s.find('/', i)\n length = int(s[i:slash])\n i = slash + length + 1\n decoded.append(s[slash + 1:i])\n\n return decoded\n", | |
| "title": "271. Encode and Decode Strings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 315 | |
| }, | |
| { | |
| "code": "class Solution:\n def closestKValues(\n self,\n root: TreeNode | None,\n target: float,\n k: int,\n ) -> list[int]:\n dq = collections.deque()\n\n def inorder(root: TreeNode | None) -> None:\n if not root:\n return\n\n inorder(root.left)\n dq.append(root.val)\n inorder(root.right)\n\n inorder(root)\n\n while len(dq) > k:\n if abs(dq[0] - target) > abs(dq[-1] - target):\n dq.popleft()\n else:\n dq.pop()\n\n return list(dq)\n", | |
| "title": "272. Closest Binary Search Tree Value II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 316 | |
| }, | |
| { | |
| "code": "class Solution:\n def numberToWords(self, num: int) -> str:\n if num == 0:\n return 'Zero'\n\n belowTwenty = ['', 'One', 'Two', 'Three',\n 'Four', 'Five', 'Six', 'Seven',\n 'Eight', 'Nine', 'Ten', 'Eleven',\n 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen',\n 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']\n tens = ['', 'Ten', 'Twenty', 'Thirty', 'Forty',\n 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']\n\n def helper(num: int) -> str:\n if num < 20:\n s = belowTwenty[num]\n elif num < 100:\n s = tens[num // 10] + ' ' + belowTwenty[num % 10]\n elif num < 1000:\n s = helper(num // 100) + ' Hundred ' + helper(num % 100)\n elif num < 1000000:\n s = helper(num // 1000) + ' Thousand ' + helper(num % 1000)\n elif num < 1000000000:\n s = helper(num // 1000000) + ' Million ' + helper(num % 1000000)\n else:\n s = helper(num // 1000000000) + ' Billion ' + helper(num % 1000000000)\n return s.strip()\n\n return helper(num)\n", | |
| "title": "273. Integer to English Words", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 317 | |
| }, | |
| { | |
| "code": "class Solution:\n def hIndex(self, citations: list[int]) -> int:\n n = len(citations)\n\n citations.sort()\n\n for i, citation in enumerate(citations):\n if citation >= n - i:\n return n - i\n\n return 0\n", | |
| "title": "274. H-Index", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 318 | |
| }, | |
| { | |
| "code": "class Solution:\n def hIndex(self, citations: list[int]) -> int:\n n = len(citations)\n return n - bisect.bisect_left(range(n), n,\n key=lambda m: citations[m] + m)\n", | |
| "title": "275. H-Index II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 319 | |
| }, | |
| { | |
| "code": "class Solution:\n def numWays(self, n: int, k: int) -> int:\n if n == 0:\n return 0\n if n == 1:\n return k\n if n == 2:\n return k * k\n\n # dp[i] := the number of ways to pan posts with k colors\n dp = [0] * (n + 1)\n dp[0] = 0\n dp[1] = k\n dp[2] = k * k\n\n for i in range(3, n + 1):\n dp[i] = (dp[i - 1] + dp[i - 2]) * (k - 1)\n\n return dp[n]\n", | |
| "title": "276. Paint Fence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 320 | |
| }, | |
| { | |
| "code": "# The knows API is already defined for you.\n# Returns a bool, whether a knows b\n# Def knows(a: int, b: int) -> bool:\n\n\nclass Solution:\n def findCelebrity(self, n: int) -> int:\n candidate = 0\n\n # Everyone knows the celebrity.\n for i in range(1, n):\n if knows(candidate, i):\n candidate = i\n\n # The candidate knows nobody and everyone knows the celebrity.\n for i in range(n):\n if i < candidate and knows(candidate, i) or not knows(i, candidate):\n return -1\n if i > candidate and not knows(i, candidate):\n return -1\n\n return candidate\n", | |
| "title": "277. Find the Celebrity", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 321 | |
| }, | |
| { | |
| "code": "class Solution:\n def firstBadVersion(self, n: int) -> int:\n l = 1\n r = n\n\n while l < r:\n m = (l + r) >> 1\n if isBadVersion(m):\n r = m\n else:\n l = m + 1\n\n return l\n", | |
| "title": "278. First Bad Version", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 322 | |
| }, | |
| { | |
| "code": "class Solution:\n def numSquares(self, n: int) -> int:\n dp = [n] * (n + 1) # 1^2 x n\n dp[0] = 0 # no way\n dp[1] = 1 # 1^2\n\n for i in range(2, n + 1):\n j = 1\n while j * j <= i:\n dp[i] = min(dp[i], dp[i - j * j] + 1)\n j += 1\n\n return dp[n]\n", | |
| "title": "279. Perfect Squares", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 323 | |
| }, | |
| { | |
| "code": "class Solution:\n def wiggleSort(self, nums: list[int]) -> None:\n # 1. If i is even, then nums[i] <= nums[i - 1].\n # 2. If i is odd, then nums[i] >= nums[i - 1].\n for i in range(1, len(nums)):\n if (i % 2 == 0 and nums[i] > nums[i - 1] or\n i % 2 == 1 and nums[i] < nums[i - 1]):\n nums[i], nums[i - 1] = nums[i - 1], nums[i]\n", | |
| "title": "280. Wiggle Sort", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 324 | |
| }, | |
| { | |
| "code": "class ZigzagIterator:\n def __init__(self, v1: list[int], v2: list[int]):\n def vals():\n for i in itertools.count():\n for v in v1, v2:\n if i < len(v):\n yield v[i]\n self.vals = vals()\n self.n = len(v1) + len(v2)\n\n def next(self):\n self.n -= 1\n return next(self.vals)\n\n def hasNext(self):\n return self.n > 0\n", | |
| "title": "281. Zigzag Iterator", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 325 | |
| }, | |
| { | |
| "code": "class Solution:\n def addOperators(self, num: str, target: int) -> list[str]:\n ans = []\n\n def dfs(start: int, prev: int, eval: int, path: list[str]) -> None:\n if start == len(num):\n if eval == target:\n ans.append(''.join(path))\n return\n\n for i in range(start, len(num)):\n if i > start and num[start] == '0':\n return\n s = num[start:i + 1]\n curr = int(s)\n if start == 0:\n path.append(s)\n dfs(i + 1, curr, curr, path)\n path.pop()\n else:\n for op in ['+', '-', '*']:\n path.append(op + s)\n if op == '+':\n dfs(i + 1, curr, eval + curr, path)\n elif op == '-':\n dfs(i + 1, -curr, eval - curr, path)\n else:\n dfs(i + 1, prev * curr, eval - prev + prev * curr, path)\n path.pop()\n\n dfs(0, 0, 0, [])\n return ans\n", | |
| "title": "282. Expression Add Operators", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 326 | |
| }, | |
| { | |
| "code": "class Solution:\n def moveZeroes(self, nums: list[int]) -> None:\n j = 0\n for num in nums:\n if num != 0:\n nums[j] = num\n j += 1\n\n for i in range(j, len(nums)):\n nums[i] = 0\n", | |
| "title": "283. Move Zeroes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 327 | |
| }, | |
| { | |
| "code": "class PeekingIterator:\n def __init__(self, iterator: Iterator):\n self.iterator = iterator\n self.buffer = self.iterator.next() if self.iterator.hasNext() else None\n\n def peek(self) -> int:\n \"\"\"\n Returns the next element in the iteration without advancing the iterator.\n \"\"\"\n return self.buffer\n\n def next(self) -> int:\n next = self.buffer\n self.buffer = self.iterator.next() if self.iterator.hasNext() else None\n return next\n\n def hasNext(self) -> bool:\n return self.buffer is not None\n", | |
| "title": "284. Peeking Iterator", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 328 | |
| }, | |
| { | |
| "code": "class Solution:\n def inorderSuccessor(\n self,\n root: TreeNode | None,\n p: TreeNode | None,\n ) -> TreeNode | None:\n if not root:\n return None\n if root.val <= p.val:\n return self.inorderSuccessor(root.right, p)\n return self.inorderSuccessor(root.left, p) or root\n", | |
| "title": "285. Inorder Successor in BST", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 329 | |
| }, | |
| { | |
| "code": "class Solution:\n def wallsAndGates(self, rooms: list[list[int]]) -> None:\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n INF = 2**31 - 1\n m = len(rooms)\n n = len(rooms[0])\n q = collections.deque((i, j)\n for i in range(m)\n for j in range(n)\n if rooms[i][j] == 0)\n\n while q:\n i, j = q.popleft()\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if rooms[x][y] != INF:\n continue\n rooms[x][y] = rooms[i][j] + 1\n q.append((x, y))\n", | |
| "title": "286. Walls and Gates", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 330 | |
| }, | |
| { | |
| "code": "class Solution:\n def findDuplicate(self, nums: list[int]) -> int:\n slow = nums[nums[0]]\n fast = nums[nums[nums[0]]]\n\n while slow != fast:\n slow = nums[slow]\n fast = nums[nums[fast]]\n\n slow = nums[0]\n\n while slow != fast:\n slow = nums[slow]\n fast = nums[fast]\n\n return slow\n", | |
| "title": "287. Find the Duplicate Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312226, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 331 | |
| }, | |
| { | |
| "code": "class ValidWordAbbr:\n def __init__(self, dictionary: list[str]):\n self.dict = set(dictionary)\n # T := unique, F := not unique\n self.abbrUnique = {}\n\n for word in self.dict:\n abbr = self._getAbbr(word)\n self.abbrUnique[abbr] = abbr not in self.abbrUnique\n\n def isUnique(self, word: str) -> bool:\n abbr = self._getAbbr(word)\n return abbr not in self.abbrUnique or self.abbrUnique[abbr] and word in self.dict\n\n def _getAbbr(self, s: str) -> str:\n n = len(s)\n if n <= 2:\n return s\n return s[0] + str(n - 2) + s[-1]\n", | |
| "title": "288. Unique Word Abbreviation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 332 | |
| }, | |
| { | |
| "code": "class Solution:\n def gameOfLife(self, board: list[list[int]]) -> None:\n m = len(board)\n n = len(board[0])\n\n for i in range(m):\n for j in range(n):\n ones = 0\n for x in range(max(0, i - 1), min(m, i + 2)):\n for y in range(max(0, j - 1), min(n, j + 2)):\n ones += board[x][y] & 1\n # Any live cell with two or three live neighbors lives on to the next\n # generation.\n if board[i][j] == 1 and (ones == 3 or ones == 4):\n board[i][j] |= 0b10\n # Any dead cell with exactly three live neighbors becomes a live cell,\n # as if by reproduction.\n if board[i][j] == 0 and ones == 3:\n board[i][j] |= 0b10\n\n for i in range(m):\n for j in range(n):\n board[i][j] >>= 1\n", | |
| "title": "289. Game of Life", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 333 | |
| }, | |
| { | |
| "code": "class Solution:\n def wordPattern(self, pattern: str, str: str) -> bool:\n t = str.split()\n return [*map(pattern.index, pattern)] == [*map(t.index, t)]\n", | |
| "title": "290. Word Pattern", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 334 | |
| }, | |
| { | |
| "code": "class Solution:\n def wordPatternMatch(self, pattern: str, s: str) -> bool:\n def isMatch(\n i: int, j: int, charToString: dict[str, str],\n seen: set[str]) -> bool:\n if i == len(pattern) and j == len(s):\n return True\n if i == len(pattern) or j == len(s):\n return False\n\n c = pattern[i]\n\n if c in charToString:\n t = charToString[c]\n # See if we can match t with s[j..n).\n if t not in s[j:]:\n return False\n\n # If there's a match, continue to match the rest.\n return isMatch(i + 1, j + len(t), charToString, seen)\n\n for k in range(j, len(s)):\n t = s[j:k + 1]\n\n # This string is mapped by another character.\n if t in seen:\n continue\n\n charToString[c] = t\n seen.add(t)\n\n if isMatch(i + 1, k + 1, charToString, seen):\n return True\n\n # Backtrack.\n del charToString[c]\n seen.remove(t)\n\n return False\n\n return isMatch(0, 0, {}, set())\n", | |
| "title": "291. Word Pattern II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 335 | |
| }, | |
| { | |
| "code": "class Solution:\n def canWinNim(self, n: int) -> bool:\n return n % 4 != 0\n", | |
| "title": "292. Nim Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 336 | |
| }, | |
| { | |
| "code": "class Solution:\n def generatePossibleNextMoves(self, currentState: str) -> list[str]:\n return [currentState[:i] + '--' + currentState[i + 2:]\n for i, (a, b) in enumerate(zip(currentState, currentState[1:]))\n if a == '+' and b == '+']\n", | |
| "title": "293. Flip Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 337 | |
| }, | |
| { | |
| "code": "class Solution:\n @functools.lru_cache(None)\n def canWin(self, currentState: str) -> bool:\n # If any of currentState[i:i + 2] == \"++\" and your friend can't win after\n # changing currentState[i:i + 2] to \"--\" (or \"-\"), then you can win.\n return any(True\n for i, (a, b) in enumerate(zip(currentState, currentState[1:]))\n if a == '+' and b == '+' and\n not self.canWin(currentState[:i] + '-' + currentState[i + 2:]))\n", | |
| "title": "294. Flip Game II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 338 | |
| }, | |
| { | |
| "code": "class MedianFinder:\n def __init__(self):\n self.maxHeap = []\n self.minHeap = []\n\n def addNum(self, num: int) -> None:\n if not self.maxHeap or num <= -self.maxHeap[0]:\n heapq.heappush(self.maxHeap, -num)\n else:\n heapq.heappush(self.minHeap, num)\n\n # Balance the two heaps s.t.\n # |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1.\n if len(self.maxHeap) < len(self.minHeap):\n heapq.heappush(self.maxHeap, -heapq.heappop(self.minHeap))\n elif len(self.maxHeap) - len(self.minHeap) > 1:\n heapq.heappush(self.minHeap, -heapq.heappop(self.maxHeap))\n\n def findMedian(self) -> float:\n if len(self.maxHeap) == len(self.minHeap):\n return (-self.maxHeap[0] + self.minHeap[0]) / 2.0\n return -self.maxHeap[0]\n", | |
| "title": "295. Find Median from Data Stream", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 339 | |
| }, | |
| { | |
| "code": "class Solution:\n def minTotalDistance(self, grid: list[list[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n # i indices s.t. grid[i][j] == 1\n I = [i for i in range(m) for j in range(n) if grid[i][j]]\n # j indices s.t. grid[i][j] == 1\n J = [j for j in range(n) for i in range(m) if grid[i][j]]\n\n def minTotalDistance(grid: list[int]) -> int:\n summ = 0\n i = 0\n j = len(grid) - 1\n while i < j:\n summ += grid[j] - grid[i]\n i += 1\n j -= 1\n return summ\n\n # sum(i - median(I)) + sum(j - median(J))\n return minTotalDistance(I) + minTotalDistance(J)\n", | |
| "title": "296. Best Meeting Point", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 340 | |
| }, | |
| { | |
| "code": "class Codec:\n def serialize(self, root: 'TreeNode') -> str:\n \"\"\"Encodes a tree to a single string.\"\"\"\n s = []\n\n def preorder(root: 'TreeNode') -> None:\n if not root:\n s.append('n')\n return\n\n s.append(str(root.val))\n preorder(root.left)\n preorder(root.right)\n\n preorder(root)\n return ' '.join(s)\n\n def deserialize(self, data: str) -> 'TreeNode':\n \"\"\"Decodes your encoded data to tree.\"\"\"\n q = collections.deque(data.split())\n\n def preorder() -> 'TreeNode':\n s = q.popleft()\n if s == 'n':\n return None\n\n root = TreeNode(s)\n root.left = preorder()\n root.right = preorder()\n return root\n\n return preorder()\n", | |
| "title": "297. Serialize and Deserialize Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 341 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestConsecutive(self, root: TreeNode | None) -> int:\n if not root:\n return 0\n\n def dfs(root: TreeNode | None, target: int, length: int, maxLength: int) -> int:\n if not root:\n return maxLength\n if root.val == target:\n length += 1\n maxLength = max(maxLength, length)\n else:\n length = 1\n return max(dfs(root.left, root.val + 1, length, maxLength),\n dfs(root.right, root.val + 1, length, maxLength))\n\n return dfs(root, root.val, 0, 0)\n", | |
| "title": "298. Binary Tree Longest Consecutive Sequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 342 | |
| }, | |
| { | |
| "code": "class Solution:\n def getHint(self, secret: str, guess: str) -> str:\n bulls = sum(map(operator.eq, secret, guess))\n bovine = sum(min(secret.count(x), guess.count(x)) for x in set(guess))\n return '%dA%dB' % (bulls, bovine - bulls)\n", | |
| "title": "299. Bulls and Cows", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 343 | |
| }, | |
| { | |
| "code": "class Solution:\n def lengthOfLIS(self, nums: list[int]) -> int:\n # tails[i] := the minimum tails of all the increasing subsequences having\n # length i + 1\n tails = []\n\n for num in nums:\n if not tails or num > tails[-1]:\n tails.append(num)\n else:\n tails[bisect.bisect_left(tails, num)] = num\n\n return len(tails)\n", | |
| "title": "300. Longest Increasing Subsequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 344 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeInvalidParentheses(self, s: str) -> list[str]:\n # Similar to 921. Minimum Add to Make Parentheses Valid\n def getLeftAndRightCounts(s: str) -> tuple[int, int]:\n \"\"\"Returns how many '(' and ')' need to be deleted.\"\"\"\n l = 0\n r = 0\n\n for c in s:\n if c == '(':\n l += 1\n elif c == ')':\n if l == 0:\n r += 1\n else:\n l -= 1\n\n return l, r\n\n def isValid(s: str):\n opened = 0 # the number of '(' - # of ')'\n for c in s:\n if c == '(':\n opened += 1\n elif c == ')':\n opened -= 1\n if opened < 0:\n return False\n return True # opened == 0\n\n ans = []\n\n def dfs(s: str, start: int, l: int, r: int) -> None:\n if l == 0 and r == 0 and isValid(s):\n ans.append(s)\n return\n\n for i in range(start, len(s)):\n if i > start and s[i] == s[i - 1]:\n continue\n if r > 0 and s[i] == ')': # Delete s[i]\n dfs(s[:i] + s[i + 1:], i, l, r - 1)\n elif l > 0 and s[i] == '(': # Delete s[i]\n dfs(s[:i] + s[i + 1:], i, l - 1, r)\n\n l, r = getLeftAndRightCounts(s)\n dfs(s, 0, l, r)\n return ans\n", | |
| "title": "301. Remove Invalid Parentheses", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 345 | |
| }, | |
| { | |
| "code": "class Solution:\n def minArea(self, image: list[list[str]], x: int, y: int) -> int:\n def firstAnyOne(l: int, r: int, allZeros: Callable[[int], bool]) -> int:\n while l < r:\n m = (l + r) // 2\n if allZeros(m):\n l = m + 1\n else:\n r = m\n return l\n\n def firstAllZeros(l: int, r: int, allZeros: Callable[[int], bool]) -> int:\n while l < r:\n m = (l + r) // 2\n if allZeros(m):\n r = m\n else:\n l = m + 1\n return l\n\n def colAllZeros(colIndex: int) -> bool:\n return all(pixel == '0' for pixel in list(zip(*image))[colIndex])\n\n def rowAllZeros(rowIndex: int) -> bool:\n return all(pixel == '0' for pixel in image[rowIndex])\n\n x1 = firstAnyOne(0, x, rowAllZeros)\n x2 = firstAllZeros(x + 1, len(image), rowAllZeros)\n y1 = firstAnyOne(0, y, colAllZeros)\n y2 = firstAllZeros(y + 1, len(image[0]), colAllZeros)\n return (x2 - x1) * (y2 - y1)\n", | |
| "title": "302. Smallest Rectangle Enclosing Black Pixels", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 346 | |
| }, | |
| { | |
| "code": "class NumArray:\n def __init__(self, nums: list[int]):\n self.prefix = list(itertools.accumulate(nums, initial=0))\n\n def sumRange(self, left: int, right: int) -> int:\n return self.prefix[right + 1] - self.prefix[left]\n", | |
| "title": "303. Range Sum Query - Immutable", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 347 | |
| }, | |
| { | |
| "code": "class NumMatrix:\n def __init__(self, matrix: list[list[int]]):\n if not matrix:\n return\n\n m = len(matrix)\n n = len(matrix[0])\n # prefix[i][j] := the sum of matrix[0..i)[0..j)\n self.prefix = [[0] * (n + 1) for _ in range(m + 1)]\n\n for i in range(m):\n for j in range(n):\n self.prefix[i + 1][j + 1] = (matrix[i][j] + self.prefix[i][j + 1] +\n self.prefix[i + 1][j] - self.prefix[i][j])\n\n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n return (self.prefix[row2 + 1][col2 + 1] - self.prefix[row1][col2 + 1] -\n self.prefix[row2 + 1][col1] + self.prefix[row1][col1])\n", | |
| "title": "304. Range Sum Query 2D - Immutable", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 348 | |
| }, | |
| { | |
| "code": "class UnionFind:\n def __init__(self, n: int):\n self.id = [-1] * n\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self.find(u)\n j = self.find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def numIslands2(\n self,\n m: int,\n n: int,\n positions: list[list[int]],\n ) -> list[int]:\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n ans = []\n seen = [[False] * n for _ in range(m)]\n uf = UnionFind(m * n)\n count = 0\n\n def getId(i: int, j: int, n: int) -> int:\n return i * n + j\n\n for i, j in positions:\n if seen[i][j]:\n ans.append(count)\n continue\n seen[i][j] = True\n id = getId(i, j, n)\n uf.id[id] = id\n count += 1\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n neighborId = getId(x, y, n)\n if uf.id[neighborId] == -1: # water\n continue\n currentParent = uf.find(id)\n neighborParent = uf.find(neighborId)\n if currentParent != neighborParent:\n uf.unionByRank(currentParent, neighborParent)\n count -= 1\n ans.append(count)\n\n return ans\n", | |
| "title": "305. Number of Islands II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 349 | |
| }, | |
| { | |
| "code": "class Solution:\n def isAdditiveNumber(self, num: str) -> bool:\n n = len(num)\n\n def dfs(firstNum: int, secondNum: int, s: int) -> bool:\n if s == len(num):\n return True\n\n thirdNum = firstNum + secondNum\n thirdNumStr = str(thirdNum)\n\n return (num.find(thirdNumStr, s) == s and\n dfs(secondNum, thirdNum, s + len(thirdNumStr)))\n\n # num[0..i] = firstNum\n for i in range(n // 2):\n if i > 0 and num[0] == '0':\n return False\n firstNum = int(num[:i + 1])\n # num[i + 1..j] = secondNum\n # |thirdNum| >= max(|firstNum|, |secondNum|)\n j = i + 1\n while max(i, j - i) < n - j:\n if j > i + 1 and num[i + 1] == '0':\n break\n secondNum = int(num[i + 1:j + 1])\n if dfs(firstNum, secondNum, j + 1):\n return True\n j += 1\n\n return False\n", | |
| "title": "306. Additive Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 350 | |
| }, | |
| { | |
| "code": "class FenwickTree:\n def __init__(self, n: int):\n self.sums = [0] * (n + 1)\n\n def add(self, i: int, delta: int) -> None:\n while i < len(self.sums):\n self.sums[i] += delta\n i += FenwickTree.lowbit(i)\n\n def get(self, i: int) -> int:\n summ = 0\n while i > 0:\n summ += self.sums[i]\n i -= FenwickTree.lowbit(i)\n return summ\n\n @staticmethod\n def lowbit(i: int) -> int:\n return i & -i\n\n\nclass NumArray:\n def __init__(self, nums: list[int]):\n self.nums = nums\n self.tree = FenwickTree(len(nums))\n for i, num in enumerate(nums):\n self.tree.add(i + 1, num)\n\n def update(self, index: int, val: int) -> None:\n self.tree.add(index + 1, val - self.nums[index])\n self.nums[index] = val\n\n def sumRange(self, left: int, right: int) -> int:\n return self.tree.get(right + 1) - self.tree.get(left)\n", | |
| "title": "307. Range Sum Query - Mutable", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 351 | |
| }, | |
| { | |
| "code": "class FenwickTree:\n def __init__(self, m: int, n: int):\n self.sums = [[0] * (n + 1) for _ in range(m + 1)]\n\n def add(self, row: int, col: int, delta: int) -> None:\n i = row\n while i < len(self.sums):\n j = col\n while j < len(self.sums[0]):\n self.sums[i][j] += delta\n j += FenwickTree.lowbit(j)\n i += FenwickTree.lowbit(i)\n\n def get(self, row: int, col: int) -> int:\n summ = 0\n i = row\n while i > 0:\n j = col\n while j > 0:\n summ += self.sums[i][j]\n j -= FenwickTree.lowbit(j)\n i -= FenwickTree.lowbit(i)\n return summ\n\n @staticmethod\n def lowbit(i: int) -> int:\n return i & -i\n\n\nclass NumMatrix:\n def __init__(self, matrix: list[list[int]]):\n self.matrix = matrix\n self.tree = FenwickTree(len(matrix), len(matrix[0]))\n\n for i in range(len(matrix)):\n for j, val in enumerate(matrix[i]):\n self.tree.add(i + 1, j + 1, val)\n\n def update(self, row: int, col: int, val: int) -> None:\n self.tree.add(row + 1, col + 1, val - self.matrix[row][col])\n self.matrix[row][col] = val\n\n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n return (self.tree.get(row2 + 1, col2 + 1) - self.tree.get(row1, col2 + 1) -\n self.tree.get(row2 + 1, col1) + self.tree.get(row1, col1))\n", | |
| "title": "308. Range Sum Query 2D - Mutable", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 352 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxProfit(self, prices: list[int]) -> int:\n sell = 0\n hold = -math.inf\n prev = 0\n\n for price in prices:\n cache = sell\n sell = max(sell, hold + price)\n hold = max(hold, prev - price)\n prev = cache\n\n return sell\n", | |
| "title": "309. Best Time to Buy and Sell Stock with Cooldown", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 353 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMinHeightTrees(self, n: int, edges: list[list[int]]) -> list[int]:\n if n == 1 or not edges:\n return [0]\n\n ans = []\n graph = collections.defaultdict(set)\n\n for u, v in edges:\n graph[u].add(v)\n graph[v].add(u)\n\n for label, children in graph.items():\n if len(children) == 1:\n ans.append(label)\n\n while n > 2:\n n -= len(ans)\n nextLeaves = []\n for leaf in ans:\n u = next(iter(graph[leaf]))\n graph[u].remove(leaf)\n if len(graph[u]) == 1:\n nextLeaves.append(u)\n ans = nextLeaves\n\n return ans\n", | |
| "title": "310. Minimum Height Trees", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 354 | |
| }, | |
| { | |
| "code": "class Solution:\n def multiply(self, mat1: list[list[int]],\n mat2: list[list[int]]) -> list[list[int]]:\n m = len(mat1)\n n = len(mat2)\n l = len(mat2[0])\n ans = [[0] * l for _ in range(m)]\n nonZeroColIndicesInMat2 = [\n [j for j, a in enumerate(row) if a]\n for row in mat2\n ]\n\n for i in range(m):\n for j, a in enumerate(mat1[i]):\n if a == 0:\n continue\n # mat1s j-th column matches mat2's j-th row\n for colIndex in nonZeroColIndicesInMat2[j]:\n ans[i][colIndex] += a * mat2[j][colIndex]\n\n return ans\n", | |
| "title": "311. Sparse Matrix Multiplication", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 355 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxCoins(self, nums: list[int]) -> int:\n n = len(nums)\n # dp[i][j] := maxCoins(nums[i..j])\n dp = [[0] * (n + 2) for _ in range(n + 2)]\n\n nums = [1] + nums + [1]\n\n for d in range(n):\n for i in range(1, n - d + 1):\n j = i + d\n for k in range(i, j + 1):\n dp[i][j] = max(\n dp[i][j],\n dp[i][k - 1] +\n dp[k + 1][j] +\n nums[i - 1] * nums[k] * nums[j + 1])\n\n return dp[1][n]\n", | |
| "title": "312. Burst Balloons", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 356 | |
| }, | |
| { | |
| "code": "class UglyNum:\n def __init__(self, prime: int, index: int, value: int):\n self.prime = prime\n self.index = index # Point the next index of uglyNums.\n self.value = value # prime * uglyNums[index]\n\n\nclass Solution:\n def nthSuperUglyNumber(self, n: int, primes: list[int]) -> int:\n minHeap = [] # (value, prime, index)\n uglyNums = [1]\n\n for prime in primes:\n heapq.heappush(minHeap, (prime * uglyNums[0], prime, 1))\n\n while len(uglyNums) < n:\n uglyNums.append(minHeap[0][0])\n while minHeap[0][0] == uglyNums[-1]:\n _, prime, index = heapq.heappop(minHeap)\n heapq.heappush(minHeap, (prime * uglyNums[index], prime, index + 1))\n\n return uglyNums[-1]\n", | |
| "title": "313. Super Ugly Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 357 | |
| }, | |
| { | |
| "code": "class Solution:\n def verticalOrder(self, root: TreeNode | None) -> list[list[int]]:\n if not root:\n return []\n\n range_ = [0] * 2\n\n def getRange(root: TreeNode | None, x: int) -> None:\n if not root:\n return\n\n range_[0] = min(range_[0], x)\n range_[1] = max(range_[1], x)\n\n getRange(root.left, x - 1)\n getRange(root.right, x + 1)\n\n getRange(root, 0) # Get the leftmost and the rightmost x index.\n\n ans = [[] for _ in range(range_[1] - range_[0] + 1)]\n q = collections.deque([(root, -range_[0])]) # (TreeNode, x)\n\n while q:\n node, x = q.popleft()\n ans[x].append(node.val)\n if node.left:\n q.append((node.left, x - 1))\n if node.right:\n q.append((node.right, x + 1))\n\n return ans\n", | |
| "title": "314. Binary Tree Vertical Order Traversal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 358 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass\nclass Item:\n num: int = 0\n index: int = 0\n\n\nclass Solution:\n def countSmaller(self, nums: list[int]) -> list[int]:\n n = len(nums)\n ans = [0] * n\n items = [Item(num, i) for i, num in enumerate(nums)]\n\n self._mergeSort(items, 0, n - 1, ans)\n return ans\n\n def _mergeSort(\n self,\n items: list[Item],\n l: int,\n r: int,\n ans: list[int],\n ) -> None:\n if l >= r:\n return\n\n m = (l + r) // 2\n self._mergeSort(items, l, m, ans)\n self._mergeSort(items, m + 1, r, ans)\n self._merge(items, l, m, r, ans)\n\n def _merge(\n self,\n items: list[Item],\n l: int,\n m: int,\n r: int,\n ans: list[int],\n ) -> None:\n sorted = [Item()] * (r - l + 1)\n k = 0 # sorted's index\n i = l # left's index\n j = m + 1 # right's index\n rightCount = 0 # the number of numbers < items[i].num\n\n while i <= m and j <= r:\n if items[i].num > items[j].num:\n rightCount += 1\n sorted[k] = items[j]\n k += 1\n j += 1\n else:\n ans[items[i].index] += rightCount\n sorted[k] = items[i]\n k += 1\n i += 1\n\n # Put the possible remaining left part into the sorted array.\n while i <= m:\n ans[items[i].index] += rightCount\n sorted[k] = items[i]\n k += 1\n i += 1\n\n # Put the possible remaining right part into the sorted array.\n while j <= r:\n sorted[k] = items[j]\n k += 1\n j += 1\n\n items[l:l + len(sorted)] = sorted\n", | |
| "title": "315. Count of Smaller Numbers After Self", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 359 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n ans = []\n count = collections.Counter(s)\n used = [False] * 26\n\n for c in s:\n count[c] -= 1\n if used[ord(c) - ord('a')]:\n continue\n while ans and ans[-1] > c and count[ans[-1]] > 0:\n used[ord(ans[-1]) - ord('a')] = False\n ans.pop()\n ans.append(c)\n used[ord(ans[-1]) - ord('a')] = True\n\n return ''.join(ans)\n", | |
| "title": "316. Remove Duplicate Letters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 360 | |
| }, | |
| { | |
| "code": "class Solution:\n def shortestDistance(self, grid: list[list[int]]) -> int:\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(grid)\n n = len(grid[0])\n nBuildings = sum(a == 1 for row in grid for a in row)\n ans = math.inf\n # dist[i][j] := the total distance of grid[i][j] (0) to reach all the\n # buildings (1)\n dist = [[0] * n for _ in range(m)]\n # reachCount[i][j] := the number of buildings (1) grid[i][j] (0) can reach\n reachCount = [[0] * n for _ in range(m)]\n\n def bfs(row: int, col: int) -> bool:\n q = collections.deque([(row, col)])\n seen = {(row, col)}\n seenBuildings = 1\n\n step = 1\n while q:\n for _ in range(len(q)):\n i, j = q.popleft()\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if (x, y) in seen:\n continue\n seen.add((x, y))\n if not grid[x][y]:\n dist[x][y] += step\n reachCount[x][y] += 1\n q.append((x, y))\n elif grid[x][y] == 1:\n seenBuildings += 1\n step += 1\n\n # True if all the buildings (1) are connected\n return seenBuildings == nBuildings\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1: # BFS from this building.\n if not bfs(i, j):\n return -1\n\n for i in range(m):\n for j in range(n):\n if reachCount[i][j] == nBuildings:\n ans = min(ans, dist[i][j])\n\n return -1 if ans == math.inf else ans\n", | |
| "title": "317. Shortest Distance from All Buildings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 361 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxProduct(self, words: list[str]) -> int:\n ans = 0\n\n def getMask(word: str) -> int:\n mask = 0\n for c in word:\n mask |= 1 << ord(c) - ord('a')\n return mask\n\n masks = [getMask(word) for word in words]\n\n for i in range(len(words)):\n for j in range(i):\n if not (masks[i] & masks[j]):\n ans = max(ans, len(words[i]) * len(words[j]))\n\n return ans\n", | |
| "title": "318. Maximum Product of Word Lengths", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 362 | |
| }, | |
| { | |
| "code": "class Solution:\n def bulbSwitch(self, n: int) -> int:\n # The k-th bulb can only be switched when k % i == 0.\n # So, we can rephrase the problem:\n # To find number of numbers <= n that have odd factors.\n # Obviously, only square numbers have odd factor(s).\n # e.g. n = 10, only 1, 4, and 9 are square numbers that <= 10\n return math.isqrt(n)\n", | |
| "title": "319. Bulb Switcher", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 363 | |
| }, | |
| { | |
| "code": "class Solution:\n def generateAbbreviations(self, word: str) -> list[str]:\n ans = []\n\n def getCountString(count: int) -> str:\n return str(count) if count > 0 else ''\n\n def dfs(i: int, count: int, path: list[str]) -> None:\n if i == len(word):\n ans.append(''.join(path) + getCountString(count))\n return\n\n # Abbreviate the word[i].\n dfs(i + 1, count + 1, path)\n # Keep the word[i], so consume the count as a string.\n path.append(getCountString(count) + word[i])\n # Reset the count to 0.\n dfs(i + 1, 0, path)\n path.pop()\n\n dfs(0, 0, [])\n return ans\n", | |
| "title": "320. Generalized Abbreviation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 364 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxNumber(self, nums1: list[int], nums2: list[int], k: int) -> list[int]:\n def maxArray(nums: list[int], k: int) -> list[int]:\n res = []\n toTop = len(nums) - k\n for num in nums:\n while res and res[-1] < num and toTop > 0:\n res.pop()\n toTop -= 1\n res.append(num)\n return res[:k]\n\n def merge(nums1: list[int], nums2: list[int]) -> list[int]:\n return [max(nums1, nums2).pop(0) for _ in nums1 + nums2]\n\n return max(merge(maxArray(nums1, i), maxArray(nums2, k - i))\n for i in range(k + 1)\n if i <= len(nums1) and k - i <= len(nums2))\n", | |
| "title": "321. Create Maximum Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 365 | |
| }, | |
| { | |
| "code": "class Solution:\n def coinChange(self, coins: list[int], amount: int) -> int:\n # dp[i] := the minimum number Of coins to make up i\n dp = [0] + [amount + 1] * amount\n\n for coin in coins:\n for i in range(coin, amount + 1):\n dp[i] = min(dp[i], dp[i - coin] + 1)\n\n return -1 if dp[amount] == amount + 1 else dp[amount]\n", | |
| "title": "322. Coin Change", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 366 | |
| }, | |
| { | |
| "code": "class Solution:\n def countComponents(self, n: int, edges: list[list[int]]) -> int:\n ans = 0\n graph = [[] for _ in range(n)]\n seen = set()\n\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n\n def bfs(node: int, seen: set[int]) -> None:\n q = collections.deque([node])\n seen.add(node)\n\n while q:\n u = q.pop()\n for v in graph[u]:\n if v not in seen:\n q.append(v)\n seen.add(v)\n\n for i in range(n):\n if i not in seen:\n bfs(i, seen)\n ans += 1\n\n return ans\n", | |
| "title": "323. Number of Connected Components in an Undirected Graph_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 367 | |
| }, | |
| { | |
| "code": "class Solution:\n def countComponents(self, n: int, edges: list[list[int]]) -> int:\n ans = 0\n graph = [[] for _ in range(n)]\n seen = set()\n\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n\n def dfs(u: int, seen: set[int]) -> None:\n for v in graph[u]:\n if v not in seen:\n seen.add(v)\n dfs(v, seen)\n\n for i in range(n):\n if i not in seen:\n seen.add(i)\n dfs(graph, i, seen)\n ans += 1\n\n return ans\n", | |
| "title": "323. Number of Connected Components in an Undirected Graph", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 368 | |
| }, | |
| { | |
| "code": "class Solution:\n def wiggleSort(self, nums: list[int]) -> None:\n n = len(nums)\n median = self._findKthLargest(nums, (n + 1) // 2)\n\n def A(i: int):\n return (1 + 2 * i) % (n | 1)\n\n i = 0\n j = 0\n k = n - 1\n\n while i <= k:\n if nums[A(i)] > median:\n nums[A(i)], nums[A(j)] = nums[A(j)], nums[A(i)]\n i, j = i + 1, j + 1\n elif nums[A(i)] < median:\n nums[A(i)], nums[A(k)] = nums[A(k)], nums[A(i)]\n k -= 1\n else:\n i += 1\n\n # Same as 215. Kth Largest Element in an Array\n def _findKthLargest(self, nums: list[int], k: int) -> int:\n def quickSelect(l: int, r: int, k: int) -> int:\n randIndex = random.randint(0, r - l) + l\n nums[randIndex], nums[r] = nums[r], nums[randIndex]\n pivot = nums[r]\n\n nextSwapped = l\n for i in range(l, r):\n if nums[i] >= pivot:\n nums[nextSwapped], nums[i] = nums[i], nums[nextSwapped]\n nextSwapped += 1\n nums[nextSwapped], nums[r] = nums[r], nums[nextSwapped]\n\n count = nextSwapped - l + 1 # Number of nums >= pivot\n if count == k:\n return nums[nextSwapped]\n if count > k:\n return quickSelect(l, nextSwapped - 1, k)\n return quickSelect(nextSwapped + 1, r, k - count)\n\n return quickSelect(0, len(nums) - 1, k)\n", | |
| "title": "324. Wiggle Sort II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 369 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxSubArrayLen(self, nums: list[int], k: int) -> int:\n ans = 0\n prefix = 0\n prefixToIndex = {0: -1}\n\n for i, num in enumerate(nums):\n prefix += num\n target = prefix - k\n if target in prefixToIndex:\n ans = max(ans, i - prefixToIndex[target])\n if prefix not in prefixToIndex:\n prefixToIndex[prefix] = i\n\n return ans\n", | |
| "title": "325. Maximum Size Subarray Sum Equals k", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 370 | |
| }, | |
| { | |
| "code": "class Solution:\n def isPowerOfThree(self, n: int) -> bool:\n return n > 0 and 3**19 % n == 0\n", | |
| "title": "326. Power of Three", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 371 | |
| }, | |
| { | |
| "code": "class Solution:\n def countRangeSum(self, nums: list[int], lower: int, upper: int) -> int:\n n = len(nums)\n self.ans = 0\n prefix = list(itertools.accumulate(nums, initial=0))\n\n self._mergeSort(prefix, 0, n, lower, upper)\n return self.ans\n\n def _mergeSort(\n self,\n prefix: list[int],\n l: int,\n r: int,\n lower: int,\n upper: int,\n ) -> None:\n if l >= r:\n return\n\n m = (l + r) // 2\n self._mergeSort(prefix, l, m, lower, upper)\n self._mergeSort(prefix, m + 1, r, lower, upper)\n self._merge(prefix, l, m, r, lower, upper)\n\n def _merge(\n self,\n prefix: list[int],\n l: int,\n m: int,\n r: int,\n lower: int,\n upper: int,\n ) -> None:\n lo = m + 1 # the first index s.t. prefix[lo] - prefix[i] >= lower\n hi = m + 1 # the first index s.t. prefix[hi] - prefix[i] > upper\n\n # For each index i in range [l, m], add hi - lo to `ans`.\n for i in range(l, m + 1):\n while lo <= r and prefix[lo] - prefix[i] < lower:\n lo += 1\n while hi <= r and prefix[hi] - prefix[i] <= upper:\n hi += 1\n self.ans += hi - lo\n\n sorted = [0] * (r - l + 1)\n k = 0 # sorted's index\n i = l # left's index\n j = m + 1 # right's index\n\n while i <= m and j <= r:\n if prefix[i] < prefix[j]:\n sorted[k] = prefix[i]\n k += 1\n i += 1\n else:\n sorted[k] = prefix[j]\n k += 1\n j += 1\n\n # Put the possible remaining left part into the sorted array.\n while i <= m:\n sorted[k] = prefix[i]\n k += 1\n i += 1\n\n # Put the possible remaining right part into the sorted array.\n while j <= r:\n sorted[k] = prefix[j]\n k += 1\n j += 1\n\n prefix[l:l + len(sorted)] = sorted\n", | |
| "title": "327. Count of Range Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 372 | |
| }, | |
| { | |
| "code": "class Solution:\n def oddEvenList(self, head: ListNode) -> ListNode:\n oddHead = ListNode(0)\n evenHead = ListNode(0)\n odd = oddHead\n even = evenHead\n isOdd = True\n\n while head:\n if isOdd:\n odd.next = head\n odd = head\n else:\n even.next = head\n even = head\n head = head.next\n isOdd = not isOdd\n\n even.next = None\n odd.next = evenHead.next\n return oddHead.next\n", | |
| "title": "328. Odd Even Linked List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 373 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestIncreasingPath(self, matrix: list[list[int]]) -> int:\n m = len(matrix)\n n = len(matrix[0])\n\n @functools.lru_cache(None)\n def dfs(i: int, j: int, prev: int) -> int:\n if i < 0 or i == m or j < 0 or j == n:\n return 0\n if matrix[i][j] <= prev:\n return 0\n\n curr = matrix[i][j]\n return 1 + max(dfs(i + 1, j, curr),\n dfs(i - 1, j, curr),\n dfs(i, j + 1, curr),\n dfs(i, j - 1, curr))\n\n return max(dfs(i, j, -math.inf) for i in range(m) for j in range(n))\n", | |
| "title": "329. Longest Increasing Path in a Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 374 | |
| }, | |
| { | |
| "code": "class Solution:\n def minPatches(self, nums: list[int], n: int) -> int:\n ans = 0\n i = 0 # nums' index\n miss = 1 # the minimum sum in [1, n] we might miss\n\n while miss <= n:\n if i < len(nums) and nums[i] <= miss:\n miss += nums[i]\n i += 1\n else:\n # Greedily add `miss` itself to increase the range from\n # [1, miss) to [1, 2 * miss).\n miss += miss\n ans += 1\n\n return ans\n", | |
| "title": "330. Patching Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 375 | |
| }, | |
| { | |
| "code": "class Solution:\n def isValidSerialization(self, preorder: str) -> bool:\n degree = 1 # out-degree (children) - in-degree (parent)\n\n for node in preorder.split(','):\n degree -= 1\n if degree < 0:\n return False\n if node != '#':\n degree += 2\n\n return degree == 0\n", | |
| "title": "331. Verify Preorder Serialization of a Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 376 | |
| }, | |
| { | |
| "code": "class Solution:\n def findItinerary(self, tickets: list[list[str]]) -> list[str]:\n ans = []\n graph = collections.defaultdict(list)\n\n for a, b in reversed(sorted(tickets)):\n graph[a].append(b)\n\n def dfs(u: str) -> None:\n while u in graph and graph[u]:\n dfs(graph[u].pop())\n ans.append(u)\n\n dfs('JFK')\n return ans[::-1]\n", | |
| "title": "332. Reconstruct Itinerary", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 377 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass(frozen=True)\nclass T:\n mn: int # the minimum value in the subtree\n mx: int # the maximum value in the subtree\n size: int # the size of the subtree\n\n\nclass Solution:\n def largestBSTSubtree(self, root: TreeNode | None) -> int:\n def dfs(root: TreeNode | None) -> T:\n if not root:\n return T(math.inf, -math.inf, 0)\n\n l = dfs(root.left)\n r = dfs(root.right)\n\n if l.mx < root.val < r.mn:\n return T(min(l.mn, root.val), max(r.mx, root.val), 1 + l.size + r.size)\n\n # Mark one as invalid, but still record the size of children.\n # Return (-inf, inf) because no node will be > inf or < -inf.\n return T(-math.inf, math.inf, max(l.size, r.size))\n\n return dfs(root).size\n", | |
| "title": "333. Largest BST Subtree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 378 | |
| }, | |
| { | |
| "code": "class Solution:\n def increasingTriplet(self, nums: list[int]) -> bool:\n first = math.inf\n second = math.inf\n\n for num in nums:\n if num <= first:\n first = num\n elif num <= second: # first < num <= second\n second = num\n else:\n return True # first < second < num (third)\n\n return False\n", | |
| "title": "334. Increasing Triplet Subsequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 379 | |
| }, | |
| { | |
| "code": "class Solution:\n def isSelfCrossing(self, x: list[int]) -> bool:\n if len(x) <= 3:\n return False\n\n for i in range(3, len(x)):\n if x[i - 2] <= x[i] and x[i - 1] <= x[i - 3]:\n return True\n if i >= 4 and x[i - 1] == x[i - 3] and x[i - 2] <= x[i] + x[i - 4]:\n return True\n if i >= 5 and x[i - 4] <= x[i - 2] and x[i - 2] <= x[i] + x[i - 4] and x[i - 1] <= x[i - 3] and x[i - 3] <= x[i - 1] + x[i - 5]:\n return True\n\n return False\n", | |
| "title": "335. Self Crossing", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 380 | |
| }, | |
| { | |
| "code": "class Solution:\n def palindromePairs(self, words: list[str]) -> list[list[int]]:\n ans = []\n dict = {word[::-1]: i for i, word in enumerate(words)}\n\n for i, word in enumerate(words):\n if \"\" in dict and dict[\"\"] != i and word == word[::-1]:\n ans.append([i, dict[\"\"]])\n\n for j in range(1, len(word) + 1):\n l = word[:j]\n r = word[j:]\n if l in dict and dict[l] != i and r == r[::-1]:\n ans.append([i, dict[l]])\n if r in dict and dict[r] != i and l == l[::-1]:\n ans.append([dict[r], i])\n\n return ans\n", | |
| "title": "336. Palindrome Pairs", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 381 | |
| }, | |
| { | |
| "code": "class Solution:\n def rob(self, root: TreeNode | None) -> int:\n def robOrNot(root: TreeNode | None) -> tuple:\n if not root:\n return (0, 0)\n\n robLeft, notRobLeft = robOrNot(root.left)\n robRight, notRobRight = robOrNot(root.right)\n\n return (root.val + notRobLeft + notRobRight,\n max(robLeft, notRobLeft) + max(robRight, notRobRight))\n\n return max(robOrNot(root))\n", | |
| "title": "337. House Robber III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 382 | |
| }, | |
| { | |
| "code": "class Solution:\n def countBits(self, n: int) -> list[int]:\n # f(i) := i's number of 1s in bitmask\n # f(i) = f(i / 2) + i % 2\n ans = [0] * (n + 1)\n\n for i in range(1, n + 1):\n ans[i] = ans[i // 2] + (i & 1)\n\n return ans\n", | |
| "title": "338. Counting Bits", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 383 | |
| }, | |
| { | |
| "code": "class Solution:\n def depthSum(self, nestedList: list[NestedInteger]) -> int:\n ans = 0\n\n def dfs(nestedList: list[NestedInteger], depth: int) -> None:\n nonlocal ans\n for ni in nestedList:\n if ni.isInteger():\n ans += ni.getInteger() * depth\n else:\n dfs(ni.getList(), depth + 1)\n\n dfs(nestedList, 1)\n return ans\n", | |
| "title": "339. Nested List Weight Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 384 | |
| }, | |
| { | |
| "code": "class Solution:\n def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:\n ans = 0\n distinct = 0\n count = collections.Counter()\n\n l = 0\n for r, c in enumerate(s):\n count[c] += 1\n if count[c] == 1:\n distinct += 1\n while distinct == k + 1:\n count[s[l]] -= 1\n if count[s[l]] == 0:\n distinct -= 1\n l += 1\n ans = max(ans, r - l + 1)\n\n return ans\n", | |
| "title": "340. Longest Substring with At Most K Distinct Characters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 385 | |
| }, | |
| { | |
| "code": "class NestedIterator:\n def __init__(self, nestedList: list[NestedInteger]):\n self.stack: list[NestedInteger] = []\n self.addInteger(nestedList)\n\n def next(self) -> int:\n return self.stack.pop().getInteger()\n\n def hasNext(self) -> bool:\n while self.stack and not self.stack[-1].isInteger():\n self.addInteger(self.stack.pop().getList())\n return self.stack\n\n # addInteger([1, [4, [6]]]) . stack = [[4, [6]], 1]\n # addInteger([4, [6]]) . stack = [[6], 4]\n # addInteger([6]) . stack = [6]\n def addInteger(self, nestedList: list[NestedInteger]) -> None:\n for n in reversed(nestedList):\n self.stack.append(n)\n", | |
| "title": "341. Flatten Nested List Iterator", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 386 | |
| }, | |
| { | |
| "code": "class Solution:\n def isPowerOfFour(self, n: int) -> bool:\n # Why (4^n - 1) % 3 == 0?\n # (4^n - 1) = (2^n - 1)(2^n + 1) and 2^n - 1, 2^n, 2^n + 1 are\n # three consecutive numbers; among one of them, there must be a multiple\n # of 3, and that can't be 2^n, so it must be either 2^n - 1 or 2^n + 1.\n # Therefore, 4^n - 1 is a multiple of 3.\n return n > 0 and n.bit_count() == 1 and (n - 1) % 3 == 0\n", | |
| "title": "342. Power of Four", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 387 | |
| }, | |
| { | |
| "code": "class Solution:\n def integerBreak(self, n: int) -> int:\n # If an optimal product contains a factor f >= 4, then we can replace it\n # with 2 and f - 2 without losing optimality. As 2(f - 2) = 2f - 4 >= f,\n # we never need a factor >= 4, meaning we only need factors 1, 2, and 3\n # (and 1 is wasteful).\n # Also, 3 * 3 is better than 2 * 2 * 2, so we never use 2 more than twice.\n if n == 2: # 1 * 1\n return 1\n if n == 3: # 1 * 2\n return 2\n\n ans = 1\n\n while n > 4:\n n -= 3\n ans *= 3\n ans *= n\n\n return ans\n", | |
| "title": "343. Integer Break", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 388 | |
| }, | |
| { | |
| "code": "class Solution:\n def reverseString(self, s: list[str]) -> None:\n l = 0\n r = len(s) - 1\n\n while l < r:\n s[l], s[r] = s[r], s[l]\n l += 1\n r -= 1\n", | |
| "title": "344. Reverse String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 389 | |
| }, | |
| { | |
| "code": "class Solution:\n def reverseVowels(self, s: str) -> str:\n chars = list(s)\n VOWELS = 'aeiouAEIOU'\n l = 0\n r = len(s) - 1\n\n while l < r:\n while l < r and chars[l] not in VOWELS:\n l += 1\n while l < r and chars[r] not in VOWELS:\n r -= 1\n chars[l], chars[r] = chars[r], chars[l]\n l += 1\n r -= 1\n\n return ''.join(chars)\n", | |
| "title": "345. Reverse Vowels of a String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 390 | |
| }, | |
| { | |
| "code": "class MovingAverage:\n def __init__(self, size: int):\n self.size = size\n self.sum = 0\n self.q = collections.deque()\n\n def next(self, val: int) -> float:\n if len(self.q) == self.size:\n self.sum -= self.q.popleft()\n self.sum += val\n self.q.append(val)\n return self.sum / len(self.q)\n", | |
| "title": "346. Moving Average from Data Stream", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 391 | |
| }, | |
| { | |
| "code": "class Solution:\n def topKFrequent(self, nums: list[int], k: int) -> list[int]:\n ans = []\n bucket = [[] for _ in range(len(nums) + 1)]\n\n for num, freq in collections.Counter(nums).items():\n bucket[freq].append(num)\n\n for b in reversed(bucket):\n ans += b\n if len(ans) == k:\n return ans\n", | |
| "title": "347. Top K Frequent Elements", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 392 | |
| }, | |
| { | |
| "code": "class TicTacToe:\n def __init__(self, n: int):\n self.n = n\n # Record count('X') - count('O').\n self.rows = [0] * n\n self.cols = [0] * n\n self.diag = 0\n self.antiDiag = 0\n\n \"\"\" Player {player} makes a move at ({row}, {col}).\n\n @param row The row of the board.\n @param col The column of the board.\n @param player The player, can be either 1 or 2.\n @return The current winning condition, can be either:\n 0: No one wins.\n 1: Player 1 wins.\n 2: Player 2 wins.\n \"\"\"\n\n def move(self, row: int, col: int, player: int) -> int:\n toAdd = 1 if player == 1 else -1\n target = self.n if player == 1 else -self.n\n\n if row == col:\n self.diag += toAdd\n if self.diag == target:\n return player\n\n if row + col == self.n - 1:\n self.antiDiag += toAdd\n if self.antiDiag == target:\n return player\n\n self.rows[row] += toAdd\n if self.rows[row] == target:\n return player\n\n self.cols[col] += toAdd\n if self.cols[col] == target:\n return player\n\n return 0\n", | |
| "title": "348. Design Tic-Tac-Toe", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 393 | |
| }, | |
| { | |
| "code": "class Solution:\n def intersection(self, nums1: list[int], nums2: list[int]) -> list[int]:\n ans = []\n nums1 = set(nums1)\n\n for num in nums2:\n if num in nums1:\n ans.append(num)\n nums1.remove(num)\n\n return ans\n", | |
| "title": "349. Intersection of Two Arrays", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 394 | |
| }, | |
| { | |
| "code": "class Solution:\n def intersect(self, nums1: list[int], nums2: list[int]) -> list[int]:\n if len(nums1) > len(nums2):\n return self.intersect(nums2, nums1)\n\n ans = []\n count = collections.Counter(nums1)\n\n for num in nums2:\n if count[num] > 0:\n ans.append(num)\n count[num] -= 1\n\n return ans\n", | |
| "title": "350. Intersection of Two Arrays II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 395 | |
| }, | |
| { | |
| "code": "class Solution:\n def numberOfPatterns(self, m: int, n: int) -> int:\n seen = set()\n accross = [[0] * 10 for _ in range(10)]\n\n accross[1][3] = accross[3][1] = 2\n accross[1][7] = accross[7][1] = 4\n accross[3][9] = accross[9][3] = 6\n accross[7][9] = accross[9][7] = 8\n accross[1][9] = accross[9][1] = accross[2][8] = accross[8][2] = \\\n accross[3][7] = accross[7][3] = accross[4][6] = accross[6][4] = 5\n\n def dfs(u: int, depth: int) -> int:\n if depth > n:\n return 0\n\n seen.add(u)\n ans = 1 if depth >= m else 0\n\n for v in range(1, 10):\n if v == u or v in seen:\n continue\n accrossed = accross[u][v]\n if not accrossed or accrossed in seen:\n ans += dfs(v, depth + 1)\n\n seen.remove(u)\n return ans\n\n # 1, 3, 7, 9 are symmetric\n # 2, 4, 6, 8 are symmetric\n return dfs(1, 1) * 4 + dfs(2, 1) * 4 + dfs(5, 1)\n", | |
| "title": "351. Android Unlock Patterns", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 396 | |
| }, | |
| { | |
| "code": "from sortedcontainers import SortedDict\n\n\nclass SummaryRanges:\n def __init__(self):\n self.intervals = SortedDict() # {start: (start, end)}\n\n def addNum(self, val: int) -> None:\n if val in self.intervals:\n return\n\n lo = self._lowerKey(val)\n hi = self._higherKey(val)\n\n # {lo, map[lo][1]} + val + {hi, map[hi][1]} = {lo, map[hi][1]}\n if lo >= 0 and hi >= 0 and self.intervals[lo][1] + 1 == val and val + 1 == hi:\n self.intervals[lo][1] = self.intervals[hi][1]\n del self.intervals[hi]\n # {lo, map[lo][1]} + val = {lo, val}\n # Prevent adding duplicate entry by using '>=' instead of '=='.\n elif lo >= 0 and self.intervals[lo][1] + 1 >= val:\n self.intervals[lo][1] = max(self.intervals[lo][1], val)\n elif hi >= 0 and val + 1 == hi:\n # val + {hi, map[hi][1]} = {val, map[hi][1]}\n self.intervals[val] = [val, self.intervals[hi][1]]\n del self.intervals[hi]\n else:\n self.intervals[val] = [val, val]\n\n def getIntervals(self) -> list[list[int]]:\n return list(self.intervals.values())\n\n def _lowerKey(self, key: int):\n \"\"\"Returns the maximum key in `self.intervals` < `key`.\"\"\"\n i = self.intervals.bisect_left(key)\n if i == 0:\n return -1\n return self.intervals.peekitem(i - 1)[0]\n\n def _higherKey(self, key: int):\n \"\"\"Returns the minimum key in `self.intervals` < `key`.\"\"\"\n i = self.intervals.bisect_right(key)\n if i == len(self.intervals):\n return -1\n return self.intervals.peekitem(i)[0]\n", | |
| "title": "352. Data Stream as Disjoint Intervals", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 397 | |
| }, | |
| { | |
| "code": "class SnakeGame:\n def __init__(self, width: int, height: int, food: list[list[int]]):\n \"\"\"\n Initialize your data structure here.\n @param width - screen width\n @param height - screen height\n @param food - A list of food positions\n E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].\n \"\"\"\n self.width = width\n self.height = height\n self.food = food\n self.score = 0\n self.k = 0 # food's index\n self.lookup = set([self.getId(0, 0)])\n self.body = collections.deque([self.getId(0, 0)]) # snake's body\n\n def move(self, direction: str) -> int:\n \"\"\"\n Moves the snake.\n @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down\n @return The game's score after the move. Return -1 if game over.\n Game over when snake crosses the screen boundary or bites its body.\n \"\"\"\n # the old head's position\n i = self.body[0] // self.width\n j = self.body[0] % self.width\n\n # Update the head's position and check if it's out-of-bounds.\n if direction == \"U\":\n i -= 1\n if i < 0:\n return -1\n if direction == \"L\":\n j -= 1\n if j < 0:\n return -1\n if direction == \"R\":\n j += 1\n if j == self.width:\n return -1\n if direction == \"D\":\n i += 1\n if i == self.height:\n return -1\n\n newHead = self.getId(i, j)\n\n # 1. Eat food and increase the size by 1.\n if self.k < len(self.food) and i == self.food[self.k][0] and j == self.food[self.k][1]:\n self.lookup.add(newHead)\n self.body.appendleft(newHead)\n self.k += 1\n self.score += 1\n return self.score\n\n # 2. new head != old tail and eat body!\n if newHead != self.body[-1] and newHead in self.lookup:\n return -1\n\n # 3. normal case\n # Remove the old tail first, then add new head because new head may be in\n # old tail's position.\n self.lookup.remove(self.body[-1])\n self.lookup.add(newHead)\n self.body.pop()\n self.body.appendleft(newHead)\n\n return self.score\n\n def getId(self, i: int, j: int) -> int:\n return i * self.width + j\n", | |
| "title": "353. Design Snake Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 398 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxEnvelopes(self, envelopes: list[list[int]]) -> int:\n envelopes.sort(key=lambda x: (x[0], -x[1]))\n return self._lengthOfLIS(envelopes)\n\n def _lengthOfLIS(self, envelopes: list[list[int]]) -> int:\n # tails[i] := the minimum tails of all the increasing subsequences having\n # length i + 1\n tails = []\n\n for _, h in envelopes:\n if not tails or h > tails[-1]:\n tails.append(h)\n else:\n tails[bisect.bisect_left(tails, h)] = h\n\n return len(tails)\n", | |
| "title": "354. Russian Doll Envelopes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 399 | |
| }, | |
| { | |
| "code": "class Twitter:\n def __init__(self):\n self.timer = itertools.count(step=-1)\n self.tweets = collections.defaultdict(deque)\n self.followees = collections.defaultdict(set)\n\n def postTweet(self, userId: int, tweetId: int) -> None:\n self.tweets[userId].appendleft((next(self.timer), tweetId))\n if len(self.tweets[userId]) > 10:\n self.tweets[userId].pop()\n\n def getNewsFeed(self, userId: int) -> list[int]:\n tweets = list(\n heapq.merge(\n *\n (self.tweets[followee]\n for followee in self.followees[userId] | {userId})))\n return [tweetId for _, tweetId in tweets[:10]]\n\n def follow(self, followerId: int, followeeId: int) -> None:\n self.followees[followerId].add(followeeId)\n\n def unfollow(self, followerId: int, followeeId: int) -> None:\n self.followees[followerId].discard(followeeId)\n", | |
| "title": "355. Design Twitter", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 400 | |
| }, | |
| { | |
| "code": "class Solution:\n def isReflected(self, points: list[list[int]]) -> bool:\n minX = math.inf\n maxX = -math.inf\n seen = set()\n\n for x, y in points:\n minX = min(minX, x)\n maxX = max(maxX, x)\n seen.add((x, y))\n\n summ = minX + maxX\n # (leftX + rightX) / 2 = (minX + maxX) / 2\n # leftX = minX + maxX - rightX\n # rightX = minX + maxX - leftX\n\n return all((summ - x, y) in seen for x, y in points)\n", | |
| "title": "356. Line Reflection", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 401 | |
| }, | |
| { | |
| "code": "class Solution:\n def countNumbersWithUniqueDigits(self, n: int) -> int:\n if n == 0:\n return 1\n\n ans = 10\n uniqueDigits = 9\n availableNum = 9\n\n while n > 1 and availableNum > 0:\n uniqueDigits *= availableNum\n ans += uniqueDigits\n n -= 1\n availableNum -= 1\n\n return ans\n", | |
| "title": "357. Count Numbers with Unique Digits", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 402 | |
| }, | |
| { | |
| "code": "class Solution:\n def rearrangeString(self, s: str, k: int) -> str:\n n = len(s)\n ans = []\n count = collections.Counter(s)\n # valid[i] := the leftmost index i can appear\n valid = collections.Counter()\n\n def getBestLetter(index: int) -> str:\n \"\"\"Returns the valid letter that has the most count.\"\"\"\n maxCount = -1\n bestLetter = '*'\n\n for c in string.ascii_lowercase:\n if count[c] > 0 and count[c] > maxCount and index >= valid[c]:\n bestLetter = c\n maxCount = count[c]\n\n return bestLetter\n\n for i in range(n):\n c = getBestLetter(i)\n if c == '*':\n return ''\n ans.append(c)\n count[c] -= 1\n valid[c] = i + k\n\n return ''.join(ans)\n", | |
| "title": "358. Rearrange String k Distance Apart", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 403 | |
| }, | |
| { | |
| "code": "class Logger:\n def __init__(self):\n self.okTime = {} # {message: ok time}\n\n def shouldPrintMessage(self, timestamp: int, message: str) -> bool:\n if timestamp < self.okTime.get(message, 0):\n return False\n\n self.okTime[message] = timestamp + 10\n return True\n", | |
| "title": "359. Logger Rate Limiter", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 404 | |
| }, | |
| { | |
| "code": "class Solution:\n def sortTransformedArray(\n self,\n nums: list[int],\n a: int,\n b: int,\n c: int,\n ) -> list[int]:\n n = len(nums)\n upward = a > 0\n ans = [0] * n\n\n # The concavity of f only depends on a's sign.\n def f(x: int, a: int, b: int, c: int) -> int:\n return (a * x + b) * x + c\n\n quad = [f(num, a, b, c) for num in nums]\n\n i = n - 1 if upward else 0\n l = 0\n r = n - 1\n while l <= r:\n if upward: # is the maximum in the both ends\n if quad[l] > quad[r]:\n ans[i] = quad[l]\n l += 1\n else:\n ans[i] = quad[r]\n r -= 1\n i -= 1\n else: # is the minimum in the both ends\n if quad[l] < quad[r]:\n ans[i] = quad[l]\n l += 1\n else:\n ans[i] = quad[r]\n r -= 1\n i += 1\n\n return ans\n", | |
| "title": "360. Sort Transformed Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 405 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxKilledEnemies(self, grid: list[list[str]]) -> int:\n m = len(grid)\n n = len(grid[0])\n enemyCount = 0\n # dp[i][j] := the maximum enemies grid[i][j] can kill\n dp = [[0] * n for _ in range(m)]\n\n def update(i: int, j: int) -> None:\n nonlocal enemyCount\n if grid[i][j] == '0':\n dp[i][j] += enemyCount\n elif grid[i][j] == 'E':\n enemyCount += 1\n else: # grid[i][j] == 'W'\n enemyCount = 0\n\n # Extend the four directions, if meet 'W', need to start over from 0.\n for i in range(m):\n enemyCount = 0\n for j in range(n):\n update(i, j)\n enemyCount = 0\n for j in reversed(range(n)):\n update(i, j)\n\n for j in range(n):\n enemyCount = 0\n for i in range(m):\n update(i, j)\n enemyCount = 0\n for i in reversed(range(m)):\n update(i, j)\n\n # Returns sum(map(sum, dp))\n return max(map(max, dp))\n", | |
| "title": "361. Bomb Enemy", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 406 | |
| }, | |
| { | |
| "code": "class HitCounter:\n def __init__(self):\n self.timestamps = [0] * 300\n self.hits = [0] * 300\n\n def hit(self, timestamp: int) -> None:\n i = timestamp % 300\n if self.timestamps[i] == timestamp:\n self.hits[i] += 1\n else:\n self.timestamps[i] = timestamp\n self.hits[i] = 1 # Reset the hit count to 1.\n\n def getHits(self, timestamp: int) -> int:\n return sum(h for t, h in zip(self.timestamps, self.hits)\n if timestamp - t < 300)\n", | |
| "title": "362. Design Hit Counter", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 407 | |
| }, | |
| { | |
| "code": "from sortedcontainers import SortedList\n\n\nclass Solution:\n def maxSumSubmatrix(self, matrix: list[list[int]], k: int) -> int:\n m = len(matrix)\n n = len(matrix[0])\n ans = -math.inf\n\n for baseCol in range(n):\n # sums[i] := sum(matrix[i][baseCol..j])\n sums = [0] * m\n for j in range(baseCol, n):\n for i in range(m):\n sums[i] += matrix[i][j]\n # Find the maximum sum <= k of all the subarrays.\n accumulate = SortedList([0])\n prefix = 0\n for summ in sums:\n prefix += summ\n it = accumulate.bisect_left(prefix - k)\n if it != len(accumulate):\n ans = max(ans, prefix - accumulate[it])\n accumulate.add(prefix)\n\n return ans\n", | |
| "title": "363. Max Sum of Rectangle No Larger Than K", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 408 | |
| }, | |
| { | |
| "code": "class Solution:\n def depthSumInverse(self, nestedList: list[NestedInteger]) -> int:\n ans = 0\n prevSum = 0\n q = collections.deque(nestedList)\n\n while q:\n for _ in range(len(q)):\n ni = q.popleft()\n if ni.isInteger():\n prevSum += ni.getInteger()\n else:\n for nextNi in ni.getList():\n q.append(nextNi)\n ans += prevSum\n\n return ans\n", | |
| "title": "364. Nested List Weight Sum II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 409 | |
| }, | |
| { | |
| "code": "class Solution:\n def canMeasureWater(\n self,\n jug1Capacity: int,\n jug2Capacity: int,\n targetCapacity: int,\n ) -> bool:\n return (targetCapacity == 0 or\n jug1Capacity + jug2Capacity >= targetCapacity and\n targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0)\n", | |
| "title": "365. Water and Jug Problem", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 410 | |
| }, | |
| { | |
| "code": "class Solution:\n def findLeaves(self, root: TreeNode | None) -> list[list[int]]:\n ans = []\n\n def depth(root: TreeNode | None) -> int:\n \"\"\"Returns the depth of the root (0-indexed).\"\"\"\n if not root:\n return -1\n\n l = depth(root.left)\n r = depth(root.right)\n h = 1 + max(l, r)\n\n if len(ans) == h: # Meet a leaf\n ans.append([])\n\n ans[h].append(root.val)\n return h\n\n depth(root)\n return ans\n", | |
| "title": "366. Find Leaves of Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 411 | |
| }, | |
| { | |
| "code": "class Solution:\n def isPerfectSquare(self, num: int) -> bool:\n l = bisect.bisect_left(range(num), num, key=lambda m: m * m)\n return l**2 == num\n", | |
| "title": "367. Valid Perfect Square", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 412 | |
| }, | |
| { | |
| "code": "class Solution:\n def largestDivisibleSubset(self, nums: list[int]) -> list[int]:\n n = len(nums)\n ans = []\n count = [1] * n\n prevIndex = [-1] * n\n maxCount = 0\n index = -1\n\n nums.sort()\n\n for i, num in enumerate(nums):\n for j in reversed(range(i)):\n if num % nums[j] == 0 and count[i] < count[j] + 1:\n count[i] = count[j] + 1\n prevIndex[i] = j\n if count[i] > maxCount:\n maxCount = count[i]\n index = i\n\n while index != -1:\n ans.append(nums[index])\n index = prevIndex[index]\n\n return ans\n", | |
| "title": "368. Largest Divisible Subset", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 413 | |
| }, | |
| { | |
| "code": "class Solution:\n def plusOne(self, head: ListNode) -> ListNode:\n dummy = ListNode(0)\n curr = dummy\n dummy.next = head\n\n while head:\n if head.val != 9:\n curr = head\n head = head.next\n # `curr` now points to the rightmost non-9 node.\n\n curr.val += 1\n while curr.next:\n curr.next.val = 0\n curr = curr.next\n\n return dummy.next if dummy.val == 0 else dummy\n", | |
| "title": "369. Plus One Linked List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 414 | |
| }, | |
| { | |
| "code": "class Solution:\n def getModifiedArray(\n self,\n length: int,\n updates: list[list[int]],\n ) -> list[int]:\n line = [0] * length\n\n for start, end, inc in updates:\n line[start] += inc\n if end + 1 < length:\n line[end + 1] -= inc\n\n return itertools.accumulate(line)\n", | |
| "title": "370. Range Addition", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 415 | |
| }, | |
| { | |
| "code": "class Solution:\n def getSum(self, a: int, b: int) -> int:\n mask = 0xFFFFFFFF\n MAX = 2000\n\n while b != 0:\n a, b = (a ^ b) & mask, ((a & b) << 1) & mask\n\n return a if a < MAX else ~(a ^ mask)\n", | |
| "title": "371. Sum of Two Integers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 416 | |
| }, | |
| { | |
| "code": "class Solution:\n def superPow(self, a: int, b: list[int]) -> int:\n MOD = 1337\n ans = 1\n\n for i in b:\n ans = pow(ans, 10, MOD) * pow(a, i, MOD)\n\n return ans % MOD\n", | |
| "title": "372. Super Pow", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 417 | |
| }, | |
| { | |
| "code": "class Solution:\n def kSmallestPairs(self, nums1: list[int],\n nums2: list[int],\n k: int) -> list[list[int]]:\n minHeap = []\n\n for i in range(min(k, len(nums1))):\n heapq.heappush(minHeap, (nums1[i] + nums2[0], i, 0))\n\n ans = []\n while minHeap and len(ans) < k:\n _, i, j = heapq.heappop(minHeap)\n ans.append([nums1[i], nums2[j]])\n if j + 1 < len(nums2):\n heapq.heappush(minHeap, (nums1[i] + nums2[j + 1], i, j + 1))\n\n return ans\n", | |
| "title": "373. Find K Pairs with Smallest Sums", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 418 | |
| }, | |
| { | |
| "code": "# The guess API is already defined for you.\n# @param num, your guess\n# @return -1 if num is higher than the picked number\n# 1 if num is lower than the picked number\n# otherwise return 0\n# def guess(num: int) -> int:\n\nclass Solution:\n def guessNumber(self, n: int) -> int:\n l = 1\n r = n\n\n # Find the first guess number that >= the target number\n while l < r:\n m = (l + r) // 2\n if guess(m) <= 0: # -1, 0\n r = m\n else:\n l = m + 1\n\n return l\n", | |
| "title": "374. Guess Number Higher or Lower", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 419 | |
| }, | |
| { | |
| "code": "class Solution:\n def getMoneyAmount(self, n: int) -> int:\n # dp[i][j] := the minimum money you need to guarantee a win of picking i..j\n dp = [[0] * (n + 2) for _ in range(n + 2)]\n\n for d in range(1, n + 1):\n for i in range(1, n - d + 1):\n j = i + d\n dp[i][j] = math.inf\n for k in range(i, j + 1):\n dp[i][j] = min(dp[i][j], max(dp[i][k - 1], dp[k + 1][j]) + k)\n\n return dp[1][n]\n", | |
| "title": "375. Guess Number Higher or Lower II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 420 | |
| }, | |
| { | |
| "code": "class Solution:\n def wiggleMaxLength(self, nums: list[int]) -> int:\n increasing = 1\n decreasing = 1\n\n for a, b in itertools.pairwise(nums):\n if b > a:\n increasing = decreasing + 1\n elif b < a:\n decreasing = increasing + 1\n\n return max(increasing, decreasing)\n", | |
| "title": "376. Wiggle Subsequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 421 | |
| }, | |
| { | |
| "code": "class Solution:\n def combinationSum4(self, nums: list[int], target: int) -> int:\n dp = [1] + [-1] * target\n\n def dfs(target: int) -> int:\n if target < 0:\n return 0\n if dp[target] != -1:\n return dp[target]\n\n dp[target] = sum(dfs(target - num) for num in nums)\n return dp[target]\n\n return dfs(target)\n", | |
| "title": "377. Combination Sum IV", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 422 | |
| }, | |
| { | |
| "code": "class Solution:\n def kthSmallest(self, matrix: list[list[int]], k: int) -> int:\n def numsNoGreaterThan(m: int) -> int:\n count = 0\n j = len(matrix[0]) - 1\n # For each row, find the first index j s.t. row[j] <= m s.t. the number of\n # numbers <= m for this row will be j + 1.\n for row in matrix:\n while j >= 0 and row[j] > m:\n j -= 1\n count += j + 1\n return count\n\n l = matrix[0][0]\n r = matrix[-1][-1]\n return bisect.bisect_left(range(l, r), k, key=numsNoGreaterThan) + l\n", | |
| "title": "378. Kth Smallest Element in a Sorted Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 423 | |
| }, | |
| { | |
| "code": "class PhoneDirectory:\n def __init__(self, maxNumbers: int):\n # the next available numbers\n self.next = [i + 1 for i in range(maxNumbers - 1)] + [0]\n # the current possible available number\n self.number = 0\n\n def get(self) -> int:\n if self.next[self.number] == -1:\n return -1\n ans = self.number\n self.number = self.next[self.number]\n self.next[ans] = -1 # Mark as used.\n return ans\n\n def check(self, number: int) -> bool:\n return self.next[number] != -1\n\n def release(self, number: int) -> None:\n if self.next[number] != -1:\n return\n self.next[number] = self.number\n self.number = number\n", | |
| "title": "379. Design Phone Directory", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 424 | |
| }, | |
| { | |
| "code": "class RandomizedSet:\n def __init__(self):\n self.vals = []\n self.valToIndex = collections.defaultdict(int) # {val: index in vals}\n\n def insert(self, val: int) -> bool:\n if val in self.valToIndex:\n return False\n self.valToIndex[val] = len(self.vals)\n self.vals.append(val)\n return True\n\n def remove(self, val: int) -> bool:\n if val not in self.valToIndex:\n return False\n index = self.valToIndex[val]\n # The order of the following two lines is important when vals.size() == 1.\n self.valToIndex[self.vals[-1]] = index\n del self.valToIndex[val]\n self.vals[index] = self.vals[-1]\n self.vals.pop()\n return True\n\n def getRandom(self) -> int:\n index = random.randint(0, len(self.vals) - 1)\n return self.vals[index]\n", | |
| "title": "380. Insert Delete GetRandom O(1)", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 425 | |
| }, | |
| { | |
| "code": "class RandomizedCollection:\n def __init__(self):\n self.vals = []\n self.valToIndices = collections.defaultdict(list)\n\n def insert(self, val: int) -> bool:\n self.valToIndices[val].append(len(self.vals))\n self.vals.append([val, len(self.valToIndices[val]) - 1])\n return len(self.valToIndices[val]) == 1\n\n def remove(self, val: int) -> bool:\n if val not in self.valToIndices or self.valToIndices[val] == []:\n return False\n\n index = self.valToIndices[val][-1]\n self.valToIndices[self.vals[-1][0]][self.vals[-1][1]] = index\n self.valToIndices[val].pop()\n self.vals[index] = self.vals[-1]\n self.vals.pop()\n return True\n\n def getRandom(self) -> int:\n index = random.randint(0, len(self.vals) - 1)\n return self.vals[index][0]\n", | |
| "title": "381. Insert Delete GetRandom O(1) - Duplicates allowed", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 426 | |
| }, | |
| { | |
| "code": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution:\n def __init__(self, head: ListNode | None):\n self.head = head\n\n def getRandom(self) -> int:\n res = -1\n i = 1\n curr = self.head\n\n while curr:\n if random.randint(0, i - 1) == 0:\n res = curr.val\n curr = curr.next\n i += 1\n\n return res\n", | |
| "title": "382. Linked List Random Node", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 427 | |
| }, | |
| { | |
| "code": "class Solution:\n def canConstruct(self, ransomNote: str, magazine: str) -> bool:\n count1 = collections.Counter(ransomNote)\n count2 = collections.Counter(magazine)\n return all(count1[c] <= count2[c] for c in string.ascii_lowercase)\n", | |
| "title": "383. Ransom Note", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 428 | |
| }, | |
| { | |
| "code": "class Solution:\n def __init__(self, nums: list[int]):\n self.nums = nums\n\n def reset(self) -> list[int]:\n return self.nums\n\n def shuffle(self) -> list[int]:\n arr = self.nums.copy()\n for i in range(len(arr) - 1, 0, -1):\n j = random.randint(0, i)\n arr[i], arr[j] = arr[j], arr[i]\n return arr\n", | |
| "title": "384. Shuffle an Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 429 | |
| }, | |
| { | |
| "code": "class Solution:\n def deserialize(self, s: str) -> NestedInteger:\n if s[0] != '[':\n return NestedInteger(int(s))\n\n stack = []\n\n for i, c in enumerate(s):\n if c == '[':\n stack.append(NestedInteger())\n start = i + 1\n elif c == ',':\n if i > start:\n num = int(s[start:i])\n stack[-1].add(NestedInteger(num))\n start = i + 1\n elif c == ']':\n popped = stack.pop()\n if i > start:\n num = int(s[start:i])\n popped.add(NestedInteger(num))\n if stack:\n stack[-1].add(popped)\n else:\n return popped\n start = i + 1\n", | |
| "title": "385. Mini Parser", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 430 | |
| }, | |
| { | |
| "code": "class Solution:\n def lexicalOrder(self, n: int) -> list[int]:\n ans = []\n curr = 1\n\n while len(ans) < n:\n ans.append(curr)\n if curr * 10 <= n:\n curr *= 10\n else:\n while curr % 10 == 9 or curr == n:\n curr //= 10\n curr += 1\n\n return ans\n", | |
| "title": "386. Lexicographical Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 431 | |
| }, | |
| { | |
| "code": "class Solution:\n def firstUniqChar(self, s: str) -> int:\n count = collections.Counter(s)\n\n for i, c in enumerate(s):\n if count[c] == 1:\n return i\n\n return -1\n", | |
| "title": "387. First Unique Character in a String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 432 | |
| }, | |
| { | |
| "code": "class Solution:\n def lengthLongestPath(self, input: str) -> int:\n ans = 0\n stack = [(-1, 0)] # placeholder\n\n for token in input.split('\\n'):\n depth = token.count('\\t')\n token = token.replace('\\t', '')\n while depth <= stack[-1][0]:\n stack.pop()\n if '.' in token: # `token` is file.\n ans = max(ans, stack[-1][1] + len(token))\n else: # directory + '/'\n stack.append((depth, stack[-1][1] + len(token) + 1))\n\n return ans\n", | |
| "title": "388. Longest Absolute File Path", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 433 | |
| }, | |
| { | |
| "code": "class Solution:\n def findTheDifference(self, s: str, t: str) -> str:\n count = collections.Counter(s)\n\n for c in t:\n if count[c] == 0:\n return c\n count[c] -= 1\n", | |
| "title": "389. Find the Difference", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 434 | |
| }, | |
| { | |
| "code": "class Solution:\n def lastRemaining(self, n: int) -> int:\n return 1 if n == 1 else 2 * (1 + n // 2 - self.lastRemaining(n // 2))\n", | |
| "title": "390. Elimination Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 435 | |
| }, | |
| { | |
| "code": "class Solution:\n def isRectangleCover(self, rectangles: list[list[int]]) -> bool:\n area = 0\n x1 = math.inf\n y1 = math.inf\n x2 = -math.inf\n y2 = -math.inf\n corners: set[tuple[int, int]] = set()\n\n for x, y, a, b in rectangles:\n area += (a - x) * (b - y)\n x1 = min(x1, x)\n y1 = min(y1, y)\n x2 = max(x2, a)\n y2 = max(y2, b)\n\n # the four points of the current rectangle\n for point in [(x, y), (x, b), (a, y), (a, b)]:\n if point in corners:\n corners.remove(point)\n else:\n corners.add(point)\n\n if len(corners) != 4:\n return False\n if ((x1, y1) not in corners or\n (x1, y2) not in corners or\n (x2, y1) not in corners or\n (x2, y2) not in corners):\n return False\n return area == (x2 - x1) * (y2 - y1)\n", | |
| "title": "391. Perfect Rectangle", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 436 | |
| }, | |
| { | |
| "code": "class Solution:\n def isSubsequence(self, s: str, t: str) -> bool:\n if not s:\n return True\n\n i = 0\n for c in t:\n if s[i] == c:\n i += 1\n if i == len(s):\n return True\n\n return False\n", | |
| "title": "392. Is Subsequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 437 | |
| }, | |
| { | |
| "code": "class Solution:\n def validUtf8(self, data: list[int]) -> bool:\n followedBytes = 0\n\n for d in data:\n if followedBytes == 0:\n if (d >> 3) == 0b11110:\n followedBytes = 3\n elif (d >> 4) == 0b1110:\n followedBytes = 2\n elif (d >> 5) == 0b110:\n followedBytes = 1\n elif (d >> 7) == 0b0:\n followedBytes = 0\n else:\n return False\n else:\n if (d >> 6) != 0b10:\n return False\n followedBytes -= 1\n\n return followedBytes == 0\n", | |
| "title": "393. UTF-8 Validation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 438 | |
| }, | |
| { | |
| "code": "class Solution:\n def decodeString(self, s: str) -> str:\n ans = ''\n\n while self.i < len(s) and s[self.i] != ']':\n if s[self.i].isdigit():\n k = 0\n while self.i < len(s) and s[self.i].isdigit():\n k = k * 10 + int(s[self.i])\n self.i += 1\n self.i += 1 # '['\n decodedString = self.decodeString(s)\n self.i += 1 # ']'\n ans += k * decodedString\n else:\n ans += s[self.i]\n self.i += 1\n\n return ans\n\n i = 0\n", | |
| "title": "394. Decode String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 439 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestSubstring(self, s: str, k: int) -> int:\n def longestSubstringWithNUniqueLetters(n: int) -> int:\n res = 0\n uniqueLetters = 0 # the number of unique letters\n lettersHavingKFreq = 0 # the number of letters having frequency >= k\n count = collections.Counter()\n\n l = 0\n for r, c in enumerate(s):\n count[c] += 1\n if count[c] == 1:\n uniqueLetters += 1\n if count[c] == k:\n lettersHavingKFreq += 1\n while uniqueLetters > n:\n if count[s[l]] == k:\n lettersHavingKFreq -= 1\n count[s[l]] -= 1\n if count[s[l]] == 0:\n uniqueLetters -= 1\n l += 1\n # Since both the number of unique letters and the number of letters\n # having frequency >= k are equal to n, this is a valid window.\n if lettersHavingKFreq == n: # Implicit: uniqueLetters == n\n res = max(res, r - l + 1)\n\n return res\n\n return max(longestSubstringWithNUniqueLetters(n)\n for n in range(1, 27))\n", | |
| "title": "395. Longest Substring with At Least K Repeating Characters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 440 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxRotateFunction(self, nums: list[int]) -> int:\n f = sum(i * num for i, num in enumerate(nums))\n ans = f\n summ = sum(nums)\n\n for a in reversed(nums):\n f += summ - len(nums) * a\n ans = max(ans, f)\n\n return ans\n", | |
| "title": "396. Rotate Function", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 441 | |
| }, | |
| { | |
| "code": "class Solution:\n def integerReplacement(self, n: int) -> int:\n ans = 0\n\n while n > 1:\n if n % 2 == 0: # `n` ends in 0.\n n >>= 1\n elif n == 3 or (n >> 1 & 1) == 0: # `n` = 3 or ends in 0b01.\n n -= 1\n else: # `n` ends in 0b11.\n n += 1\n ans += 1\n\n return ans\n", | |
| "title": "397. Integer Replacement", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 442 | |
| }, | |
| { | |
| "code": "class Solution:\n def __init__(self, nums: list[int]):\n self.nums = nums\n\n def pick(self, target: int) -> int:\n ans = -1\n rng = 0\n for i, num in enumerate(self.nums):\n if num == target:\n rng += 1\n if random.randint(0, rng - 1) == 0:\n ans = i\n return ans\n", | |
| "title": "398. Random Pick Index", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 443 | |
| }, | |
| { | |
| "code": "class Solution:\n def calcEquation(\n self,\n equations: list[list[str]],\n values: list[float],\n queries: list[list[str]],\n ) -> list[float]:\n ans = []\n # graph[A][B] := A / B\n graph = collections.defaultdict(dict)\n\n for (A, B), value in zip(equations, values):\n graph[A][B] = value\n graph[B][A] = 1 / value\n\n def devide(A: str, C: str, seen: set[str]) -> float:\n \"\"\"Returns A / C.\"\"\"\n if A == C:\n return 1.0\n\n seen.add(A)\n\n # value := A / B\n for B, value in graph[A].items():\n if B in seen:\n continue\n res = devide(B, C, seen) # B / C\n if res > 0: # valid result\n return value * res # (A / B) * (B / C) = A / C\n\n return -1.0 # invalid result\n\n for A, C in queries:\n if A not in graph or C not in graph:\n ans.append(-1.0)\n else:\n ans.append(devide(A, C, set()))\n\n return ans\n", | |
| "title": "399. Evaluate Division", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 444 | |
| }, | |
| { | |
| "code": "class Solution:\n def findNthDigit(self, n: int) -> int:\n def getDigit(num: int, pos: int, digitSize: int):\n if pos == 0:\n return num % 10\n for _ in range(digitSize - pos):\n num //= 10\n return num % 10\n\n digitSize = 1\n startNum = 1\n count = 9\n\n while digitSize * count < n:\n n -= digitSize * count\n digitSize += 1\n startNum *= 10\n count *= 10\n\n targetNum = startNum + (n - 1) // digitSize\n pos = n % digitSize\n\n return getDigit(targetNum, pos, digitSize)\n", | |
| "title": "400. Nth Digit", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 445 | |
| }, | |
| { | |
| "code": "class Solution:\n def readBinaryWatch(self, turnedOn: int) -> list[str]:\n ans = []\n\n for h in range(12):\n for m in range(60):\n if h.bit_count() + m.bit_count() == turnedOn:\n ans.append(f'{h}:{m:02d}')\n\n return ans\n", | |
| "title": "401. Binary Watch", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 446 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeKdigits(self, num: str, k: int) -> str:\n if len(num) == k:\n return '0'\n\n ans = []\n stack = []\n\n for i, digit in enumerate(num):\n while k > 0 and stack and stack[-1] > digit:\n stack.pop()\n k -= 1\n stack.append(digit)\n\n for _ in range(k):\n stack.pop()\n\n for c in stack:\n if c == '0' and not ans:\n continue\n ans.append(c)\n\n return ''.join(ans) if ans else '0'\n", | |
| "title": "402. Remove K Digits", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 447 | |
| }, | |
| { | |
| "code": "class Solution:\n def canCross(self, stones: list[int]) -> bool:\n n = len(stones)\n # dp[i][j] := True if a frog can make a size j jump from stones[i]\n dp = [[False] * (n + 1) for _ in range(n)]\n dp[0][1] = True\n\n for i in range(1, n):\n for j in range(i):\n k = stones[i] - stones[j]\n if k <= n and dp[j][k]:\n dp[i][k - 1] = True\n dp[i][k] = True\n dp[i][k + 1] = True\n\n return any(dp[-1])\n", | |
| "title": "403. Frog Jump", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 448 | |
| }, | |
| { | |
| "code": "class Solution:\n def sumOfLeftLeaves(self, root: TreeNode | None) -> int:\n if not root:\n return 0\n\n ans = 0\n stack = [root]\n\n while stack:\n root = stack.pop()\n if root.left:\n if not root.left.left and not root.left.right:\n ans += root.left.val\n else:\n stack.append(root.left)\n if root.right:\n stack.append(root.right)\n\n return ans\n", | |
| "title": "404. Sum of Left Leaves", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 449 | |
| }, | |
| { | |
| "code": "class Solution:\n def toHex(self, num: int) -> str:\n if num == 0:\n return '0'\n\n hex = '0123456789abcdef'\n ans = []\n\n # Handling negative numbers by using 32-bit unsigned representation Python's\n # bitwise operation works on signed numbers, so we convert to 32-bit\n # unsigned for negative numbers.\n if num < 0:\n num += 2**32\n\n while num > 0:\n ans.append(hex[num & 0xF])\n num >>= 4\n\n return ''.join(reversed(ans))\n", | |
| "title": "405. Convert a Number to Hexadecimal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 450 | |
| }, | |
| { | |
| "code": "class Solution:\n def reconstructQueue(self, people: list[list[int]]) -> list[list[int]]:\n ans = []\n\n people.sort(key=lambda x: (-x[0], x[1]))\n\n for person in people:\n ans.insert(person[1], person)\n\n return ans\n", | |
| "title": "406. Queue Reconstruction by Height", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 451 | |
| }, | |
| { | |
| "code": "class Solution:\n def trapRainWater(self, heightMap: list[list[int]]) -> int:\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(heightMap)\n n = len(heightMap[0])\n ans = 0\n minHeap = []\n seen = set()\n\n for i in range(m):\n heapq.heappush(minHeap, (heightMap[i][0], i, 0))\n heapq.heappush(minHeap, (heightMap[i][n - 1], i, n - 1))\n seen.add((i, 0))\n seen.add((i, n - 1))\n\n for j in range(1, n - 1):\n heapq.heappush(minHeap, (heightMap[0][j], 0, j))\n heapq.heappush(minHeap, (heightMap[m - 1][j], m - 1, j))\n seen.add((0, j))\n seen.add((m - 1, j))\n\n while minHeap:\n h, i, j = heapq.heappop(minHeap)\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if (x, y) in seen:\n continue\n if heightMap[x][y] < h:\n ans += h - heightMap[x][y]\n # Fill water in grid[x][y].\n heapq.heappush(minHeap, (h, x, y))\n else:\n heapq.heappush(minHeap, (heightMap[x][y], x, y))\n seen.add((x, y))\n\n return ans\n", | |
| "title": "407. Trapping Rain Water II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 452 | |
| }, | |
| { | |
| "code": "class Solution:\n def validWordAbbreviation(self, word: str, abbr: str) -> bool:\n i = 0 # word's index\n j = 0 # abbr's index\n\n while i < len(word) and j < len(abbr):\n if word[i] == abbr[j]:\n i += 1\n j += 1\n continue\n if not abbr[j].isdigit() or abbr[j] == '0':\n return False\n num = 0\n while j < len(abbr) and abbr[j].isdigit():\n num = num * 10 + int(abbr[j])\n j += 1\n i += num\n\n return i == len(word) and j == len(abbr)\n", | |
| "title": "408. Valid Word Abbreviation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 453 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestPalindrome(self, s: str) -> int:\n ans = 0\n count = collections.Counter(s)\n\n for c in count.values():\n ans += c if c % 2 == 0 else c - 1\n\n hasOddCount = any(c % 2 == 1 for c in count.values())\n return ans + hasOddCount\n", | |
| "title": "409. Longest Palindrome", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 454 | |
| }, | |
| { | |
| "code": "class Solution:\n def splitArray(self, nums: list[int], k: int) -> int:\n prefix = list(itertools.accumulate(nums, initial=0))\n\n @functools.lru_cache(None)\n def dp(i: int, k: int) -> int:\n \"\"\"\n Returns the minimum of the maximum sum to split the first i numbers into\n k groups.\n \"\"\"\n if k == 1:\n return prefix[i]\n return min(max(dp(j, k - 1), prefix[i] - prefix[j])\n for j in range(k - 1, i))\n\n return dp(len(nums), k)\n", | |
| "title": "410. Split Array Largest Sum_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 455 | |
| }, | |
| { | |
| "code": "class Solution:\n def splitArray(self, nums: list[int], k: int) -> int:\n n = len(nums)\n # dp[i][k] := the minimum of the maximum sum to split the first i numbers\n # into k groups\n dp = [[math.inf] * (k + 1) for _ in range(n + 1)]\n prefix = list(itertools.accumulate(nums, initial=0))\n\n for i in range(1, n + 1):\n dp[i][1] = prefix[i]\n\n for l in range(2, k + 1):\n for i in range(l, n + 1):\n for j in range(l - 1, i):\n dp[i][l] = min(dp[i][l], max(dp[j][l - 1], prefix[i] - prefix[j]))\n\n return dp[n][k]\n", | |
| "title": "410. Split Array Largest Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 456 | |
| }, | |
| { | |
| "code": "class Solution:\n def minAbbreviation(self, target: str, dictionary: list[str]) -> str:\n m = len(target)\n\n def getMask(word: str) -> int:\n # mask[i] = 0 := target[i] == word[i]\n # mask[i] = 1 := target[i] != word[i]\n # e.g. target = \"apple\"\n # word = \"blade\"\n # mask = 11110\n mask = 0\n for i, c in enumerate(word):\n if c != target[i]:\n mask |= 1 << m - 1 - i\n return mask\n\n masks = [getMask(word) for word in dictionary if len(word) == m]\n if not masks:\n return str(m)\n\n abbrs = []\n\n def getAbbr(cand: int) -> str:\n abbr = []\n replacedCount = 0\n for i, c in enumerate(target):\n if cand >> m - 1 - i & 1:\n # If cand[i] = 1, `abbr` should show the original character.\n if replacedCount:\n abbr += str(replacedCount)\n abbr.append(c)\n replacedCount = 0\n else:\n # If cand[i] = 0, `abbr` can be replaced.\n replacedCount += 1\n if replacedCount:\n abbr.append(str(replacedCount))\n return ''.join(abbr)\n\n # all the candidate representation of the target\n for cand in range(2**m):\n # All the masks have at lease one bit different from the candidate.\n if all(cand & mask for mask in masks):\n abbr = getAbbr(cand)\n abbrs.append(abbr)\n\n def getAbbrLen(abbr: str) -> int:\n abbrLen = 0\n i = 0\n j = 0\n while i < len(abbr):\n if abbr[j].isalpha():\n j += 1\n else:\n while j < len(abbr) and abbr[j].isdigit():\n j += 1\n abbrLen += 1\n i = j\n return abbrLen\n\n return min(abbrs, key=lambda x: getAbbrLen(x))\n", | |
| "title": "411. Minimum Unique Word Abbreviation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 457 | |
| }, | |
| { | |
| "code": "class Solution:\n def fizzBuzz(self, n: int) -> list[str]:\n d = {3: 'Fizz', 5: 'Buzz'}\n return [''.join([d[k] for k in d if i % k == 0]) or str(i) for i in range(1, n + 1)]\n", | |
| "title": "412. Fizz Buzz", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 458 | |
| }, | |
| { | |
| "code": "class Solution:\n def numberOfArithmeticSlices(self, nums: list[int]) -> int:\n ans = 0\n dp = 0\n\n for i in range(2, len(nums)):\n if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]:\n dp += 1\n ans += dp\n else:\n dp = 0\n\n return ans\n", | |
| "title": "413. Arithmetic Slices", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 459 | |
| }, | |
| { | |
| "code": "class Solution:\n def thirdMax(self, nums: list[int]) -> int:\n minHeap = []\n seen = set()\n\n for num in nums:\n if num not in seen:\n seen.add(num)\n heapq.heappush(minHeap, num)\n if len(minHeap) > 3:\n heapq.heappop(minHeap)\n\n if len(minHeap) == 2:\n heapq.heappop(minHeap)\n\n return minHeap[0]\n", | |
| "title": "414. Third Maximum Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 460 | |
| }, | |
| { | |
| "code": "class Solution:\n def addStrings(self, num1: str, num2: str) -> str:\n ans = []\n carry = 0\n i = len(num1) - 1\n j = len(num2) - 1\n\n while i >= 0 or j >= 0 or carry:\n if i >= 0:\n carry += int(num1[i])\n if j >= 0:\n carry += int(num2[j])\n ans.append(str(carry % 10))\n carry //= 10\n i -= 1\n j -= 1\n\n return ''.join(reversed(ans))\n", | |
| "title": "415. Add Strings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 461 | |
| }, | |
| { | |
| "code": "class Solution:\n def canPartition(self, nums: list[int]) -> bool:\n summ = sum(nums)\n if summ % 2 == 1:\n return False\n return self.knapsack_(nums, summ // 2)\n\n def knapsack_(self, nums: list[int], subsetSum: int) -> bool:\n # dp[i] := True if i can be formed by nums so far\n dp = [False] * (subsetSum + 1)\n dp[0] = True\n\n for num in nums:\n for i in range(subsetSum, num - 1, -1):\n dp[i] = dp[i] or dp[i - num]\n\n return dp[subsetSum]\n", | |
| "title": "416. Partition Equal Subset Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 462 | |
| }, | |
| { | |
| "code": "class Solution:\n def pacificAtlantic(self, heights: list[list[int]]) -> list[list[int]]:\n m = len(heights)\n n = len(heights[0])\n seenP = [[False] * n for _ in range(m)]\n seenA = [[False] * n for _ in range(m)]\n\n def dfs(i: int, j: int, h: int, seen: list[list[bool]]) -> None:\n if i < 0 or i == m or j < 0 or j == n:\n return\n if seen[i][j] or heights[i][j] < h:\n return\n\n seen[i][j] = True\n dfs(i + 1, j, heights[i][j], seen)\n dfs(i - 1, j, heights[i][j], seen)\n dfs(i, j + 1, heights[i][j], seen)\n dfs(i, j - 1, heights[i][j], seen)\n\n for i in range(m):\n dfs(i, 0, 0, seenP)\n dfs(i, n - 1, 0, seenA)\n\n for j in range(n):\n dfs(0, j, 0, seenP)\n dfs(m - 1, j, 0, seenA)\n\n return [[i, j]\n for i in range(m)\n for j in range(n)\n if seenP[i][j] and seenA[i][j]]\n", | |
| "title": "417. Pacific Atlantic Water Flow", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 463 | |
| }, | |
| { | |
| "code": "class Solution:\n def wordsTyping(self, sentence: list[str], rows: int, cols: int) -> int:\n combined = ' '.join(sentence) + ' '\n n = len(combined)\n i = 0\n\n for _ in range(rows):\n i += cols\n if combined[i % n] == ' ':\n i += 1\n else:\n while i > 0 and combined[(i - 1) % n] != ' ':\n i -= 1\n\n return i // n\n", | |
| "title": "418. Sentence Screen Fitting", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 464 | |
| }, | |
| { | |
| "code": "class Solution:\n def countBattleships(self, board: list[list[str]]) -> int:\n ans = 0\n\n for i, row in enumerate(board):\n for j, cell in enumerate(row):\n if cell == '.':\n continue\n if i > 0 and board[i - 1][j] == 'X':\n continue\n if j > 0 and board[i][j - 1] == 'X':\n continue\n ans += 1\n\n return ans\n", | |
| "title": "419. Battleships in a Board", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 465 | |
| }, | |
| { | |
| "code": "class Solution:\n def strongPasswordChecker(self, password: str) -> int:\n n = len(password)\n missing = self._getMissing(password)\n # the number of replacements to deal with 3 repeating characters\n replaces = 0\n # the number of sequences that can be substituted with 1 deletions,\n # (3k)-seqs\n oneSeq = 0\n # the number of sequences that can be substituted with 2 deletions,\n # (3k + 1)-seqs\n twoSeq = 0\n\n i = 2\n while i < n:\n if password[i] == password[i - 1] and password[i - 1] == password[i - 2]:\n length = 2 # the length of the repeating password\n while i < n and password[i] == password[i - 1]:\n length += 1\n i += 1\n replaces += length // 3 # 'aaaaaaa' -> 'aaxaaxa'\n if length % 3 == 0:\n oneSeq += 1\n if length % 3 == 1:\n twoSeq += 1\n else:\n i += 1\n\n if n < 6:\n return max(6 - n, missing)\n if n <= 20:\n return max(replaces, missing)\n\n deletes = n - 20\n # Each replacement in (3k)-seqs can be substituted with 1 deletions.\n replaces -= min(oneSeq, deletes)\n # Each replacement in (3k + 1)-seqs can be substituted with 2 deletions.\n replaces -= min(max(deletes - oneSeq, 0), twoSeq * 2) // 2\n # Each replacement in other seqs can be substituted with 3 deletions.\n replaces -= max(deletes - oneSeq - twoSeq * 2, 0) // 3\n return deletes + max(replaces, missing)\n\n def _getMissing(self, password: str) -> int:\n return (3\n - any(c.isupper() for c in password)\n - any(c.islower() for c in password)\n - any(c.isdigit() for c in password))\n", | |
| "title": "420. Strong Password Checker", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 466 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: list[TrieNode | None] = [None] * 2\n\n\nclass BitTrie:\n def __init__(self, maxBit: int):\n self.maxBit = maxBit\n self.root = TrieNode()\n\n def insert(self, num: int) -> None:\n node = self.root\n for i in range(self.maxBit, -1, -1):\n bit = num >> i & 1\n if not node.children[bit]:\n node.children[bit] = TrieNode()\n node = node.children[bit]\n\n def getMaxXor(self, num: int) -> int:\n maxXor = 0\n node = self.root\n for i in range(self.maxBit, -1, -1):\n bit = num >> i & 1\n toggleBit = bit ^ 1\n if node.children[toggleBit]:\n maxXor = maxXor | 1 << i\n node = node.children[toggleBit]\n elif node.children[bit]:\n node = node.children[bit]\n else: # There's nothing in the Bit Trie.\n return 0\n return maxXor\n\n\nclass Solution:\n def findMaximumXOR(self, nums: list[int]) -> int:\n maxNum = max(nums)\n if maxNum == 0:\n return 0\n maxBit = int(math.log2(maxNum))\n ans = 0\n bitTrie = BitTrie(maxBit)\n\n for num in nums:\n ans = max(ans, bitTrie.getMaxXor(num))\n bitTrie.insert(num)\n\n return ans\n", | |
| "title": "421. Maximum XOR of Two Numbers in an Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 467 | |
| }, | |
| { | |
| "code": "class Solution:\n def validWordSquare(self, words: list[str]) -> bool:\n for i, word in enumerate(words):\n for j, c in enumerate(word):\n if len(words) <= j or len(words[j]) <= i: # out-of-bounds\n return False\n if c != words[j][i]:\n return False\n return True\n", | |
| "title": "422. Valid Word Square", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 468 | |
| }, | |
| { | |
| "code": "class Solution:\n def originalDigits(self, s: str) -> str:\n count = [0] * 10\n\n for c in s:\n if c == 'z':\n count[0] += 1\n if c == 'o':\n count[1] += 1\n if c == 'w':\n count[2] += 1\n if c == 'h':\n count[3] += 1\n if c == 'u':\n count[4] += 1\n if c == 'f':\n count[5] += 1\n if c == 'x':\n count[6] += 1\n if c == 's':\n count[7] += 1\n if c == 'g':\n count[8] += 1\n if c == 'i':\n count[9] += 1\n\n count[1] -= count[0] + count[2] + count[4]\n count[3] -= count[8]\n count[5] -= count[4]\n count[7] -= count[6]\n count[9] -= count[5] + count[6] + count[8]\n return ''.join(chr(i + ord('0')) for i, c in enumerate(count)\n for _ in range(c))\n", | |
| "title": "423. Reconstruct Original Digits from English", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 469 | |
| }, | |
| { | |
| "code": "class Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n maxCount = 0\n count = collections.Counter()\n\n # l and r track the maximum window instead of the valid window.\n l = 0\n for r, c in enumerate(s):\n count[c] += 1\n maxCount = max(maxCount, count[c])\n while maxCount + k < r - l + 1:\n count[s[l]] -= 1\n l += 1\n\n return r - l + 1\n", | |
| "title": "424. Longest Repeating Character Replacement", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 470 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: dict[str, TrieNode] = {}\n self.startsWith: list[str] = []\n\n\nclass Trie:\n def __init__(self, words: list[str]):\n self.root = TrieNode()\n for word in words:\n self._insert(word)\n\n def findBy(self, prefix: str) -> list[str]:\n node = self.root\n for c in prefix:\n if c not in node.children:\n return []\n node = node.children[c]\n return node.startsWith\n\n def _insert(self, word: str) -> None:\n node = self.root\n for c in word:\n node = node.children.setdefault(c, TrieNode())\n node.startsWith.append(word)\n\n\nclass Solution:\n def wordSquares(self, words: list[str]) -> list[list[str]]:\n if not words:\n return []\n\n n = len(words[0])\n ans = []\n path = []\n trie = Trie(words)\n\n for word in words:\n path.append(word)\n self._dfs(trie, n, path, ans)\n path.pop()\n\n return ans\n\n def _dfs(self, trie: Trie, n: int, path: list[str], ans: list[list[str]]):\n if len(path) == n:\n ans.append(path.copy())\n return\n\n prefix = self._getPrefix(path)\n\n for s in trie.findBy(prefix):\n path.append(s)\n self._dfs(trie, n, path, ans)\n path.pop()\n\n def _getPrefix(self, path: list[str]) -> str:\n \"\"\"\n e.g. path = [\"wall\",\n \"area\"]\n prefix = \"le..\"\n \"\"\"\n prefix = []\n index = len(path)\n for s in path:\n prefix.append(s[index])\n return ''.join(prefix)\n", | |
| "title": "425. Word Squares", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 471 | |
| }, | |
| { | |
| "code": "class Solution:\n def treeToDoublyList(self, root: 'Node | None') -> 'Node | None':\n if not root:\n return None\n\n stack = []\n first = None\n pred = None\n\n while root or stack:\n while root:\n stack.append(root)\n root = root.left\n root = stack.pop()\n if not first:\n first = root\n if pred:\n pred.right = root\n root.left = pred\n pred = root\n root = root.right\n\n pred.right = first\n first.left = pred\n return first\n", | |
| "title": "426. Convert Binary Search Tree to Sorted Doubly Linked List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 472 | |
| }, | |
| { | |
| "code": "class Solution:\n def construct(self, grid: list[list[int]]) -> 'Node':\n return self._helper(grid, 0, 0, len(grid))\n\n def _helper(self, grid: list[list[int]], i: int, j: int, w: int) -> 'Node':\n if self._allSame(grid, i, j, w):\n return Node(grid[i][j] == 1, True)\n half = w // 2\n return Node(True, False,\n self._helper(grid, i, j, half),\n self._helper(grid, i, j + half, half),\n self._helper(grid, i + half, j, half),\n self._helper(grid, i + half, j + half, half))\n\n def _allSame(self, grid: list[list[int]], i: int, j: int, w: int) -> bool:\n return all(grid[x][y] == grid[i][j]\n for x in range(i, i + w)\n for y in range(j, j + w))\n", | |
| "title": "427. Construct Quad Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 473 | |
| }, | |
| { | |
| "code": "class Codec:\n def serialize(self, root: 'Node') -> str:\n \"\"\"Encodes a tree to a single string.\"\"\"\n if not root:\n return ''\n\n s = []\n q = collections.deque([root])\n s.append(str(root.val) + ' ')\n\n while q:\n for _ in range(len(q)):\n node = q.popleft()\n if not node.children:\n s.append('n')\n else:\n for child in node.children:\n q.append(child)\n s.append(str(child.val) + '#')\n s.append(' ')\n\n return ''.join(s)\n\n def deserialize(self, data: str) -> 'Node':\n \"\"\"Decodes your encoded data to tree.\"\"\"\n if not data:\n return None\n\n words = data.split()\n root = Node(int(words[0]))\n q = collections.deque([root])\n\n for word in words[1:]:\n parent = q.popleft()\n children = []\n for kid in word.split('#'):\n if kid in ('', 'n'):\n continue\n child = Node(int(kid))\n children.append(child)\n q.append(child)\n parent.children = children\n\n return root\n", | |
| "title": "428. Serialize and Deserialize N-ary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 474 | |
| }, | |
| { | |
| "code": "class Solution:\n def levelOrder(self, root: 'Node') -> list[list[int]]:\n if not root:\n return []\n\n ans = []\n q = collections.deque([root])\n\n while q:\n currLevel = []\n for _ in range(len(q)):\n node = q.popleft()\n currLevel.append(node.val)\n for child in node.children:\n q.append(child)\n ans.append(currLevel)\n\n return ans\n", | |
| "title": "429. N-ary Tree Level Order Traversal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 475 | |
| }, | |
| { | |
| "code": "class Solution:\n def flatten(self, head: 'Node') -> 'Node':\n curr = head\n\n while curr:\n if curr.child:\n cachedNext = curr.next\n curr.next = curr.child\n curr.child.prev = curr\n curr.child = None\n tail = curr.next\n while tail.next:\n tail = tail.next\n tail.next = cachedNext\n if cachedNext:\n cachedNext.prev = tail\n curr = curr.next\n\n return head\n", | |
| "title": "430. Flatten a Multilevel Doubly Linked List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 476 | |
| }, | |
| { | |
| "code": "class Codec:\n # Encodes an n-ary tree to a binary tree.\n def encode(self, root: 'Node') -> TreeNode | None:\n if not root:\n return None\n\n rootTreeNode = TreeNode(root.val)\n if root.children:\n rootTreeNode.left = self.encode(root.children[0])\n\n # The parent for the rest of the children\n currTreeNode = rootTreeNode.left\n\n # Encode the rest of the children\n for i in range(1, len(root.children)):\n currTreeNode.right = self.encode(root.children[i])\n currTreeNode = currTreeNode.right\n\n return rootTreeNode\n\n # Decodes your binary tree to an n-ary tree.\n def decode(self, root: TreeNode | None) -> 'Node':\n if not root:\n return None\n\n rootNode = Node(root.val, [])\n currTreeNode = root.left\n\n while currTreeNode:\n rootNode.children.append(self.decode(currTreeNode))\n currTreeNode = currTreeNode.right\n\n return rootNode\n", | |
| "title": "431. Encode N-ary Tree to Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 477 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n def __init__(self, count: int, key: str | None = None):\n self.count = count\n self.keys: set[str] = {key} if key else set()\n self.prev: Node | None = None\n self.next: Node | None = None\n\n def __eq__(self, other) -> bool:\n if not isinstance(other, Node):\n return NotImplemented\n return self.count == other.count and self.keys == other.keys\n\n\nclass AllOne:\n def __init__(self):\n self.keyToNode: dict[str, Node] = {}\n self.head = Node(0)\n self.tail = Node(0)\n self.head.next = self.tail\n self.tail.prev = self.head\n\n def inc(self, key: str) -> None:\n if key in self.keyToNode:\n self._incrementExistingKey(key)\n else:\n self._addNewKey(key)\n\n def dec(self, key: str) -> None:\n # It is guaranteed that key exists in the data structure before the\n # decrement.\n self._decrementExistingKey(key)\n\n def getMaxKey(self) -> str:\n return '' if self.tail.prev == self.head \\\n else next(iter(self.tail.prev.keys))\n\n def getMinKey(self) -> str:\n return '' if self.head.next == self.tail \\\n else next(iter(self.head.next.keys))\n\n def _addNewKey(self, key: str) -> None:\n \"\"\"Adds a new node with frequency 1.\"\"\"\n if self.head.next.count == 1:\n self.head.next.keys.add(key)\n else:\n self._insertAfter(self.head, Node(1, key))\n self.keyToNode[key] = self.head.next\n\n def _incrementExistingKey(self, key: str) -> None:\n \"\"\"Increments the frequency of the key by 1.\"\"\"\n node = self.keyToNode[key]\n node.keys.remove(key)\n if node.next == self.tail or node.next.count > node.count + 1:\n self._insertAfter(node, Node(node.count + 1))\n node.next.keys.add(key)\n self.keyToNode[key] = node.next\n if not node.keys:\n self._remove(node)\n\n def _decrementExistingKey(self, key: str) -> None:\n \"\"\"Decrements the count of the key by 1.\"\"\"\n node = self.keyToNode[key]\n node.keys.remove(key)\n if node.count > 1:\n if node.prev == self.head or node.prev.count != node.count - 1:\n self._insertAfter(node.prev, Node(node.count - 1))\n node.prev.keys.add(key)\n self.keyToNode[key] = node.prev\n else:\n del self.keyToNode[key]\n if not node.keys:\n self._remove(node)\n\n def _insertAfter(self, node: Node, newNode: Node) -> None:\n newNode.prev = node\n newNode.next = node.next\n node.next.prev = newNode\n node.next = newNode\n\n def _remove(self, node: Node) -> None:\n node.prev.next = node.next\n node.next.prev = node.prev\n", | |
| "title": "432. All O`one Data Structure", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 478 | |
| }, | |
| { | |
| "code": "class Solution:\n def minMutation(self, startGene: str, endGene: str, bank: list[str]) -> int:\n bankSet = set(bank)\n if endGene not in bankSet:\n return -1\n\n GENES = 'ACGT'\n q = collections.deque([startGene])\n\n step = 1\n while q:\n for _ in range(len(q)):\n wordList = list(q.popleft())\n for j, cache in enumerate(wordList):\n for c in GENES:\n wordList[j] = c\n word = ''.join(wordList)\n if word == endGene:\n return step\n if word in bankSet:\n bankSet.remove(word)\n q.append(word)\n wordList[j] = cache\n step += 1\n\n return -1\n", | |
| "title": "433. Minimum Genetic Mutation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 479 | |
| }, | |
| { | |
| "code": "class Solution:\n def countSegments(self, s: str) -> int:\n return len(s.split())\n", | |
| "title": "434. Number of Segments in a String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 480 | |
| }, | |
| { | |
| "code": "class Solution:\n def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int:\n ans = 0\n currentEnd = -math.inf\n\n for interval in sorted(intervals, key=lambda x: x[1]):\n if interval[0] >= currentEnd:\n currentEnd = interval[1]\n else:\n ans += 1\n\n return ans\n", | |
| "title": "435. Non-overlapping Intervals", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 481 | |
| }, | |
| { | |
| "code": "from sortedcontainers import SortedDict\n\n\nclass Solution:\n def findRightInterval(self, intervals: list[list[int]]) -> list[int]:\n ans = []\n startToIndex = SortedDict()\n\n for i, (start, end) in enumerate(intervals):\n startToIndex[start] = i\n\n for start, end in intervals:\n i = startToIndex.bisect_left(end)\n ans.append(-1 if i == len(startToIndex) else startToIndex.peekitem(i)[1])\n\n return ans\n", | |
| "title": "436. Find Right Interval", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 482 | |
| }, | |
| { | |
| "code": "class Solution:\n def pathSum(self, root: TreeNode | None, summ: int) -> int:\n if not root:\n return 0\n\n def dfs(root: TreeNode, summ: int) -> int:\n if not root:\n return 0\n return (int(summ == root.val) +\n dfs(root.left, summ - root.val) +\n dfs(root.right, summ - root.val))\n\n return (dfs(root, summ) +\n self.pathSum(root.left, summ) +\n self.pathSum(root.right, summ))\n", | |
| "title": "437. Path Sum III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 483 | |
| }, | |
| { | |
| "code": "class Solution:\n def findAnagrams(self, s: str, p: str) -> list[int]:\n ans = []\n count = collections.Counter(p)\n required = len(p)\n\n for r, c in enumerate(s):\n count[c] -= 1\n if count[c] >= 0:\n required -= 1\n if r >= len(p):\n count[s[r - len(p)]] += 1\n if count[s[r - len(p)]] > 0:\n required += 1\n if required == 0:\n ans.append(r - len(p) + 1)\n\n return ans\n", | |
| "title": "438. Find All Anagrams in a String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 484 | |
| }, | |
| { | |
| "code": "class Solution:\n def parseTernary(self, expression: str) -> str:\n c = expression[self.i]\n\n if self.i + 1 == len(expression) or expression[self.i + 1] == ':':\n self.i += 2\n return str(c)\n\n self.i += 2\n first = self.parseTernary(expression)\n second = self.parseTernary(expression)\n\n return first if c == 'T' else second\n\n i = 0\n", | |
| "title": "439. Ternary Expression Parser", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 485 | |
| }, | |
| { | |
| "code": "class Solution:\n def findKthNumber(self, n: int, k: int) -> int:\n ans = 1\n\n i = 1\n while i < k:\n gap = self._getGap(ans, ans + 1, n)\n if i + gap <= k:\n i += gap\n ans += 1\n else:\n i += 1\n ans *= 10\n\n return ans\n\n def _getGap(self, a: int, b: int, n: int) -> int:\n gap = 0\n while a <= n:\n gap += min(n + 1, b) - a\n a *= 10\n b *= 10\n return gap\n", | |
| "title": "440. K-th Smallest in Lexicographical Order", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 486 | |
| }, | |
| { | |
| "code": "class Solution:\n def arrangeCoins(self, n: int) -> int:\n return int((-1 + math.sqrt(8 * n + 1)) // 2)\n", | |
| "title": "441. Arranging Coins", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 487 | |
| }, | |
| { | |
| "code": "class Solution:\n def findDuplicates(self, nums: list[int]) -> list[int]:\n ans = []\n\n for num in nums:\n nums[abs(num) - 1] *= -1\n if nums[abs(num) - 1] > 0:\n ans.append(abs(num))\n\n return ans\n", | |
| "title": "442. Find All Duplicates in an Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 488 | |
| }, | |
| { | |
| "code": "class Solution:\n def compress(self, chars: list[str]) -> int:\n ans = 0\n i = 0\n\n while i < len(chars):\n letter = chars[i]\n count = 0\n while i < len(chars) and chars[i] == letter:\n count += 1\n i += 1\n chars[ans] = letter\n ans += 1\n if count > 1:\n for c in str(count):\n chars[ans] = c\n ans += 1\n\n return ans\n", | |
| "title": "443. String Compression", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 489 | |
| }, | |
| { | |
| "code": "class Solution:\n def sequenceReconstruction(\n self,\n org: list[int],\n seqs: list[list[int]],\n ) -> bool:\n if not seqs:\n return False\n\n n = len(org)\n graph = [[] for _ in range(n)]\n inDegrees = [0] * n\n\n # Build the graph.\n for seq in seqs:\n if len(seq) == 1 and seq[0] < 1 or seq[0] > n:\n return False\n for u, v in zip(seq, seq[1:]):\n if u < 1 or u > n or v < 1 or v > n:\n return False\n graph[u - 1].append(v - 1)\n inDegrees[v - 1] += 1\n\n # Perform topological sorting.\n q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0])\n i = 0 # org's index\n\n while q:\n if len(q) > 1:\n return False\n u = q.popleft()\n if u != org[i] - 1:\n return False\n i += 1\n for v in graph[u]:\n inDegrees[v] -= 1\n if inDegrees[v] == 0:\n q.append(v)\n\n return i == n\n", | |
| "title": "444. Sequence Reconstruction", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 490 | |
| }, | |
| { | |
| "code": "class Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n stack1 = []\n stack2 = []\n\n while l1:\n stack1.append(l1)\n l1 = l1.next\n\n while l2:\n stack2.append(l2)\n l2 = l2.next\n\n head = None\n carry = 0\n\n while carry or stack1 or stack2:\n if stack1:\n carry += stack1.pop().val\n if stack2:\n carry += stack2.pop().val\n node = ListNode(carry % 10)\n node.next = head\n head = node\n carry //= 10\n\n return head\n", | |
| "title": "445. Add Two Numbers II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 491 | |
| }, | |
| { | |
| "code": "class Solution:\n def numberOfArithmeticSlices(self, nums: list[int]) -> int:\n n = len(nums)\n ans = 0\n # dp[i][j] := the number of subsequences end in nums[j] nums[i]\n dp = [[0] * n for _ in range(n)]\n numToIndices = collections.defaultdict(list)\n\n for i, num in enumerate(nums):\n numToIndices[num].append(i)\n\n for i in range(n):\n for j in range(i):\n target = nums[j] * 2 - nums[i]\n if target in numToIndices:\n for k in numToIndices[target]:\n if k < j:\n dp[i][j] += dp[j][k] + 1\n ans += dp[i][j]\n\n return ans\n", | |
| "title": "446. Arithmetic Slices II - Subsequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 492 | |
| }, | |
| { | |
| "code": "class Solution:\n def numberOfBoomerangs(self, points: list[list[int]]) -> int:\n ans = 0\n\n for x1, y1 in points:\n count = collections.Counter()\n for x2, y2 in points:\n ans += 2 * count[(x1 - x2)**2 + (y1 - y2)**2]\n count[(x1 - x2)**2 + (y1 - y2)**2] += 1\n\n return ans\n", | |
| "title": "447. Number of Boomerangs", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 493 | |
| }, | |
| { | |
| "code": "class Solution:\n def findDisappearedNumbers(self, nums: list[int]) -> list[int]:\n for num in nums:\n index = abs(num) - 1\n nums[index] = -abs(nums[index])\n\n return [i + 1 for i, num in enumerate(nums) if num > 0]\n", | |
| "title": "448. Find All Numbers Disappeared in an Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 494 | |
| }, | |
| { | |
| "code": "class Codec:\n def serialize(self, root: TreeNode | None) -> str:\n \"\"\"Encodes a tree to a single string.\"\"\"\n if not root:\n return ''\n chars = []\n self._serialize(root, chars)\n return ''.join(chars)\n\n def deserialize(self, data: str) -> TreeNode | None:\n \"\"\"Decodes your encoded data to tree.\"\"\"\n if not data:\n return None\n q = collections.deque(int(val) for val in data.split())\n return self._deserialize(-math.inf, math.inf, q)\n\n def _serialize(self, root: TreeNode | None, chars: list[str]) -> None:\n if not root:\n return\n chars.append(str(root.val))\n chars.append(' ')\n self._serialize(root.left, chars)\n self._serialize(root.right, chars)\n\n def _deserialize(\n self,\n mn: int,\n mx: int,\n q: collections.deque[int]\n ) -> TreeNode | None:\n if not q:\n return None\n\n val = q[0]\n if val < mn or val > mx:\n return None\n\n q.popleft()\n return TreeNode(val,\n self._deserialize(mn, val, q),\n self._deserialize(val, mx, q))\n", | |
| "title": "449. Serialize and Deserialize BST", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 495 | |
| }, | |
| { | |
| "code": "class Solution:\n def deleteNode(self, root: TreeNode | None, key: int) -> TreeNode | None:\n if not root:\n return None\n if root.val == key:\n if not root.left:\n return root.right\n if not root.right:\n return root.left\n minNode = self._getMin(root.right)\n root.right = self.deleteNode(root.right, minNode.val)\n minNode.left = root.left\n minNode.right = root.right\n root = minNode\n elif root.val < key:\n root.right = self.deleteNode(root.right, key)\n else: # root.val > key\n root.left = self.deleteNode(root.left, key)\n return root\n\n def _getMin(self, node: TreeNode | None) -> TreeNode | None:\n while node.left:\n node = node.left\n return node\n", | |
| "title": "450. Delete Node in a BST", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 496 | |
| }, | |
| { | |
| "code": "class Solution:\n def frequencySort(self, s: str) -> str:\n ans = []\n buckets = [[] for _ in range(len(s) + 1)]\n\n for c, freq in collections.Counter(s).items():\n buckets[freq].append(c)\n\n for freq in reversed(range(len(buckets))):\n for c in buckets[freq]:\n ans.append(c * freq)\n\n return ''.join(ans)\n", | |
| "title": "451. Sort Characters By Frequency", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 497 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMinArrowShots(self, points: list[list[int]]) -> int:\n ans = 0\n arrowX = -math.inf\n\n for point in sorted(points, key=lambda x: x[1]):\n if point[0] > arrowX:\n ans += 1\n arrowX = point[1]\n\n return ans\n", | |
| "title": "452. Minimum Number of Arrows to Burst Balloons", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 498 | |
| }, | |
| { | |
| "code": "class Solution:\n def minMoves(self, nums: list[int]) -> int:\n mn = min(nums)\n return sum(num - mn for num in nums)\n", | |
| "title": "453. Minimum Moves to Equal Array Elements", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 499 | |
| }, | |
| { | |
| "code": "class Solution:\n def fourSumCount(self, nums1: list[int], nums2: list[int],\n nums3: list[int], nums4: list[int]) -> int:\n count = collections.Counter(a + b for a in nums1 for b in nums2)\n return sum(count[-c - d] for c in nums3 for d in nums4)\n", | |
| "title": "454. 4Sum II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 500 | |
| }, | |
| { | |
| "code": "class Solution:\n def findContentChildren(self, g: list[int], s: list[int]) -> int:\n g.sort()\n s.sort()\n\n i = 0\n for cookie in s:\n if i < len(g) and g[i] <= cookie:\n i += 1\n\n return i\n", | |
| "title": "455. Assign Cookies", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 501 | |
| }, | |
| { | |
| "code": "class Solution:\n def find132pattern(self, nums: list[int]) -> bool:\n stack = [] # a decreasing stack\n ak = -math.inf # Find a seq, where ai < ak < aj.\n\n for num in reversed(nums):\n # If ai < ak, done because ai must < aj.\n if num < ak:\n return True\n while stack and stack[-1] < num:\n ak = stack[-1]\n stack.pop()\n stack.append(num) # `nums[i]` is a candidate of aj.\n\n return False\n", | |
| "title": "456. 132 Pattern", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 502 | |
| }, | |
| { | |
| "code": "class Solution:\n def circularArrayLoop(self, nums: list[int]) -> bool:\n def advance(i: int) -> int:\n return (i + nums[i]) % len(nums)\n\n if len(nums) < 2:\n return False\n\n for i, num in enumerate(nums):\n if num == 0:\n continue\n\n slow = i\n fast = advance(slow)\n while num * nums[fast] > 0 and num * nums[advance(fast)] > 0:\n if slow == fast:\n if slow == advance(slow):\n break\n return True\n slow = advance(slow)\n fast = advance(advance(fast))\n\n slow = i\n sign = num\n while sign * nums[slow] > 0:\n next = advance(slow)\n nums[slow] = 0\n slow = next\n\n return False\n", | |
| "title": "457. Circular Array Loop", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 503 | |
| }, | |
| { | |
| "code": "class Solution:\n def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:\n base = minutesToTest // minutesToDie + 1\n ans = 0\n x = 1\n while x < buckets:\n ans += 1\n x *= base\n return ans\n", | |
| "title": "458. Poor Pigs", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 504 | |
| }, | |
| { | |
| "code": "class Solution:\n def repeatedSubstringPattern(self, s: str) -> bool:\n return s in (s + s)[1:-1]\n", | |
| "title": "459. Repeated Substring Pattern", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 505 | |
| }, | |
| { | |
| "code": "class Node:\n def __init__(self, key: int, value: int, freq: int, it):\n self.key = key\n self.value = value\n self.freq = freq\n self.it = it\n\n\nclass LFUCache:\n def __init__(self, capacity: int):\n self.capacity = capacity\n self.minFreq = 0\n self.keyToNode = {}\n self.freqToList = {}\n\n def get(self, key: int) -> int:\n if key not in self.keyToNode:\n return -1\n\n node = self.keyToNode[key]\n self._touch(node)\n return node.value\n\n def put(self, key: int, value: int) -> None:\n if self.capacity == 0:\n return\n\n if key in self.keyToNode:\n node = self.keyToNode[key]\n node.value = value\n self._touch(node)\n return\n\n if len(self.keyToNode) == self.capacity:\n # Evict an LRU key from `minFreq` list\n keyToEvict = self.freqToList[self.minFreq][-1]\n self.freqToList[self.minFreq].pop()\n del self.keyToNode[keyToEvict]\n\n self.minFreq = 1\n if 1 not in self.freqToList:\n self.freqToList[1] = []\n self.freqToList[1].insert(0, key)\n self.keyToNode[key] = Node(key, value, 1, 0) # Using index 0 as iterator\n\n def _touch(self, node: Node) -> None:\n # Update the node's frequency\n prevFreq = node.freq\n node.freq += 1\n newFreq = node.freq\n\n # Remove the key from `prevFreq`'s list\n self.freqToList[prevFreq].remove(node.key)\n if not self.freqToList[prevFreq]:\n del self.freqToList[prevFreq]\n # Update `minFreq` if needed\n if prevFreq == self.minFreq:\n self.minFreq += 1\n\n # Insert the key to the front of `newFreq`'s list\n if newFreq not in self.freqToList:\n self.freqToList[newFreq] = []\n self.freqToList[newFreq].insert(0, node.key)\n node.it = 0 # Using index 0 as iterator\n", | |
| "title": "460. LFU Cache", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 506 | |
| }, | |
| { | |
| "code": "class Solution:\n def hammingDistance(self, x: int, y: int) -> int:\n ans = 0\n\n while x > 0 or y > 0:\n ans += (x & 1) ^ (y & 1)\n x >>= 1\n y >>= 1\n\n return ans\n", | |
| "title": "461. Hamming Distance", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 507 | |
| }, | |
| { | |
| "code": "import statistics\n\n\nclass Solution:\n def minMoves2(self, nums: list[int]) -> int:\n median = int(statistics.median(nums))\n return sum(abs(num - median) for num in nums)\n", | |
| "title": "462. Minimum Moves to Equal Array Elements II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 508 | |
| }, | |
| { | |
| "code": "class Solution:\n def islandPerimeter(self, grid: list[list[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n\n islands = 0\n neighbors = 0\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n islands += 1\n if i + 1 < m and grid[i + 1][j] == 1:\n neighbors += 1\n if j + 1 < n and grid[i][j + 1] == 1:\n neighbors += 1\n\n return islands * 4 - neighbors * 2\n", | |
| "title": "463. Island Perimeter", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 509 | |
| }, | |
| { | |
| "code": "class Solution:\n def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:\n if desiredTotal <= 0:\n return True\n\n totalSum = maxChoosableInteger * (maxChoosableInteger + 1) // 2\n if totalSum < desiredTotal:\n return False\n\n @functools.lru_cache(None)\n def dp(total: int, used: int) -> bool:\n \"\"\"\n Returns true if the first player can we, where `used` represents the use\n numbers.\n \"\"\"\n if total <= 0:\n return False\n return any((used >> i & 1) == 0\n and not dp(total - i, used | 1 << i)\n for i in range(1, maxChoosableInteger + 1))\n\n return dp(desiredTotal, 0)\n", | |
| "title": "464. Can I Win", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 510 | |
| }, | |
| { | |
| "code": "class Solution:\n def minTransfers(self, transactions: list[list[int]]) -> int:\n balance = [0] * 21\n\n for u, v, amount in transactions:\n balance[u] -= amount\n balance[v] += amount\n\n debts = [b for b in balance if b]\n\n def dfs(s: int) -> int:\n while s < len(debts) and not debts[s]:\n s += 1\n if s == len(debts):\n return 0\n\n ans = math.inf\n\n for i in range(s + 1, len(debts)):\n if debts[i] * debts[s] < 0:\n debts[i] += debts[s] # `debts[s]` is settled.\n ans = min(ans, 1 + dfs(s + 1))\n debts[i] -= debts[s] # Backtrack.\n\n return ans\n\n return dfs(0)\n", | |
| "title": "465. Optimal Account Balancing", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312227, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 511 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass\nclass Record:\n count: int\n nextIndex: int\n\n\nclass Solution:\n def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:\n # records[i].count := the number of times that s2 starting from index i has\n # been fully matched with s1\n # records[i].nextIndex := the next index in s2 to be matched after\n # completing a full match starting from index i\n records = []\n\n for nextIndex in range(len(s2)):\n count = 0\n for c in s1:\n if s2[nextIndex] == c:\n nextIndex += 1\n if nextIndex == len(s2): # There's a match.\n count += 1\n nextIndex = 0\n records.append(Record(count, nextIndex))\n\n matches = 0 # the number of matches between `s1` x n1 and `s2`\n i = 0 # the index in `s2` to start matching\n\n for _ in range(n1):\n matches += records[i].count\n i = records[i].nextIndex\n\n return matches // n2\n", | |
| "title": "466. Count The Repetitions", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 512 | |
| }, | |
| { | |
| "code": "class Solution:\n def findSubstringInWraproundString(self, s: str) -> int:\n maxLength = 1\n # count[i] := the number of substrings ending in ('a' + i)\n count = [0] * 26\n\n for i in range(len(s)):\n if i > 0 and (ord(s[i]) - ord(s[i - 1]) == 1\n or ord(s[i - 1]) - ord(s[i]) == 25):\n maxLength += 1\n else:\n maxLength = 1\n index = ord(s[i]) - ord('a')\n count[index] = max(count[index], maxLength)\n\n return sum(count)\n", | |
| "title": "467. Unique Substrings in Wraparound String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 513 | |
| }, | |
| { | |
| "code": "class Solution:\n def validIPAddress(self, queryIP: str) -> str:\n if queryIP.count('.') == 3:\n parts = queryIP.split('.')\n if len(parts) == 4 and all(self._isIPv4(part) for part in parts):\n return 'IPv4'\n\n if queryIP.count(':') == 7:\n parts = queryIP.split(':')\n if len(parts) == 8 and all(self._isIPv6(part) for part in parts):\n return 'IPv6'\n\n return 'Neither'\n\n def _isIPv4(self, digit: str) -> bool:\n if not digit or len(digit) > 3:\n return False\n if len(digit) > 1 and digit[0] == '0':\n return False\n if not all(c.isdigit() for c in digit):\n return False\n num = int(digit)\n return 0 <= num <= 255\n\n def _isIPv6(self, digit: str) -> bool:\n if not digit or len(digit) > 4:\n return False\n validChars = set('0123456789abcdefABCDEF')\n return all(c in validChars for c in digit)\n", | |
| "title": "468. Validate IP Address", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 514 | |
| }, | |
| { | |
| "code": "class Solution:\n def isConvex(self, points: list[list[int]]) -> bool:\n def getCross(p: list[int], q: list[int], r: list[int]):\n \"\"\"Returns pq x qr.\"\"\"\n return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])\n\n sign = 0\n for i in range(len(points)):\n cross = getCross(points[i - 2], points[i - 1], points[i])\n if cross == 0: # p, q, r are collinear.\n continue\n if sign == 0: # Find the first cross that's not 0.\n sign = cross\n elif cross * sign < 0:\n return False\n\n return True\n", | |
| "title": "469. Convex Polygon", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 515 | |
| }, | |
| { | |
| "code": "# The rand7() API is already defined for you.\n# def rand7():\n# @return a random integer in the range 1 to 7\n\nclass Solution:\n def rand10(self) -> int:\n num = 40\n while num >= 40:\n num = (rand7() - 1) * 7 + (rand7() - 1)\n return num % 10 + 1\n", | |
| "title": "470. Implement Rand10() Using Rand7()", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 516 | |
| }, | |
| { | |
| "code": "class Solution:\n def encode(self, s: str) -> str:\n n = len(s)\n # dp[i][j] := the shortest encoded string of s[i..j]\n dp = [[''] * n for _ in range(n)]\n\n for d in range(n):\n for i in range(n - d):\n j = i + d\n curr = s[i:j + 1]\n dp[i][j] = curr\n\n if len(dp[i][j]) < 5:\n continue\n\n # Try all the possible partitions.\n for k in range(i, j):\n if len(dp[i][k]) + len(dp[k + 1][j]) < len(dp[i][j]):\n dp[i][j] = dp[i][k] + dp[k + 1][j]\n\n # Try to compress the string.\n # e.g. s = aabaabaab -> 3[aab]\n for k in range(i, j):\n pattern = s[i:k + 1]\n if len(curr) % len(pattern) == 0 and pattern * (len(curr) //\n len(pattern)) == curr:\n candidate = f\"{len(curr) // len(pattern)}[{dp[i][k]}]\"\n if len(candidate) < len(dp[i][j]):\n dp[i][j] = candidate\n\n return dp[0][n - 1]\n", | |
| "title": "471. Encode String with Shortest Length", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 517 | |
| }, | |
| { | |
| "code": "class Solution:\n def findAllConcatenatedWordsInADict(self, words: list[str]) -> list[str]:\n wordSet = set(words)\n\n @functools.lru_cache(None)\n def isConcat(word: str) -> bool:\n for i in range(1, len(word)):\n prefix = word[:i]\n suffix = word[i:]\n if prefix in wordSet and (suffix in wordSet or isConcat(suffix)):\n return True\n\n return False\n\n return [word for word in words if isConcat(word)]\n", | |
| "title": "472. Concatenated Words", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 518 | |
| }, | |
| { | |
| "code": "class Solution:\n def makesquare(self, matchsticks: list[int]) -> bool:\n if len(matchsticks) < 4:\n return False\n\n perimeter = sum(matchsticks)\n if perimeter % 4 != 0:\n return False\n\n A = sorted(matchsticks)[::-1]\n\n def dfs(selected: int, edges: list[int]) -> bool:\n if selected == len(A):\n return all(edge == edges[0] for edge in edges)\n\n for i, edge in enumerate(edges):\n if A[selected] > edge:\n continue\n edges[i] -= A[selected]\n if dfs(selected + 1, edges):\n return True\n edges[i] += A[selected]\n\n return False\n\n return dfs(0, [perimeter // 4] * 4)\n", | |
| "title": "473. Matchsticks to Square", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 519 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMaxForm(self, strs: list[str], m: int, n: int) -> int:\n # dp[i][j] := the maximum size of the subset given i 0s and j 1s are\n # available\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n for s in strs:\n zeros = s.count('0')\n ones = len(s) - zeros\n for i in range(m, zeros - 1, -1):\n for j in range(n, ones - 1, -1):\n dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)\n\n return dp[m][n]\n", | |
| "title": "474. Ones and Zeroes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 520 | |
| }, | |
| { | |
| "code": "class Solution:\n def totalHammingDistance(self, nums: list[int]) -> int:\n MAX_BIT = 30\n ans = 0\n\n for i in range(MAX_BIT):\n ones = sum(num & (1 << i) > 0 for num in nums)\n zeros = len(nums) - ones\n ans += ones * zeros\n\n return ans\n", | |
| "title": "477. Total Hamming Distance", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 521 | |
| }, | |
| { | |
| "code": "class Solution:\n def __init__(self, radius: float, x_center: float, y_center: float):\n self.radius = radius\n self.x_center = x_center\n self.y_center = y_center\n\n def randPoint(self) -> list[float]:\n length = math.sqrt(random.uniform(0, 1)) * self.radius\n degree = random.uniform(0, 1) * 2 * math.pi\n x = self.x_center + length * math.cos(degree)\n y = self.y_center + length * math.sin(degree)\n return [x, y]\n", | |
| "title": "478. Generate Random Point in a Circle", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 522 | |
| }, | |
| { | |
| "code": "class Solution:\n def largestPalindrome(self, n: int) -> int:\n if n == 1:\n return 9\n\n MOD = 1337\n upper = pow(10, n) - 1\n lower = pow(10, n - 1) - 1\n\n for i in range(upper, lower, -1):\n cand = int(str(i) + str(i)[::-1])\n j = upper\n while j * j >= cand:\n if cand % j == 0:\n return cand % MOD\n j -= 1\n", | |
| "title": "479. Largest Palindrome Product", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 523 | |
| }, | |
| { | |
| "code": "class Solution:\n def magicalString(self, n: int) -> int:\n s = [' ', '1', '2', '2']\n\n for i in range(3, n + 1):\n if i % 2 == 1:\n s.extend(['1'] * (int(s[i])))\n else:\n s.extend(['2'] * (int(s[i])))\n\n return sum(1 for c in s[:n + 1] if c == '1')\n", | |
| "title": "481. Magical String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 524 | |
| }, | |
| { | |
| "code": "class Solution:\n def licenseKeyFormatting(self, s: str, k: int) -> str:\n ans = []\n length = 0\n\n for i in reversed(range(len(s))):\n if s[i] == '-':\n continue\n if length > 0 and length % k == 0:\n ans += '-'\n ans += s[i].upper()\n length += 1\n\n return ''.join(reversed(ans))\n", | |
| "title": "482. License Key Formatting", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 525 | |
| }, | |
| { | |
| "code": "class Solution:\n def smallestGoodBase(self, n: str) -> str:\n n = int(n)\n\n for m in range(int(math.log(n, 2)), 1, -1):\n k = int(n**m**-1)\n if (k**(m + 1) - 1) // (k - 1) == n:\n return str(k)\n\n return str(n - 1)\n", | |
| "title": "483. Smallest Good Base", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 526 | |
| }, | |
| { | |
| "code": "class Solution:\n def findPermutation(self, s: str) -> list[int]:\n ans = [i for i in range(1, len(s) + 2)]\n\n # For each D* group (s[i..j]), reverse ans[i..j + 1].\n i = -1\n j = -1\n\n def getNextIndex(c: str, start: int) -> int:\n for i in range(start, len(s)):\n if s[i] == c:\n return i\n return len(s)\n\n while True:\n i = getNextIndex('D', j + 1)\n if i == len(s):\n break\n j = getNextIndex('I', i + 1)\n ans[i:j + 1] = ans[i:j + 1][::-1]\n\n return ans\n", | |
| "title": "484. Find Permutation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 527 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMaxConsecutiveOnes(self, nums: list[int]) -> int:\n ans = 0\n summ = 0\n\n for num in nums:\n if num == 0:\n summ = 0\n else:\n summ += num\n ans = max(ans, summ)\n\n return ans\n", | |
| "title": "485. Max Consecutive Ones", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 528 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMaxConsecutiveOnes(self, nums: list[int]) -> int:\n ans = 0\n zeros = 0\n\n l = 0\n for r, num in enumerate(nums):\n if num == 0:\n zeros += 1\n while zeros == 2:\n if nums[l] == 0:\n zeros -= 1\n l += 1\n ans = max(ans, r - l + 1)\n\n return ans\n", | |
| "title": "487. Max Consecutive Ones II_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 529 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMaxConsecutiveOnes(self, nums: list[int]) -> int:\n maxZeros = 1\n ans = 0\n q = collections.deque() # Store indices of zero.\n\n l = 0\n for r, num in enumerate(nums):\n if num == 0:\n q.append(r)\n if len(q) > maxZeros:\n l = q.popleft() + 1\n ans = max(ans, r - l + 1)\n\n return ans\n", | |
| "title": "487. Max Consecutive Ones II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 530 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMinStep(self, board: str, hand: str) -> int:\n def deDup(board):\n start = 0 # the start index of a color sequenece\n for i, c in enumerate(board):\n if c != board[start]:\n if i - start >= 3:\n return deDup(board[:start] + board[i:])\n start = i # Meet a new sequence.\n return board\n\n @functools.lru_cache(None)\n def dfs(board: str, hand: str):\n board = deDup(board)\n if board == '#':\n return 0\n\n boardSet = set(board)\n # hand that is in board\n hand = ''.join(h for h in hand if h in boardSet)\n if not hand: # infeasible\n return math.inf\n\n ans = math.inf\n\n for i in range(len(board)):\n for j, h in enumerate(hand):\n # Place hs[j] in board[i].\n newHand = hand[:j] + hand[j + 1:]\n newBoard = board[:i] + h + board[i:]\n ans = min(ans, 1 + dfs(newBoard, newHand))\n\n return ans\n\n ans = dfs(board + '#', hand)\n return -1 if ans == math.inf else ans\n", | |
| "title": "488. Zuma Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 531 | |
| }, | |
| { | |
| "code": "class Solution:\n def hasPath(\n self,\n maze: list[list[int]],\n start: list[int],\n destination: list[int],\n ) -> bool:\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(maze)\n n = len(maze[0])\n\n seen = set()\n\n def isValid(x: int, y: int) -> bool:\n return 0 <= x < m and 0 <= y < n and maze[x][y] == 0\n\n def dfs(i: int, j: int) -> bool:\n if [i, j] == destination:\n return True\n if (i, j) in seen:\n return False\n\n seen.add((i, j))\n\n for dx, dy in DIRS:\n x = i\n y = j\n while isValid(x + dx, y + dy):\n x += dx\n y += dy\n if dfs(x, y):\n return True\n\n return False\n\n return dfs(start[0], start[1])\n", | |
| "title": "490. The Maze", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 532 | |
| }, | |
| { | |
| "code": "class Solution:\n def findSubsequences(self, nums: list[int]) -> list[list[int]]:\n ans = []\n\n def dfs(s: int, path: list[int]) -> None:\n if len(path) > 1:\n ans.append(path)\n\n used = set()\n\n for i in range(s, len(nums)):\n if nums[i] in used:\n continue\n if not path or nums[i] >= path[-1]:\n used.add(nums[i])\n dfs(i + 1, path + [nums[i]])\n\n dfs(0, [])\n return ans\n", | |
| "title": "491. Increasing Subsequences", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 533 | |
| }, | |
| { | |
| "code": "class Solution:\n def findTargetSumWays(self, nums: list[int], target: int) -> int:\n summ = sum(nums)\n if summ < abs(target) or (summ + target) % 2 == 1:\n return 0\n\n def knapsack(nums: list[int], target: int) -> int:\n # dp[i] := the number of ways to sum to i by nums so far\n dp = [0] * (target + 1)\n dp[0] = 1\n\n for num in nums:\n for i in range(target, num - 1, -1):\n dp[i] += dp[i - num]\n\n return dp[target]\n\n return knapsack(nums, (summ + target) // 2)\n", | |
| "title": "494. Target Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 534 | |
| }, | |
| { | |
| "code": "class Solution:\n def findPoisonedDuration(self, timeSeries: list[int], duration: int) -> int:\n if duration == 0:\n return 0\n\n ans = 0\n\n for i in range(0, len(timeSeries) - 1):\n ans += min(timeSeries[i + 1] - timeSeries[i], duration)\n\n return ans + duration\n", | |
| "title": "495. Teemo Attacking", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 535 | |
| }, | |
| { | |
| "code": "class Solution:\n def nextGreaterElement(self, nums1: list[int], nums2: list[int]) -> list[int]:\n numToNextGreater = {}\n stack = [] # a decreasing stack\n\n for num in nums2:\n while stack and stack[-1] < num:\n numToNextGreater[stack.pop()] = num\n stack.append(num)\n\n return [numToNextGreater.get(num, -1) for num in nums1]\n", | |
| "title": "496. Next Greater Element I", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 536 | |
| }, | |
| { | |
| "code": "class Solution:\n def __init__(self, rects: list[list[int]]):\n self.rects = rects\n self.areas = list(itertools.accumulate(\n [(x2 - x1 + 1) * (y2 - y1 + 1) for x1, y1, x2, y2 in rects]))\n\n def pick(self) -> list[int]:\n index = bisect_right(self.areas, random.randint(0, self.areas[-1] - 1))\n x1, y1, x2, y2 = self.rects[index]\n return [random.randint(x1, x2), random.randint(y1, y2)]\n", | |
| "title": "497. Random Point in Non-overlapping Rectangles", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 537 | |
| }, | |
| { | |
| "code": "class Solution:\n def findShortestWay(\n self,\n maze: list[list[int]],\n ball: list[int],\n hole: list[int],\n ) -> str:\n ans = 'impossible'\n minSteps = math.inf\n\n def dfs(i: int, j: int, dx: int, dy: int, steps: int, path: str):\n nonlocal ans\n nonlocal minSteps\n if steps >= minSteps:\n return\n\n if dx != 0 or dy != 0: # Both are zeros for the initial ball position.\n while (0 <= i + dx < len(maze) and 0 <= j + dy < len(maze[0]) and\n maze[i + dx][j + dy] != 1):\n i += dx\n j += dy\n steps += 1\n if i == hole[0] and j == hole[1] and steps < minSteps:\n minSteps = steps\n ans = path\n\n if maze[i][j] == 0 or steps + 2 < maze[i][j]:\n maze[i][j] = steps + 2 # +2 because maze[i][j] == 0 || 1.\n if dx == 0:\n dfs(i, j, 1, 0, steps, path + 'd')\n if dy == 0:\n dfs(i, j, 0, -1, steps, path + 'l')\n if dy == 0:\n dfs(i, j, 0, 1, steps, path + 'r')\n if dx == 0:\n dfs(i, j, -1, 0, steps, path + 'u')\n\n dfs(ball[0], ball[1], 0, 0, 0, '')\n return ans\n", | |
| "title": "499. The Maze III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 538 | |
| }, | |
| { | |
| "code": "class Solution:\n def findWords(self, words: list[str]) -> list[str]:\n ans = []\n rows = [set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')]\n\n for word in words:\n lowerWord = set(word.lower())\n if any(lowerWord <= row for row in rows):\n ans.append(word)\n\n return ans\n", | |
| "title": "500. Keyboard Row", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 539 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMode(self, root: TreeNode | None) -> list[int]:\n self.ans = []\n self.pred = None\n self.count = 0\n self.maxCount = 0\n\n def updateCount(root: TreeNode | None) -> None:\n if self.pred and self.pred.val == root.val:\n self.count += 1\n else:\n self.count = 1\n\n if self.count > self.maxCount:\n self.maxCount = self.count\n self.ans = [root.val]\n elif self.count == self.maxCount:\n self.ans.append(root.val)\n\n self.pred = root\n\n def inorder(root: TreeNode | None) -> None:\n if not root:\n return\n\n inorder(root.left)\n updateCount(root)\n inorder(root.right)\n\n inorder(root)\n return self.ans\n", | |
| "title": "501. Find Mode in Binary Search Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 540 | |
| }, | |
| { | |
| "code": "class Solution:\n def nextGreaterElements(self, nums: list[int]) -> list[int]:\n n = len(nums)\n ans = [-1] * n\n stack = [] # a decreasing stack storing indices\n\n for i in range(n * 2):\n num = nums[i % n]\n while stack and nums[stack[-1]] < num:\n ans[stack.pop()] = num\n if i < n:\n stack.append(i)\n\n return ans\n", | |
| "title": "503. Next Greater Element II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 541 | |
| }, | |
| { | |
| "code": "class Solution:\n def checkPerfectNumber(self, num: int) -> bool:\n return num in {6, 28, 496, 8128, 33550336}\n", | |
| "title": "507. Perfect Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 542 | |
| }, | |
| { | |
| "code": "class Solution:\n def findFrequentTreeSum(self, root: TreeNode | None) -> list[int]:\n if not root:\n return []\n\n count = collections.Counter()\n\n def dfs(root: TreeNode | None) -> int:\n if not root:\n return 0\n\n summ = root.val + dfs(root.left) + dfs(root.right)\n count[summ] += 1\n return summ\n\n dfs(root)\n maxFreq = max(count.values())\n return [summ for summ in count if count[summ] == maxFreq]\n", | |
| "title": "508. Most Frequent Subtree Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 543 | |
| }, | |
| { | |
| "code": "class Solution:\n def fib(self, n: int) -> int:\n if n < 2:\n return n\n\n dp = [0, 0, 1]\n\n for i in range(2, n + 1):\n dp[0] = dp[1]\n dp[1] = dp[2]\n dp[2] = dp[0] + dp[1]\n\n return dp[2]\n", | |
| "title": "509. Fibonacci Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 544 | |
| }, | |
| { | |
| "code": "SELECT player_id, MIN(event_date) AS first_login\nFROM Activity\nGROUP BY 1;\n", | |
| "title": "511. Game Play Analysis I", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 545 | |
| }, | |
| { | |
| "code": "SELECT DISTINCT\n player_id,\n FIRST_VALUE(device_id) OVER(\n PARTITION by player_id\n ORDER BY event_date\n ) AS device_id\nFROM Activity;\n", | |
| "title": "512. Game Play Analysis II", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 546 | |
| }, | |
| { | |
| "code": "class Solution:\n def findBottomLeftValue(self, root: TreeNode | None) -> int:\n ans = 0\n maxDepth = 0\n\n def dfs(root: TreeNode | None, depth: int) -> None:\n nonlocal ans\n nonlocal maxDepth\n if not root:\n return\n if depth > maxDepth:\n maxDepth = depth\n ans = root.val\n\n dfs(root.left, depth + 1)\n dfs(root.right, depth + 1)\n\n dfs(root, 1)\n return ans\n", | |
| "title": "513. Find Bottom Left Tree Value", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 547 | |
| }, | |
| { | |
| "code": "class Solution:\n def findRotateSteps(self, ring: str, key: str) -> int:\n @functools.lru_cache(None)\n def dfs(ring: str, index: int) -> int:\n \"\"\"Returns the number of rotates of ring to match key[index..n).\"\"\"\n if index == len(key):\n return 0\n\n ans = math.inf\n\n # For each ring[i] == key[index], we rotate the ring to match the ring[i]\n # with the key[index], then recursively match the newRing with the\n # key[index + 1..n).\n for i, r in enumerate(ring):\n if r == key[index]:\n minRotates = min(i, len(ring) - i)\n newRing = ring[i:] + ring[:i]\n remainingRotates = dfs(newRing, index + 1)\n ans = min(ans, minRotates + remainingRotates)\n\n return ans\n\n return dfs(ring, 0) + len(key)\n", | |
| "title": "514. Freedom Trail", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 548 | |
| }, | |
| { | |
| "code": "class Solution:\n def largestValues(self, root: TreeNode | None) -> list[int]:\n ans = []\n\n def dfs(root: TreeNode | None, depth: int) -> None:\n if not root:\n return\n if depth + 1 > len(ans):\n ans.append(root.val)\n else:\n ans[depth] = max(ans[depth], root.val)\n\n dfs(root.left, depth + 1)\n dfs(root.right, depth + 1)\n\n dfs(root, 0)\n return ans\n", | |
| "title": "515. Find Largest Value in Each Tree Row", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 549 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n n = len(s)\n # dp[i][j] := the length of LPS(s[i..j])\n dp = [[0] * n for _ in range(n)]\n\n for i in range(n):\n dp[i][i] = 1\n\n for d in range(1, n):\n for i in range(n - d):\n j = i + d\n if s[i] == s[j]:\n dp[i][j] = 2 + dp[i + 1][j - 1]\n else:\n dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])\n\n return dp[0][n - 1]\n", | |
| "title": "516. Longest Palindromic Subsequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 550 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMinMoves(self, machines: list[int]) -> int:\n dresses = sum(machines)\n\n if dresses % len(machines) != 0:\n return -1\n\n ans = 0\n average = dresses // len(machines)\n inout = 0\n\n for dress in machines:\n inout += dress - average\n ans = max(ans, abs(inout), dress - average)\n\n return ans\n", | |
| "title": "517. Super Washing Machines", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 551 | |
| }, | |
| { | |
| "code": "class Solution:\n def change(self, amount: int, coins: list[int]) -> int:\n dp = [1] + [0] * amount\n\n for coin in coins:\n for i in range(coin, amount + 1):\n dp[i] += dp[i - coin]\n\n return dp[amount]\n", | |
| "title": "518. Coin Change 2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 552 | |
| }, | |
| { | |
| "code": "class Solution:\n def detectCapitalUse(self, word: str) -> bool:\n return word.isupper() or word.islower() or word.istitle()\n", | |
| "title": "520. Detect Capital", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 553 | |
| }, | |
| { | |
| "code": "class Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n return -1 if a == b else max(len(a), len(b))\n", | |
| "title": "521. Longest Uncommon Subsequence I", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 554 | |
| }, | |
| { | |
| "code": "class Solution:\n def findLUSlength(self, strs: list[str]) -> int:\n def isSubsequence(a: str, b: str) -> bool:\n i = 0\n j = 0\n\n while i < len(a) and j < len(b):\n if a[i] == b[j]:\n i += 1\n j += 1\n\n return i == len(a)\n\n seen = set()\n duplicates = set()\n\n for s in strs:\n if s in seen:\n duplicates.add(s)\n seen.add(s)\n\n strs.sort(key=lambda x: -len(x))\n\n for i in range(len(strs)):\n if strs[i] in duplicates:\n continue\n isASubsequence = False\n for j in range(i):\n isASubsequence |= isSubsequence(strs[i], strs[j])\n if not isASubsequence:\n return len(strs[i])\n\n return -1\n", | |
| "title": "522. Longest Uncommon Subsequence II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 555 | |
| }, | |
| { | |
| "code": "class Solution:\n def checkSubarraySum(self, nums: list[int], k: int) -> bool:\n prefix = 0\n prefixToIndex = {0: -1}\n\n for i, num in enumerate(nums):\n prefix += num\n if k != 0:\n prefix %= k\n if prefix in prefixToIndex:\n if i - prefixToIndex[prefix] > 1:\n return True\n else:\n # Set a new key if it's absent because the previous index is better.\n prefixToIndex[prefix] = i\n\n return False\n", | |
| "title": "523. Continuous Subarray Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 556 | |
| }, | |
| { | |
| "code": "class Solution:\n def findLongestWord(self, s: str, d: list[str]) -> str:\n ans = ''\n\n for word in d:\n i = 0\n for c in s:\n if i < len(word) and c == word[i]:\n i += 1\n if i == len(word):\n if len(word) > len(ans) or len(word) == len(ans) and word < ans:\n ans = word\n\n return ans\n", | |
| "title": "524. Longest Word in Dictionary through Deleting", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 557 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMaxLength(self, nums: list[int]) -> int:\n ans = 0\n prefix = 0\n prefixToIndex = {0: -1}\n\n for i, num in enumerate(nums):\n prefix += 1 if num else -1\n ans = max(ans, i - prefixToIndex.setdefault(prefix, i))\n\n return ans\n", | |
| "title": "525. Contiguous Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 558 | |
| }, | |
| { | |
| "code": "class Solution:\n def wordsAbbreviation(self, words: list[str]) -> list[str]:\n n = len(words)\n\n def getAbbrev(s: str, prefixIndex: int) -> str:\n n = len(s)\n num = n - (prefixIndex + 1) - 1\n numLength = 1 if num < 10 else (2 if num < 100 else 3)\n abbrevLength = (prefixIndex + 1) + numLength + 1\n if abbrevLength >= n:\n return s\n return s[:prefixIndex + 1] + str(num) + s[-1]\n\n ans = [getAbbrev(word, 0) for word in words]\n # prefix[i] := ans[i] takes words[i][0..prefix[i]]\n prefix = [0] * n\n\n for i in range(n):\n while True:\n dupeIndices = []\n for j in range(i + 1, n):\n if ans[i] == ans[j]:\n dupeIndices.append(j)\n if not dupeIndices:\n break\n dupeIndices.append(i)\n for index in dupeIndices:\n prefix[index] += 1\n ans[index] = getAbbrev(words[index], prefix[index])\n\n return ans\n", | |
| "title": "527. Word Abbreviation_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 559 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass\nclass IndexedWord:\n word: str\n index: int\n\n\nclass Solution:\n def wordsAbbreviation(self, words: list[str]) -> list[str]:\n n = len(words)\n ans = [''] * n\n\n def getAbbrev(s: str, prefixIndex: int) -> str:\n n = len(s)\n num = n - (prefixIndex + 1) - 1\n numLength = 1 if num < 10 else (2 if num < 100 else 3)\n abbrevLength = (prefixIndex + 1) + numLength + 1\n if abbrevLength >= n:\n return s\n return s[:prefixIndex + 1] + str(num) + s[-1]\n\n abbrevToIndexedWords = collections.defaultdict(list)\n\n for i, word in enumerate(words):\n abbrev = getAbbrev(word, 0)\n abbrevToIndexedWords[abbrev].append(IndexedWord(word, i))\n\n def longestCommonPrefix(s1: str, s2: str) -> int:\n i = 0\n while i < len(s1) and i < len(s2) and s1[i] == s2[i]:\n i += 1\n return i\n\n for indexedWords in abbrevToIndexedWords.values():\n indexedWords.sort(key=lambda x: x.word)\n lcp = [0] * len(indexedWords)\n for i, (a, b) in enumerate(zip(indexedWords, indexedWords[1:])):\n k = longestCommonPrefix(a.word, b.word)\n lcp[i] = max(lcp[i], k)\n lcp[i + 1] = k\n for iw, l in zip(indexedWords, lcp):\n ans[iw.index] = getAbbrev(iw.word, l)\n\n return ans\n", | |
| "title": "527. Word Abbreviation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 560 | |
| }, | |
| { | |
| "code": "class Solution:\n def __init__(self, w: list[int]):\n self.prefix = list(itertools.accumulate(w))\n\n def pickIndex(self) -> int:\n return bisect_left(self.prefix, random.random() * self.prefix[-1])\n", | |
| "title": "528. Random Pick with Weight", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 561 | |
| }, | |
| { | |
| "code": "class Solution:\n def updateBoard(self, board: list[list[str]],\n click: list[int]) -> list[list[str]]:\n i, j = click\n if board[i][j] == 'M':\n board[i][j] = 'X'\n return board\n\n DIRS = ((-1, -1), (-1, 0), (-1, 1), (0, -1),\n (0, 1), (1, -1), (1, 0), (1, 1))\n\n def getMinesCount(i: int, j: int) -> int:\n minesCount = 0\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x == len(board) or y < 0 or y == len(board[0]):\n continue\n if board[x][y] == 'M':\n minesCount += 1\n return minesCount\n\n def dfs(i: int, j: int) -> None:\n if i < 0 or i == len(board) or j < 0 or j == len(board[0]):\n return\n if board[i][j] != 'E':\n return\n\n minesCount = getMinesCount(i, j)\n board[i][j] = 'B' if minesCount == 0 else str(minesCount)\n\n if minesCount == 0:\n for dx, dy in DIRS:\n dfs(i + dx, j + dy)\n\n dfs(i, j)\n return board\n", | |
| "title": "529. Minesweeper", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 562 | |
| }, | |
| { | |
| "code": "class Solution:\n def findLonelyPixel(self, picture: list[list[str]]) -> int:\n m = len(picture)\n n = len(picture[0])\n ans = 0\n rows = [0] * m # rows[i] := the number of B's in rows i\n cols = [0] * n # cols[i] := the number of B's in cols i\n\n for i in range(m):\n for j in range(n):\n if picture[i][j] == 'B':\n rows[i] += 1\n cols[j] += 1\n\n for i in range(m):\n if rows[i] == 1: # Only have to examine the rows if rows[i] == 1.\n for j in range(n):\n # After meeting a 'B' in this rows, break and search the next row.\n if picture[i][j] == 'B':\n if cols[j] == 1:\n ans += 1\n break\n\n return ans\n", | |
| "title": "531. Lonely Pixel I", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 563 | |
| }, | |
| { | |
| "code": "class Solution:\n def findPairs(self, nums: list[int], k: int) -> int:\n ans = 0\n numToIndex = {num: i for i, num in enumerate(nums)}\n\n for i, num in enumerate(nums):\n target = num + k\n if target in numToIndex and numToIndex[target] != i:\n ans += 1\n del numToIndex[target]\n\n return ans\n", | |
| "title": "532. K-diff Pairs in an Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 564 | |
| }, | |
| { | |
| "code": "class Solution:\n def findBlackPixel(self, picture: list[list[str]], target: int) -> int:\n m = len(picture)\n n = len(picture[0])\n ans = 0\n rows = [row.count('B') for row in picture]\n cols = [col.count('B') for col in zip(*picture)]\n rowStrings = [''.join(row) for row in picture]\n countRowStrings = collections.Counter(rowStrings)\n\n for i, (row, stringRow) in enumerate(zip(rows, rowStrings)):\n if row == target and countRowStrings[stringRow] == target:\n for j, col in enumerate(cols):\n if picture[i][j] == 'B' and col == target:\n ans += 1\n\n return ans\n", | |
| "title": "533. Lonely Pixel II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 565 | |
| }, | |
| { | |
| "code": "SELECT\n Activity.player_id,\n Activity.event_date,\n SUM(PrevActivity.games_played) AS games_played_so_far\nFROM Activity\nINNER JOIN Activity AS PrevActivity\n ON (\n Activity.player_id = PrevActivity.player_id\n AND Activity.event_date >= PrevActivity.event_date)\nGROUP BY 1, 2\nORDER BY 1, 2;\n", | |
| "title": "534. Game Play Analysis III", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 566 | |
| }, | |
| { | |
| "code": "class Codec:\n alphabets = string.ascii_letters + '0123456789'\n urlToCode = {}\n codeToUrl = {}\n\n def encode(self, longUrl: str) -> str:\n while longUrl not in self.urlToCode:\n code = ''.join(random.choice(self.alphabets) for _ in range(6))\n if code not in self.codeToUrl:\n self.codeToUrl[code] = longUrl\n self.urlToCode[longUrl] = code\n return 'http://tinyurl.com/' + self.urlToCode[longUrl]\n\n def decode(self, shortUrl: str) -> str:\n return self.codeToUrl[shortUrl[-6:]]\n", | |
| "title": "535. Encode and Decode TinyURL", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 567 | |
| }, | |
| { | |
| "code": "class Solution:\n def complexNumberMultiply(self, num1: str, num2: str) -> str:\n a0, a1 = self._getReala0ndImag(num1)\n b0, b1 = self._getReala0ndImag(num2)\n return str(a0 * b0 - a1 * b1) + '+' + str(a0 * b1 + a1 * b0) + 'i'\n\n def _getReala0ndImag(self, s: str) -> tuple:\n return int(s[:s.index('+')]), int(s[s.index('+') + 1:-1])\n", | |
| "title": "537. Complex Number Multiplication", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 568 | |
| }, | |
| { | |
| "code": "class Solution:\n def convertBST(self, root: TreeNode | None) -> TreeNode | None:\n prefix = 0\n\n def reversedInorder(root: TreeNode | None) -> None:\n nonlocal prefix\n if not root:\n return\n\n reversedInorder(root.right)\n prefix += root.val\n root.val = prefix\n reversedInorder(root.left)\n\n reversedInorder(root)\n return root\n", | |
| "title": "538. Convert BST to Greater Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 569 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMinDifference(self, timePoints: list[str]) -> int:\n ans = 24 * 60\n nums = sorted([int(timePoint[:2]) * 60 + int(timePoint[3:])\n for timePoint in timePoints])\n\n for a, b in zip(nums, nums[1:]):\n ans = min(ans, b - a)\n\n return min(ans, 24 * 60 - nums[-1] + nums[0])\n", | |
| "title": "539. Minimum Time Difference", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 570 | |
| }, | |
| { | |
| "code": "class Solution:\n def singleNonDuplicate(self, nums: list[int]) -> int:\n l = 0\n r = len(nums) - 1\n\n while l < r:\n m = (l + r) // 2\n if m % 2 == 1:\n m -= 1\n if nums[m] == nums[m + 1]:\n l = m + 2\n else:\n r = m\n\n return nums[l]\n", | |
| "title": "540. Single Element in a Sorted Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 571 | |
| }, | |
| { | |
| "code": "class Solution:\n def reverseStr(self, s: str, k: int) -> str:\n return s[:k][::-1] + s[k:2 * k] + self.reverseStr(s[2 * k:], k) if s else \"\"\n", | |
| "title": "541. Reverse String II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 572 | |
| }, | |
| { | |
| "code": "class Solution:\n def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(mat)\n n = len(mat[0])\n q = collections.deque()\n\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 0:\n q.append((i, j))\n else:\n mat[i][j] = math.inf\n\n while q:\n i, j = q.popleft()\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if mat[x][y] <= mat[i][j] + 1:\n continue\n q.append((x, y))\n mat[x][y] = mat[i][j] + 1\n\n return mat\n", | |
| "title": "542. 01 Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 573 | |
| }, | |
| { | |
| "code": "class Solution:\n def diameterOfBinaryTree(self, root: TreeNode | None) -> int:\n ans = 0\n\n def maxDepth(root: TreeNode | None) -> int:\n nonlocal ans\n if not root:\n return 0\n\n l = maxDepth(root.left)\n r = maxDepth(root.right)\n ans = max(ans, l + r)\n return 1 + max(l, r)\n\n maxDepth(root)\n return ans\n", | |
| "title": "543. Diameter of Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 574 | |
| }, | |
| { | |
| "code": "class Solution:\n def findContestMatch(self, n: int) -> str:\n matches = [str(i + 1) for i in range(n)]\n\n while n > 1:\n for i in range(n // 2):\n matches[i] = '(' + matches[i] + ',' + matches[n - 1 - i] + ')'\n n //= 2\n\n return matches[0]\n", | |
| "title": "544. Output Contest Matches", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 575 | |
| }, | |
| { | |
| "code": "class Solution:\n def boundaryOfBinaryTree(self, root: TreeNode | None) -> list[int]:\n if not root:\n return []\n\n ans = [root.val]\n\n def dfs(root: TreeNode | None, lb: bool, rb: bool):\n \"\"\"\n 1. root.left is left boundary if root is left boundary.\n root.right if left boundary if root.left is None.\n 2. Same applys for right boundary.\n 3. If root is left boundary, add it before 2 children - preorder.\n If root is right boundary, add it after 2 children - postorder.\n 4. A leaf that is neighter left/right boundary belongs to the bottom.\n \"\"\"\n if not root:\n return\n if lb:\n ans.append(root.val)\n if not lb and not rb and not root.left and not root.right:\n ans.append(root.val)\n\n dfs(root.left, lb, rb and not root.right)\n dfs(root.right, lb and not root.left, rb)\n if rb:\n ans.append(root.val)\n\n dfs(root.left, True, False)\n dfs(root.right, False, True)\n return ans\n", | |
| "title": "545. Boundary of Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 576 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeBoxes(self, boxes: list[int]) -> int:\n @functools.lru_cache(None)\n def dp(i: int, j: int, k: int) -> int:\n \"\"\"\n Returns the maximum score of boxes[i..j] if k boxes equal to boxes[j].\n \"\"\"\n if i > j:\n return 0\n\n r = j\n sameBoxes = k + 1\n while r > 0 and boxes[r - 1] == boxes[r]:\n r -= 1\n sameBoxes += 1\n res = dp(i, r - 1, 0) + sameBoxes * sameBoxes\n\n for p in range(i, r):\n if boxes[p] == boxes[r]:\n res = max(res, dp(i, p, sameBoxes) + dp(p + 1, r - 1, 0))\n\n return res\n\n return dp(0, len(boxes) - 1, 0)\n", | |
| "title": "546. Remove Boxes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 577 | |
| }, | |
| { | |
| "code": "class UnionFind:\n def __init__(self, n: int):\n self.count = n\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n self.count -= 1\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def findCircleNum(self, isConnected: list[list[int]]) -> int:\n n = len(isConnected)\n uf = UnionFind(n)\n\n for i in range(n):\n for j in range(i, n):\n if isConnected[i][j] == 1:\n uf.unionByRank(i, j)\n\n return uf.count\n", | |
| "title": "547. Friend Circles", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 578 | |
| }, | |
| { | |
| "code": "WITH\n Players AS (\n SELECT player_id, MIN(event_date) AS first_login\n FROM Activity\n GROUP BY 1\n )\nSELECT ROUND(\n COUNT(Players.player_id) / (\n SELECT COUNT(DISTINCT Activity.player_id)\n FROM Activity\n ),\n 2\n ) AS fraction\nFROM Players\nINNER JOIN Activity\n ON (\n Players.player_id = Activity.player_id\n AND DATEDIFF(Players.first_login, Activity.event_date) = -1)\n", | |
| "title": "550. Game Play Analysis IV", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 579 | |
| }, | |
| { | |
| "code": "class Solution:\n def checkRecord(self, s: str) -> bool:\n return s.count('A') <= 1 and 'LLL' not in s\n", | |
| "title": "551. Student Attendance Record I", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 580 | |
| }, | |
| { | |
| "code": "class Solution:\n def checkRecord(self, n: int) -> int:\n MOD = 1_000_000_007\n # dp[i][j] := the length so far with i A's and the last letters are j L's\n dp = [[0] * 3 for _ in range(2)]\n dp[0][0] = 1\n\n for _ in range(n):\n prev = [A[:] for A in dp]\n\n # Append a P.\n dp[0][0] = (prev[0][0] + prev[0][1] + prev[0][2]) % MOD\n\n # Append an L.\n dp[0][1] = prev[0][0]\n\n # Append an L.\n dp[0][2] = prev[0][1]\n\n # Append an A or append a P.\n dp[1][0] = (prev[0][0] + prev[0][1] + prev[0][2] +\n prev[1][0] + prev[1][1] + prev[1][2]) % MOD\n\n # Append an L.\n dp[1][1] = prev[1][0]\n\n # Append an L.\n dp[1][2] = prev[1][1]\n\n return (sum(dp[0]) + sum(dp[1])) % MOD\n", | |
| "title": "552. Student Attendance Record II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 581 | |
| }, | |
| { | |
| "code": "class Solution:\n def optimalDivision(self, nums: list[int]) -> str:\n ans = str(nums[0])\n\n if len(nums) == 1:\n return ans\n if len(nums) == 2:\n return ans + '/' + str(nums[1])\n\n ans += '/(' + str(nums[1])\n for i in range(2, len(nums)):\n ans += '/' + str(nums[i])\n ans += ')'\n return ans\n", | |
| "title": "553. Optimal Division", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 582 | |
| }, | |
| { | |
| "code": "class Solution:\n def leastBricks(self, wall: list[list[int]]) -> int:\n maxFreq = 0\n count = collections.defaultdict(int)\n\n for row in wall:\n prefix = 0\n for i in range(len(row) - 1):\n prefix += row[i]\n count[prefix] += 1\n maxFreq = max(maxFreq, count[prefix])\n\n return len(wall) - maxFreq\n", | |
| "title": "554. Brick Wall", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 583 | |
| }, | |
| { | |
| "code": "class Solution:\n def splitLoopedString(self, strs: list[str]) -> str:\n ans = ''\n sortedStrs = [max(s, s[::-1]) for s in strs]\n\n for i, sortedStr in enumerate(sortedStrs):\n for s in (sortedStr, sortedStr[::-1]):\n for j in range(len(s) + 1):\n ans = max(\n ans, s[j:] + ''.join(sortedStrs[i + 1:] + sortedStrs[:i]) + s[:j])\n\n return ans\n", | |
| "title": "555. Split Concatenated Strings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 584 | |
| }, | |
| { | |
| "code": "class Solution:\n def nextGreaterElement(self, n: int) -> int:\n def nextPermutation(s: list[str]) -> str:\n i = len(s) - 2\n while i >= 0:\n if s[i] < s[i + 1]:\n break\n i -= 1\n\n if i >= 0:\n for j in range(len(s) - 1, i, -1):\n if s[j] > s[i]:\n break\n s[i], s[j] = s[j], s[i]\n\n reverse(s, i + 1, len(s) - 1)\n return ''.join(s)\n\n def reverse(s: list[str], l: int, r: int):\n while l < r:\n s[l], s[r] = s[r], s[l]\n l += 1\n r -= 1\n\n s = nextPermutation(list(str(n)))\n ans = int(s)\n return -1 if ans > 2**31 - 1 or ans <= n else ans\n", | |
| "title": "556. Next Greater Element III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 585 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxDepth(self, root: 'Node') -> int:\n if not root:\n return 0\n if not root.children:\n return 1\n return 1 + max(self.maxDepth(child) for child in root.children)\n", | |
| "title": "559. Maximum Depth of N-ary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 586 | |
| }, | |
| { | |
| "code": "class Solution:\n def subarraySum(self, nums: list[int], k: int) -> int:\n ans = 0\n prefix = 0\n count = collections.Counter({0: 1})\n\n for num in nums:\n prefix += num\n ans += count[prefix - k]\n count[prefix] += 1\n\n return ans\n", | |
| "title": "560. Subarray Sum Equals K", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 587 | |
| }, | |
| { | |
| "code": "class Solution:\n def arrayPairSum(self, nums: list[int]) -> int:\n return sum(sorted(nums)[::2])\n", | |
| "title": "561. Array Partition I", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 588 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestLine(self, mat: list[list[int]]) -> int:\n m = len(mat)\n n = len(mat[0])\n ans = 0\n # dp[i][j][0] := horizontal\n # dp[i][j][1] := vertical\n # dp[i][j][2] := diagonal\n # dp[i][j][3] := anti-diagonal\n dp = [[[0] * 4 for j in range(n)] for _ in range(m)]\n\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 1:\n dp[i][j][0] = dp[i][j - 1][0] + 1 if j > 0 else 1\n dp[i][j][1] = dp[i - 1][j][1] + 1 if i > 0 else 1\n dp[i][j][2] = dp[i - 1][j - 1][2] + 1 if i > 0 and j > 0 else 1\n dp[i][j][3] = dp[i - 1][j + 1][3] + 1 if i > 0 and j < n - 1 else 1\n ans = max(ans, max(dp[i][j]))\n\n return ans\n", | |
| "title": "562. Longest Line of Consecutive One in Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 589 | |
| }, | |
| { | |
| "code": "class Solution:\n def findTilt(self, root: TreeNode | None) -> int:\n ans = 0\n\n def summ(root: TreeNode | None) -> None:\n nonlocal ans\n if not root:\n return 0\n\n l = summ(root.left)\n r = summ(root.right)\n ans += abs(l - r)\n return root.val + l + r\n\n summ(root)\n return ans\n", | |
| "title": "563. Binary Tree Tilt", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 590 | |
| }, | |
| { | |
| "code": "class Solution:\n def nearestPalindromic(self, n: str) -> str:\n prevPalindrome, nextPalindrome = self._getPalindromes(n)\n return (str(prevPalindrome)\n if abs(prevPalindrome - int(n)) <= abs(nextPalindrome - int(n))\n else str(nextPalindrome))\n\n def _getPalindromes(self, s: str) -> tuple[str, str]:\n \"\"\"Returns the two closest palindromes to the given number.\"\"\"\n num = int(s)\n sz = len(s)\n palindromes = []\n half = s[0:(sz + 1) // 2]\n reversedHalf = half[:sz // 2][::-1]\n candidate = int(half + reversedHalf)\n\n if candidate < num:\n palindromes.append(candidate)\n else:\n prevHalf = str(int(half) - 1)\n reversedPrevHalf = prevHalf[:sz // 2][::-1]\n if sz % 2 == 0 and int(prevHalf) == 0:\n palindromes.append(9)\n elif sz % 2 == 0 and prevHalf == '9':\n palindromes.append(int(prevHalf + '9' + reversedPrevHalf))\n else:\n palindromes.append(int(prevHalf + reversedPrevHalf))\n\n if candidate > num:\n palindromes.append(candidate)\n else:\n nextHalf = str(int(half) + 1)\n reversedNextHalf = nextHalf[:sz // 2][::-1]\n palindromes.append(int(nextHalf + reversedNextHalf))\n\n return palindromes\n", | |
| "title": "564. Find the Closest Palindrome", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 591 | |
| }, | |
| { | |
| "code": "class Solution:\n def arrayNesting(self, nums: list[int]) -> int:\n ans = 0\n\n for num in nums:\n if num == -1:\n continue\n index = num\n count = 0\n while nums[index] != -1:\n cache = index\n index = nums[index]\n nums[cache] = -1\n count += 1\n ans = max(ans, count)\n\n return ans\n", | |
| "title": "565. Array Nesting", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 592 | |
| }, | |
| { | |
| "code": "class Solution:\n def matrixReshape(self, nums: list[list[int]],\n r: int, c: int) -> list[list[int]]:\n if nums == [] or r * c != len(nums) * len(nums[0]):\n return nums\n\n ans = [[0 for j in range(c)] for i in range(r)]\n k = 0\n\n for row in nums:\n for num in row:\n ans[k // c][k % c] = num\n k += 1\n\n return ans\n", | |
| "title": "566. Reshape the Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 593 | |
| }, | |
| { | |
| "code": "class Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n count = collections.Counter(s1)\n required = len(s1)\n\n for r, c in enumerate(s2):\n count[c] -= 1\n if count[c] >= 0:\n required -= 1\n if r >= len(s1): # The window is oversized.\n count[s2[r - len(s1)]] += 1\n if count[s2[r - len(s1)]] > 0:\n required += 1\n if required == 0:\n return True\n\n return False\n", | |
| "title": "567. Permutation in String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 594 | |
| }, | |
| { | |
| "code": "WITH\n EmployeesWithRowNumberInCompany AS (\n SELECT\n id,\n company,\n salary,\n ROW_NUMBER() OVER(\n PARTITION BY company\n ORDER BY salary\n ) AS `row_number`,\n COUNT(*) OVER(PARTITION BY company) AS `count`\n FROM Employee\n )\nSELECT id, company, salary\nFROM EmployeesWithRowNumberInCompany\nWHERE\n `row_number` >= `count` / 2\n AND `row_number` <= `count` / 2 + 1;\n", | |
| "title": "569. Median Employee Salary", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 595 | |
| }, | |
| { | |
| "code": "SELECT Manager.name\nFROM Employee\nINNER JOIN Employee AS Manager\n ON (Employee.managerId = Manager.id)\nGROUP BY Manager.id\nHAVING COUNT(*) >= 5;\n", | |
| "title": "570. Managers with at Least 5 Direct Reports", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 596 | |
| }, | |
| { | |
| "code": "WITH\n NumbersMetadata AS (\n SELECT\n *,\n SUM(frequency) OVER(ORDER BY num) AS running_frequency,\n (SUM(frequency) OVER()) / 2 AS median_frequency\n FROM Numbers\n )\nSELECT AVG(num) AS median\nFROM NumbersMetadata\nWHERE median_frequency BETWEEN running_frequency - frequency AND running_frequency;\n", | |
| "title": "571. Find Median Given Frequency of Numbers", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 597 | |
| }, | |
| { | |
| "code": "class Solution:\n def minDistance(\n self,\n height: int,\n width: int,\n tree: list[int],\n squirrel: list[int],\n nuts: list[list[int]],\n ) -> int:\n def dist(a: list[int], b: list[int]) -> int:\n return abs(a[0] - b[0]) + abs(a[1] - b[1])\n\n totDist = sum(dist(nut, tree) for nut in nuts) * 2\n maxSave = max(dist(nut, tree) - dist(nut, squirrel) for nut in nuts)\n return totDist - maxSave\n", | |
| "title": "573. Squirrel Simulation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 598 | |
| }, | |
| { | |
| "code": "SELECT Candidate.name\nFROM Candidate\nINNER JOIN Vote\n ON (Candidate.id = Vote.candidateId)\nGROUP BY Candidate.id\nORDER BY COUNT(*) DESC\nLIMIT 1;\n", | |
| "title": "574. Winning Candidate", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 599 | |
| }, | |
| { | |
| "code": "class Solution:\n def distributeCandies(self, candies: list[int]) -> int:\n return min(len(candies) // 2, len(set(candies)))\n", | |
| "title": "575. Distribute Candies", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 600 | |
| }, | |
| { | |
| "code": "class Solution:\n def findPaths(\n self,\n m: int,\n n: int,\n maxMove: int,\n startRow: int,\n startColumn: int,\n ) -> int:\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n MOD = 1_000_000_007\n ans = 0\n # dp[i][j] := the number of paths to move the ball (i, j) out-of-bounds\n dp = [[0] * n for _ in range(m)]\n dp[startRow][startColumn] = 1\n\n for _ in range(maxMove):\n newDp = [[0] * n for _ in range(m)]\n for i in range(m):\n for j in range(n):\n if dp[i][j] > 0:\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n ans = (ans + dp[i][j]) % MOD\n else:\n newDp[x][y] = (newDp[x][y] + dp[i][j]) % MOD\n dp = newDp\n\n return ans\n", | |
| "title": "576. Out of Boundary Paths", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 601 | |
| }, | |
| { | |
| "code": "SELECT Employee.name, Bonus.bonus\nFROM Employee\nLEFT JOIN Bonus\n USING (empId)\nWHERE IFNULL(Bonus.bonus, 0) < 1000;\n", | |
| "title": "577. Employee Bonus", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 602 | |
| }, | |
| { | |
| "code": "SELECT question_id AS survey_log\nFROM SurveyLog\nGROUP BY 1\nORDER BY\n COUNT(answer_id) / COUNT(*) DESC,\n question_id ASC\nLIMIT 1;\n", | |
| "title": "578. Get Highest Answer Rate Question", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 603 | |
| }, | |
| { | |
| "code": "WITH\n CurrMonth AS (\n SELECT\n *,\n MAX(month) OVER(PARTITION BY id) AS max_month\n FROM Employee\n )\nSELECT\n CurrMonth.id,\n CurrMonth.month,\n SUM(PrevMonth.salary) AS salary\nFROM CurrMonth\nINNER JOIN Employee AS PrevMonth\n ON (CurrMonth.id = PrevMonth.id AND CurrMonth.month - PrevMonth.month BETWEEN 0 AND 2)\nWHERE CurrMonth.month != CurrMonth.max_month\nGROUP BY 1, 2\nORDER BY 1, 2 DESC;\n", | |
| "title": "579. Find Cumulative Salary of an Employee", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 604 | |
| }, | |
| { | |
| "code": "SELECT\n Department.dept_name,\n COUNT(Student.student_id) AS student_number\nFROM Department\nLEFT JOIN Student\n USING (dept_id)\nGROUP BY 1\nORDER BY 2 DESC, 1;\n", | |
| "title": "580. Count Student Number in Departments", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 605 | |
| }, | |
| { | |
| "code": "class Solution:\n def findUnsortedSubarray(self, nums: list[int]) -> int:\n mn = math.inf\n mx = -math.inf\n flag = False\n\n for i in range(1, len(nums)):\n if nums[i] < nums[i - 1]:\n flag = True\n if flag:\n mn = min(mn, nums[i])\n\n flag = False\n\n for i in reversed(range(len(nums) - 1)):\n if nums[i] > nums[i + 1]:\n flag = True\n if flag:\n mx = max(mx, nums[i])\n\n for l in range(len(nums)):\n if nums[l] > mn:\n break\n\n for r, num in reversed(list(enumerate(nums))):\n if num < mx:\n break\n\n return 0 if l >= r else r - l + 1\n", | |
| "title": "581. Shortest Unsorted Continuous Subarray", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 606 | |
| }, | |
| { | |
| "code": "class Solution:\n def killProcess(\n self,\n pid: list[int],\n ppid: list[int],\n kill: int,\n ) -> list[int]:\n ans = []\n tree = collections.defaultdict(list)\n\n for v, u in zip(pid, ppid):\n if u == 0:\n continue\n tree[u].append(v)\n\n def dfs(u: int) -> None:\n ans.append(u)\n for v in tree.get(u, []):\n dfs(v)\n\n dfs(kill)\n return ans\n", | |
| "title": "582. Kill Process", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 607 | |
| }, | |
| { | |
| "code": "class Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n k = self._lcs(word1, word2)\n return (len(word1) - k) + (len(word2) - k)\n\n def _lcs(self, a: str, b: str) -> int:\n m = len(a)\n n = len(b)\n # dp[i][j] := the length of LCS(a[0..i), b[0..j))\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if a[i - 1] == b[j - 1]:\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\n return dp[m][n]\n", | |
| "title": "583. Delete Operation for Two Strings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 608 | |
| }, | |
| { | |
| "code": "SELECT name\nFROM Customer\nWHERE referee_id IS NULL OR referee_id != 2;\n", | |
| "title": "584. Find Customer Referee", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 609 | |
| }, | |
| { | |
| "code": "WITH\n InsuranceWithCounts AS (\n SELECT\n tiv_2016,\n COUNT(*) OVER(PARTITION by tiv_2015) AS tiv_2015_count,\n COUNT(*) OVER(PARTITION by lat, lon) AS city_count\n FROM Insurance\n )\nSELECT ROUND(SUM(tiv_2016), 2) AS tiv_2016\nFROM InsuranceWithCounts\nWHERE tiv_2015_count > 1\n AND city_count = 1;\n", | |
| "title": "585. Investments in 2016", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 610 | |
| }, | |
| { | |
| "code": "SELECT customer_number\nFROM Orders\nGROUP BY 1\nORDER BY COUNT(*) DESC\nLIMIT 1;\n", | |
| "title": "586. Customer Placing the Largest Number of Orders", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 611 | |
| }, | |
| { | |
| "code": "class Solution:\n def outerTrees(self, trees: list[list[int]]) -> list[list[int]]:\n hull = []\n\n trees.sort(key=lambda x: (x[0], x[1]))\n\n def cross(p: list[int], q: list[int], r: list[int]) -> int:\n return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])\n\n # Build the lower hull: left-to-right scan.\n for tree in trees:\n while len(hull) > 1 and cross(hull[-1], hull[-2], tree) > 0:\n hull.pop()\n hull.append(tuple(tree))\n hull.pop()\n\n # Build the upper hull: right-to-left scan.\n for tree in reversed(trees):\n while len(hull) > 1 and cross(hull[-1], hull[-2], tree) > 0:\n hull.pop()\n hull.append(tuple(tree))\n\n # Remove the redundant elements from the stack.\n return list(set(hull))\n", | |
| "title": "587. Erect the Fence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 612 | |
| }, | |
| { | |
| "code": "class Solution:\n def isValid(self, code: str) -> bool:\n if code[0] != '<' or code[-1] != '>':\n return False\n\n containsTag = False\n stack = []\n\n def isValidCdata(s: str) -> bool:\n return s.find('[CDATA[') == 0\n\n def isValidTagName(tagName: str, isEndTag: bool) -> bool:\n nonlocal containsTag\n if not tagName or len(tagName) > 9:\n return False\n if any(not c.isupper() for c in tagName):\n return False\n\n if isEndTag:\n return stack and stack.pop() == tagName\n\n containsTag = True\n stack.append(tagName)\n return True\n\n i = 0\n while i < len(code):\n if not stack and containsTag:\n return False\n if code[i] == '<':\n # It's inside a tag, so check if it's a cdata.\n if stack and code[i + 1] == '!':\n closeIndex = code.find(']]>', i + 2)\n if closeIndex == -1 or not isValidCdata(code[i + 2:closeIndex]):\n return False\n elif code[i + 1] == '/': # the end tag\n closeIndex = code.find('>', i + 2)\n if closeIndex == -1 or not isValidTagName(\n code[i + 2: closeIndex],\n True):\n return False\n else: # the start tag\n closeIndex = code.find('>', i + 1)\n if closeIndex == -1 or not isValidTagName(\n code[i + 1: closeIndex],\n False):\n return False\n i = closeIndex\n i += 1\n\n return not stack and containsTag\n", | |
| "title": "591. Tag Validator", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 613 | |
| }, | |
| { | |
| "code": "class Solution:\n def fractionAddition(self, expression: str) -> str:\n ints = list(map(int, re.findall('[+-]?[0-9]+', expression)))\n A = 0\n B = 1\n\n for a, b in zip(ints[::2], ints[1::2]):\n A = A * b + a * B\n B *= b\n g = math.gcd(A, B)\n A //= g\n B //= g\n\n return str(A) + '/' + str(B)\n", | |
| "title": "592. Fraction Addition and Subtraction", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 614 | |
| }, | |
| { | |
| "code": "class Solution:\n def validSquare(\n self,\n p1: list[int],\n p2: list[int],\n p3: list[int],\n p4: list[int],\n ) -> bool:\n def dist(p1: list[int], p2: list[int]) -> int:\n return (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2\n\n distSet = set([dist(*pair)\n for pair in list(\n itertools.combinations([p1, p2, p3, p4], 2))])\n return 0 not in distSet and len(distSet) == 2\n", | |
| "title": "593. Valid Square", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 615 | |
| }, | |
| { | |
| "code": "class Solution:\n def findLHS(self, nums: list[int]) -> int:\n ans = 0\n count = collections.Counter(nums)\n\n for num, freq in count.items():\n if num + 1 in count:\n ans = max(ans, freq + count[num + 1])\n\n return ans\n", | |
| "title": "594. Longest Harmonious Subsequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 616 | |
| }, | |
| { | |
| "code": "SELECT name, population, area\nFROM World\nWHERE area >= 3000000 OR population >= 25000000;\n", | |
| "title": "595. Big Countries", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 617 | |
| }, | |
| { | |
| "code": "SELECT class\nFROM Courses\nGROUP BY 1\nHAVING COUNT(*) >= 5;\n", | |
| "title": "596. Classes More Than 5 Students", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 618 | |
| }, | |
| { | |
| "code": "WITH\n Request AS (\n SELECT COUNT(DISTINCT sender_id, send_to_id) AS `count`\n FROM FriendRequest\n ),\n Accepted AS (\n SELECT IFNULL(COUNT(DISTINCT requester_id, accepter_id), 0) AS `count`\n FROM RequestAccepted\n )\nSELECT IF(\n `Request`.count = 0,\n 0,\n ROUND(Accepted.`count` / Request.`count`, 2)\n ) AS accept_rate\nFROM Request, Accepted;\n", | |
| "title": "597. Friend Requests I: Overall Acceptance Rate", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 619 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxCount(self, m: int, n: int, ops: list[list[int]]) -> int:\n minY = m\n minX = n\n\n for y, x in ops:\n minY = min(minY, y)\n minX = min(minX, x)\n\n return minX * minY\n", | |
| "title": "598. Range Addition II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 620 | |
| }, | |
| { | |
| "code": "class Solution:\n def findRestaurant(self, list1: list[str], list2: list[str]) -> list[str]:\n ans = []\n restaurantToIndex = {restaurant: i for i,\n restaurant in enumerate(list1)}\n minSum = math.inf\n\n for i, restaurant in enumerate(list2):\n if restaurant in restaurantToIndex:\n summ = restaurantToIndex[restaurant] + i\n if summ < minSum:\n ans.clear()\n if summ <= minSum:\n ans.append(restaurant)\n minSum = summ\n\n return ans\n", | |
| "title": "599. Minimum Index Sum of Two Lists", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 621 | |
| }, | |
| { | |
| "code": "WITH\n StadiumWithGroupId AS (\n SELECT\n id,\n visit_date,\n people,\n id - ROW_NUMBER() OVER(ORDER BY id) AS group_id\n FROM Stadium\n WHERE people >= 100\n )\nSELECT id, visit_date, people\nFROM StadiumWithGroupId\nWHERE group_id IN (\n SELECT group_id\n FROM StadiumWithGroupId\n GROUP BY group_id\n HAVING COUNT(*) >= 3\n )\nORDER BY visit_date;\n", | |
| "title": "601. Human Traffic of Stadium", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 622 | |
| }, | |
| { | |
| "code": "WITH\n AllIds AS (\n SELECT requester_id AS id FROM RequestAccepted\n UNION ALL\n SELECT accepter_id FROM RequestAccepted\n )\nSELECT\n id,\n COUNT(*) AS num\nFROM AllIds\nGROUP BY 1\nORDER BY 2 DESC\nLIMIT 1;\n", | |
| "title": "602. Friend Requests II: Who Has the Most Friends", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 623 | |
| }, | |
| { | |
| "code": "WITH CinemaNeighbors AS (\n SELECT\n *,\n LAG(free) OVER(ORDER BY seat_id) AS prev_free,\n LEAD(free) OVER(ORDER BY seat_id) AS next_free\n FROM Cinema\n)\nSELECT seat_id\nFROM CinemaNeighbors\nWHERE free = 1\n AND (prev_free = 1 OR next_free = 1)\nORDER BY 1;\n", | |
| "title": "603. Consecutive Available Seats", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 624 | |
| }, | |
| { | |
| "code": "class StringIterator:\n def __init__(self, compressedString: str):\n self.q = collections.deque() # (currentChar, num)\n\n i = 0 # compressedString's index\n while i < len(compressedString):\n c = compressedString[i]\n i += 1\n num = 0\n while i < len(compressedString) and compressedString[i].isdigit():\n num = num * 10 + int(compressedString[i])\n i += 1\n self.q.append((c, num))\n\n def next(self) -> str:\n if not self.hasNext():\n return ' '\n c, num = self.q.popleft()\n if num > 1:\n self.q.appendleft((c, num - 1))\n return c\n\n def hasNext(self) -> bool:\n return self.q\n", | |
| "title": "604. Design Compressed String Iterator", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 625 | |
| }, | |
| { | |
| "code": "class Solution:\n def canPlaceFlowers(self, flowerbed: list[int], n: int) -> bool:\n for i, flower in enumerate(flowerbed):\n if flower == 0 and (\n i == 0 or flowerbed[i - 1] == 0) and (\n i == len(flowerbed) - 1 or flowerbed[i + 1] == 0):\n flowerbed[i] = 1\n n -= 1\n if n <= 0:\n return True\n\n return False\n", | |
| "title": "605. Can Place Flowers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 626 | |
| }, | |
| { | |
| "code": "class Solution:\n def tree2str(self, t: TreeNode | None) -> str:\n def dfs(root: TreeNode | None) -> str:\n if not root:\n return ''\n if root.right:\n return str(root.val) + '(' + dfs(root.left) + ')(' + dfs(root.right) + ')'\n if root.left:\n return str(root.val) + '(' + dfs(root.left) + ')'\n return str(root.val)\n return dfs(t)\n", | |
| "title": "606. Construct String from Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 627 | |
| }, | |
| { | |
| "code": "SELECT SalesPerson.name\nFROM Orders\nINNER JOIN Company\n ON (Orders.com_id = Company.com_id AND Company.name = 'RED')\nRIGHT JOIN SalesPerson\n USING (sales_id)\nWHERE Orders.sales_id IS NULL;\n", | |
| "title": "607. Sales Person", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 628 | |
| }, | |
| { | |
| "code": "SELECT DISTINCT Parent.id,\n (\n CASE\n WHEN Parent.p_id IS NULL THEN 'Root'\n WHEN Parent.p_id IS NOT NULL AND Child.p_id IS NOT NULL THEN 'Inner'\n WHEN Parent.p_id IS NOT NULL AND Child.p_id IS NULL THEN 'Leaf'\n END\n ) AS type\nFROM Tree AS Parent\nLEFT JOIN Tree AS Child\n ON (Parent.id = Child.p_id);\n", | |
| "title": "608. Tree Node", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 629 | |
| }, | |
| { | |
| "code": "class Solution:\n def findDuplicate(self, paths: list[str]) -> list[list[str]]:\n contentToPathFiles = collections.defaultdict(list)\n\n for path in paths:\n words = path.split(' ')\n rootPath = words[0] # \"root/d1/d2/.../dm\"\n for fileAndContent in words[1:]: # \"fn.txt(fn_content)\"\n l = fileAndContent.find('(')\n r = fileAndContent.find(')')\n # \"fn.txt\"\n file = fileAndContent[:l]\n # \"fn_content\"\n content = fileAndContent[l + 1:r]\n # \"root/d1/d2/.../dm/fn.txt\"\n filePath = rootPath + '/' + file\n contentToPathFiles[content].append(filePath)\n\n return [filePath for filePath in contentToPathFiles.values() if len(filePath) > 1]\n", | |
| "title": "609. Find Duplicate File in System", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 630 | |
| }, | |
| { | |
| "code": "SELECT\n *,\n IF(x + y > z AND x + z > y AND y + z > x, 'Yes', 'No') AS triangle\nFROM Triangle;\n", | |
| "title": "610. Triangle Judgement", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 631 | |
| }, | |
| { | |
| "code": "class Solution:\n def triangleNumber(self, nums: list[int]) -> int:\n ans = 0\n\n nums.sort()\n\n for k in range(len(nums) - 1, 1, -1):\n i = 0\n j = k - 1\n while i < j:\n if nums[i] + nums[j] > nums[k]:\n ans += j - i\n j -= 1\n else:\n i += 1\n\n return ans\n", | |
| "title": "611. Valid Triangle Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 632 | |
| }, | |
| { | |
| "code": "SELECT ROUND(\n MIN(SQRT(POW(P1.x - P2.x, 2) + POW(P1.y - P2.y, 2))),\n 2\n ) AS shortest\nFROM Point2D AS P1\nLEFT JOIN Point2D AS P2\n ON (P1.x, P1.y) != (P2.x, P2.y);\n", | |
| "title": "612. Shortest Distance in a Plane", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 633 | |
| }, | |
| { | |
| "code": "SELECT MIN(P1.x - P2.x) AS shortest\nFROM Point AS P1, Point AS P2\nWHERE P1.x > P2.x;\n", | |
| "title": "613. Shortest Distance in a Line", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 634 | |
| }, | |
| { | |
| "code": "SELECT\n Follower.follower,\n COUNT(DISTINCT Followee.follower) AS num\nFROM Follow AS Follower\nINNER JOIN Follow AS Followee\n ON (Follower.follower = Followee.followee)\nGROUP BY 1\nORDER BY 1;\n", | |
| "title": "614. Second Degree Follower", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 635 | |
| }, | |
| { | |
| "code": "WITH\n AvgSalary AS (\n SELECT DISTINCT\n DATE_FORMAT(pay_date, '%Y-%m') AS pay_month,\n Employee.department_id,\n AVG(amount) OVER(\n PARTITION BY Employee.department_id,\n Salary.pay_date\n ) AS department_avg_salary,\n AVG(amount) OVER(PARTITION BY Salary.pay_date) AS company_avg_salary\n FROM Salary\n INNER JOIN Employee\n USING (employee_id)\n )\nSELECT DISTINCT\n pay_month,\n department_id,\n (\n CASE\n WHEN department_avg_salary > company_avg_salary THEN 'higher'\n WHEN department_avg_salary < company_avg_salary THEN 'lower'\n ELSE 'same'\n END\n ) AS comparison\nFROM AvgSalary;\n", | |
| "title": "615. Average Salary: Departments VS Company", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 636 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: dict[str, TrieNode] = {}\n self.isWord = False\n\n\nclass Solution:\n def addBoldTag(self, s: str, words: list[str]) -> str:\n n = len(s)\n ans = []\n # bold[i] := True if s[i] should be bolded\n bold = [0] * n\n root = TrieNode()\n\n def insert(word: str) -> None:\n node = root\n for c in word:\n node = node.children.setdefault(c, TrieNode())\n node.isWord = True\n\n def find(s: str, i: int) -> int:\n node = root\n ans = -1\n for j in range(i, len(s)):\n if s[j] not in node.children:\n node.children[s[j]] = TrieNode()\n node = node.children[s[j]]\n if node.isWord:\n ans = j\n return ans\n\n for word in words:\n insert(word)\n\n boldEnd = -1 # `s[i..boldEnd]` should be bolded.\n for i in range(n):\n boldEnd = max(boldEnd, find(s, i))\n bold[i] = boldEnd >= i\n\n # Construct the with bold tags\n i = 0\n while i < n:\n if bold[i]:\n j = i\n while j < n and bold[j]:\n j += 1\n # `s[i..j)` should be bolded.\n ans.append('<b>' + s[i:j] + '</b>')\n i = j\n else:\n ans.append(s[i])\n i += 1\n\n return ''.join(ans)\n", | |
| "title": "616. Add Bold Tag in String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 637 | |
| }, | |
| { | |
| "code": "class Solution:\n def mergeTrees(\n self,\n root1: TreeNode | None,\n root2: TreeNode | None,\n ) -> TreeNode | None:\n if not root1 and not root2:\n return None\n val = (root1.val if root1 else 0) + (root2.val if root2 else 0)\n root = TreeNode(val)\n root.left = self.mergeTrees(root1.left if root1 else None,\n root2.left if root2 else None)\n root.right = self.mergeTrees(root1.right if root1 else None,\n root2.right if root2 else None)\n return root\n", | |
| "title": "617. Merge Two Binary Trees", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 638 | |
| }, | |
| { | |
| "code": "WITH\n StudentWithIdInContinent AS (\n SELECT\n *,\n ROW_NUMBER() OVER(PARTITION BY continent ORDER BY name) AS id\n FROM Student\n )\nSELECT\n MAX(CASE WHEN continent = 'America' THEN name END) AS America,\n MAX(CASE WHEN continent = 'Asia' THEN name END) AS Asia,\n MAX(CASE WHEN continent = 'Europe' THEN name END) AS Europe,\n id\nFROM StudentWithIdInContinent\nGROUP BY id;\n", | |
| "title": "618. Students Report By Geography", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 639 | |
| }, | |
| { | |
| "code": "WITH\n UniqueNumbers AS (\n SELECT num\n FROM MyNumbers\n GROUP BY 1\n HAVING COUNT(num) = 1\n )\nSELECT MAX(num) AS num\nFROM UniqueNumbers;\n", | |
| "title": "619. Biggest Single Number", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 640 | |
| }, | |
| { | |
| "code": "SELECT *\nFROM Cinema\nWHERE\n MOD(id, 2) = 1\n AND description != 'boring'\nORDER BY rating DESC;\n", | |
| "title": "620. Not Boring Movies", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 641 | |
| }, | |
| { | |
| "code": "class Solution:\n def leastInterval(self, tasks: list[str], n: int) -> int:\n count = collections.Counter(tasks)\n maxFreq = max(count.values())\n # Put the most frequent task in the slot first.\n maxFreqTaskOccupy = (maxFreq - 1) * (n + 1)\n # Get the number of tasks with same frequency as maxFreq, we'll append them after the\n # `maxFreqTaskOccupy`.\n nMaxFreq = sum(value == maxFreq for value in count.values())\n # max(\n # the most frequent task is frequent enough to force some idle slots,\n # the most frequent task is not frequent enough to force idle slots\n # )\n return max(maxFreqTaskOccupy + nMaxFreq, len(tasks))\n", | |
| "title": "621. Task Scheduler", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 642 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxDistance(self, arrays: list[list[int]]) -> int:\n min1, index_min1 = min((A[0], i) for i, A in enumerate(arrays))\n max1, index_max1 = max((A[-1], i) for i, A in enumerate(arrays))\n if index_min1 != index_max1:\n return max1 - min1\n\n min2, index_min2 = min((A[0], i)\n for i, A in enumerate(arrays) if i != index_min1)\n max2, index_min2 = max((A[-1], i)\n for i, A in enumerate(arrays) if i != index_max1)\n return max(max1 - min2, max2 - min1)\n", | |
| "title": "624. Maximum Distance in Arrays", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 643 | |
| }, | |
| { | |
| "code": "class Solution:\n def smallestFactorization(self, num: int) -> int:\n if num == 1:\n return 1\n\n ans = 0\n base = 1\n\n for i in range(9, 1, -1):\n while num % i == 0:\n num //= i\n ans = base * i + ans\n base *= 10\n\n return ans if num == 1 and ans < 2**31 - 1 else 0\n", | |
| "title": "625. Minimum Factorization", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 644 | |
| }, | |
| { | |
| "code": "SELECT\n ROW_NUMBER() OVER(ORDER BY IF(MOD(id, 2) = 0, id - 1, id + 1)) AS id,\n student\nFROM Seat;\n", | |
| "title": "626. Exchange Seats", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 645 | |
| }, | |
| { | |
| "code": "UPDATE Salary\nSET sex = IF(sex = 'm', 'f', 'm');\n", | |
| "title": "627. Swap Salary", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 646 | |
| }, | |
| { | |
| "code": "class Solution:\n def maximumProduct(self, nums: list[int]) -> int:\n min1 = inf # the minimum\n min2 = inf # the second minimum\n max1 = -inf # the maximum\n max2 = -inf # the second maximum\n max3 = -inf # the third maximum\n\n for num in nums:\n if num <= min1:\n min2 = min1\n min1 = num\n elif num <= min2:\n min2 = num\n\n if num >= max1:\n max3 = max2\n max2 = max1\n max1 = num\n elif num >= max2:\n max3 = max2\n max2 = num\n elif num >= max3:\n max3 = num\n\n return max(max1 * min1 * min2, max1 * max2 * max3)\n", | |
| "title": "628. Maximum Product of Three Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 647 | |
| }, | |
| { | |
| "code": "class Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n MOD = 1_000_000_007\n # dp[i][j] := the number of permutations of numbers 1..i with j inverse pairs\n dp = [[0] * (k + 1) for _ in range(n + 1)]\n\n # If there's no inverse pair, the permutation is unique '123..i'\n for i in range(n + 1):\n dp[i][0] = 1\n\n for i in range(1, n + 1):\n for j in range(1, k + 1):\n dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % MOD\n if j - i >= 0:\n dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + MOD) % MOD\n\n return dp[n][k]\n", | |
| "title": "629. K Inverse Pairs Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 648 | |
| }, | |
| { | |
| "code": "class Solution:\n def scheduleCourse(self, courses: list[list[int]]) -> int:\n time = 0\n maxHeap = []\n\n for duration, lastDay in sorted(courses, key=lambda x: x[1]):\n heapq.heappush(maxHeap, -duration)\n time += duration\n # If the current course cannot be taken, check if it can be swapped with\n # a previously taken course that has a larger duration to increase the\n # time available to take upcoming courses.\n if time > lastDay:\n time += heapq.heappop(maxHeap)\n\n return len(maxHeap)\n", | |
| "title": "630. Course Schedule III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 649 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass\nclass Cell:\n val: int = 0\n posCount: dict[tuple[int, int], int] | None = None\n\n\nclass Excel:\n def __init__(self, height: int, width: str):\n self.width = ord(width) - ord('A') + 1\n self.sheet = [[Cell() for _ in range(self.width)] for _ in range(height)]\n\n def set(self, row: int, column: str, val: int) -> None:\n self._getCell(row, column).val = val\n self._getCell(row, column).posCount = {}\n\n def get(self, row: int, column: str) -> int:\n cell = self._getCell(row, column)\n if not cell.posCount:\n return cell.val\n val = 0\n for pos, count in cell.posCount.items():\n val += self.get(pos // self.width + 1, chr(pos %\n self.width + ord('A'))) * count\n return val\n\n def sum(self, row: int, column: str, numbers: list[str]) -> int:\n self._getCell(row, column).posCount = self._parse(numbers)\n return self.get(row, column)\n\n def _getCell(self, row: int, column: str) -> Cell:\n return self.sheet[row - 1][ord(column) - ord('A')]\n\n def _parse(self, numbers: list[str]) -> dict[int, int]:\n count: dict[int, int] = {}\n for s in numbers:\n startRow, startCol, endRow, endCol = self._parseRange(s)\n for i in range(startRow - 1, endRow):\n for j in range(ord(startCol) - ord('A'), ord(endCol) - ord('A') + 1):\n pos = i * self.width + j\n count[pos] = count.get(pos, 0) + 1\n return count\n\n def _parseRange(self, s: str) -> tuple[int, str, int, str]:\n if ':' not in s:\n return int(s[1:]), s[0], int(s[1:]), s[0]\n l, r = s.split(':')\n return int(l[1:]), l[0], int(r[1:]), r[0]\n", | |
| "title": "631. Design Excel Sum Formula", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 650 | |
| }, | |
| { | |
| "code": "class Solution:\n def smallestRange(self, nums: list[list[int]]) -> list[int]:\n minHeap = [(row[0], i, 0) for i, row in enumerate(nums)]\n heapq.heapify(minHeap)\n\n maxRange = max(row[0] for row in nums)\n minRange = heapq.nsmallest(1, minHeap)[0][0]\n ans = [minRange, maxRange]\n\n while len(minHeap) == len(nums):\n num, r, c = heapq.heappop(minHeap)\n if c + 1 < len(nums[r]):\n heapq.heappush(minHeap, (nums[r][c + 1], r, c + 1))\n maxRange = max(maxRange, nums[r][c + 1])\n minRange = heapq.nsmallest(1, minHeap)[0][0]\n if maxRange - minRange < ans[1] - ans[0]:\n ans[0], ans[1] = minRange, maxRange\n\n return ans\n", | |
| "title": "632. Smallest Range Covering Elements from K Lists", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 651 | |
| }, | |
| { | |
| "code": "class Solution:\n def judgeSquareSum(self, c: int) -> bool:\n l = 0\n r = math.isqrt(c)\n\n while l <= r:\n summ = l * l + r * r\n if summ == c:\n return True\n if summ < c:\n l += 1\n else:\n r -= 1\n\n return False\n", | |
| "title": "633. Sum of Square Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 652 | |
| }, | |
| { | |
| "code": "class Solution:\n def findDerangement(self, n: int) -> int:\n MOD = 1_000_000_007\n dp = [1] + [0] * n\n\n for i in range(2, n + 1):\n dp[i] = (i - 1) * (dp[i - 1] + dp[i - 2]) % MOD\n\n return dp[n]\n", | |
| "title": "634. Find the Derangement of An Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 653 | |
| }, | |
| { | |
| "code": "class LogSystem:\n def __init__(self):\n self.granularityToIndices = {'Year': 4, 'Month': 7, 'Day': 10,\n 'Hour': 13, 'Minute': 16, 'Second': 19}\n self.idAndTimestamps = []\n\n def put(self, id: int, timestamp: str) -> None:\n self.idAndTimestamps.append((id, timestamp))\n\n def retrieve(self, start: str, end: str, granularity: str) -> list[int]:\n index = self.granularityToIndices[granularity]\n s = start[:index]\n e = end[:index]\n return [id for id, timestamp in self.idAndTimestamps\n if s <= timestamp[:index] <= e]\n", | |
| "title": "635. Design Log Storage System", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 654 | |
| }, | |
| { | |
| "code": "class Solution:\n def shoppingOffers(\n self,\n price: list[int],\n special: list[list[int]],\n needs: list[int]\n ) -> int:\n def dfs(s: int) -> int:\n ans = 0\n for i, need in enumerate(needs):\n ans += need * price[i]\n\n for i in range(s, len(special)):\n offer = special[i]\n if all(offer[j] <= need for j, need in enumerate(needs)):\n # Use the special[i].\n for j in range(len(needs)):\n needs[j] -= offer[j]\n ans = min(ans, offer[-1] + dfs(i))\n # Unuse the special[i] (backtracking).\n for j in range(len(needs)):\n needs[j] += offer[j]\n\n return ans\n\n return dfs(0)\n", | |
| "title": "638. Shopping Offers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 655 | |
| }, | |
| { | |
| "code": "class Solution:\n def solveEquation(self, equation: str) -> str:\n def calculate(s: str) -> tuple:\n coefficient = 0\n constant = 0\n num = 0\n sign = 1\n\n for i, c in enumerate(s):\n if c.isdigit():\n num = num * 10 + int(c)\n elif c in '+-':\n constant += sign * num\n sign = 1 if c == '+' else -1\n num = 0\n else:\n if i > 0 and num == 0 and s[i - 1] == '0':\n continue\n coefficient += sign if num == 0 else sign * num\n num = 0\n\n return coefficient, constant + sign * num\n\n lhsEquation, rhsEquation = equation.split('=')\n lhsCoefficient, lhsConstant = calculate(lhsEquation)\n rhsCoefficient, rhsConstant = calculate(rhsEquation)\n coefficient = lhsCoefficient - rhsCoefficient\n constant = rhsConstant - lhsConstant\n\n if coefficient == 0 and constant == 0:\n return \"Infinite solutions\"\n if coefficient == 0 and constant != 0:\n return \"No solution\"\n return \"x=\" + str(constant // coefficient)\n", | |
| "title": "640. Solve the Equation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 656 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: dict[str, TrieNode] = {}\n self.s: str | None = None\n self.time = 0\n self.top3: list[TrieNode] = []\n\n def __lt__(self, other):\n if self.time == other.time:\n return self.s < other.s\n return self.time > other.time\n\n def update(self, node) -> None:\n if node not in self.top3:\n self.top3.append(node)\n self.top3.sort()\n if len(self.top3) > 3:\n self.top3.pop()\n\n\nclass AutocompleteSystem:\n def __init__(self, sentences: list[str], times: list[int]):\n self.root = TrieNode()\n self.curr = self.root\n self.s: list[str] = []\n\n for sentence, time in zip(sentences, times):\n self._insert(sentence, time)\n\n def input(self, c: str) -> list[str]:\n if c == '#':\n self._insert(''.join(self.s), 1)\n self.curr = self.root\n self.s = []\n return []\n\n self.s.append(c)\n\n if self.curr:\n self.curr = self.curr.children.get(c, None)\n if not self.curr:\n return []\n return [node.s for node in self.curr.top3]\n\n def _insert(self, sentence: str, time: int) -> None:\n node = self.root\n for c in sentence:\n node = node.children.setdefault(c, TrieNode())\n node.s = sentence\n node.time += time\n\n leaf = node\n node: TrieNode = self.root\n for c in sentence:\n node = node.children[c]\n node.update(leaf)\n", | |
| "title": "642. Design Search Autocomplete System", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 657 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMaxAverage(self, nums: list[int], k: int) -> float:\n summ = sum(nums[:k])\n ans = summ\n\n for i in range(k, len(nums)):\n summ += nums[i] - nums[i - k]\n ans = max(ans, summ)\n\n return ans / k\n", | |
| "title": "643. Maximum Average Subarray I", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 658 | |
| }, | |
| { | |
| "code": "class Solution:\n def findMaxAverage(self, nums: list[int], k: int) -> float:\n ERR = 1e-5\n l = min(nums)\n r = max(nums)\n\n def check(m: float) -> bool:\n \"\"\"\n Returns True if there's a subarray, where its length >= k and its average\n sum >= m.\n \"\"\"\n summ = 0\n prevSum = 0\n minPrevSum = 0\n\n for i, num in enumerate(nums):\n # Need to substract m for each `num` so that we can check if the sum of\n # the subarray >= 0.\n summ += num - m\n if i >= k:\n prevSum += nums[i - k] - m\n minPrevSum = min(minPrevSum, prevSum)\n if i + 1 >= k and summ >= minPrevSum:\n return True\n\n return False\n\n while r - l > ERR:\n m = (l + r) / 2\n if check(m):\n l = m\n else:\n r = m\n\n return l\n", | |
| "title": "644. Maximum Average Subarray II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 659 | |
| }, | |
| { | |
| "code": "class Solution:\n def findErrorNums(self, nums: list[int]) -> list[int]:\n for num in nums:\n if nums[abs(num) - 1] < 0:\n duplicate = abs(num)\n else:\n nums[abs(num) - 1] *= -1\n\n for i, num in enumerate(nums):\n if num > 0:\n return [duplicate, i + 1]\n", | |
| "title": "645. Set Mismatch", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 660 | |
| }, | |
| { | |
| "code": "class Solution:\n def findLongestChain(self, pairs: list[list[int]]) -> int:\n ans = 0\n prevEnd = -math.inf\n\n for s, e in sorted(pairs, key=lambda x: x[1]):\n if s > prevEnd:\n ans += 1\n prevEnd = e\n\n return ans\n", | |
| "title": "646. Maximum Length of Pair Chain", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 661 | |
| }, | |
| { | |
| "code": "class Solution:\n def countSubstrings(self, s: str) -> int:\n def extendPalindromes(l: int, r: int) -> int:\n count = 0\n\n while l >= 0 and r < len(s) and s[l] == s[r]:\n count += 1\n l -= 1\n r += 1\n\n return count\n\n ans = 0\n\n for i in range(len(s)):\n ans += extendPalindromes(i, i)\n ans += extendPalindromes(i, i + 1)\n\n return ans\n", | |
| "title": "647. Palindromic Substrings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 662 | |
| }, | |
| { | |
| "code": "class Solution:\n def __init__(self):\n self.root = {}\n\n def insert(self, word: str) -> None:\n node = self.root\n for c in word:\n if c not in node:\n node[c] = {}\n node = node[c]\n node['word'] = word\n\n def search(self, word: str) -> str:\n node = self.root\n for c in word:\n if 'word' in node:\n return node['word']\n if c not in node:\n return word\n node = node[c]\n return word\n\n def replaceWords(self, dictionary: list[str], sentence: str) -> str:\n for word in dictionary:\n self.insert(word)\n\n words = sentence.split(' ')\n return ' '.join([self.search(word) for word in words])\n", | |
| "title": "648. Replace Words", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 663 | |
| }, | |
| { | |
| "code": "class Solution:\n def minSteps(self, n: int) -> int:\n if n <= 1:\n return 0\n\n # dp[i] := the minimum steps to get i 'A's\n # Copy 'A', then paste 'A' i - 1 times.\n dp = [i for i in range(n + 1)]\n\n for i in range(2, n + 1):\n for j in range(i // 2, 2, -1):\n if i % j == 0:\n dp[i] = dp[j] + i // j # Paste dp[j] i / j times.\n break\n\n return dp[n]\n", | |
| "title": "650. 2 Keys Keyboard", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 664 | |
| }, | |
| { | |
| "code": "class Solution:\n def findDuplicateSubtrees(self, root: TreeNode | None) -> list[TreeNode | None]:\n ans = []\n count = collections.Counter()\n\n def encode(root: TreeNode | None) -> str:\n if not root:\n return ''\n\n encoded = (str(root.val) + '#' +\n encode(root.left) + '#' +\n encode(root.right))\n count[encoded] += 1\n if count[encoded] == 2:\n ans.append(root)\n return encoded\n\n encode(root)\n return ans\n", | |
| "title": "652. Find Duplicate Subtrees", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 665 | |
| }, | |
| { | |
| "code": "class BSTIterator:\n def __init__(self, root: TreeNode | None, leftToRight: bool):\n self.stack = []\n self.leftToRight = leftToRight\n self._pushUntilNone(root)\n\n def next(self) -> int:\n node = self.stack.pop()\n if self.leftToRight:\n self._pushUntilNone(node.right)\n else:\n self._pushUntilNone(node.left)\n return node.val\n\n def _pushUntilNone(self, root: TreeNode | None):\n while root:\n self.stack.append(root)\n root = root.left if self.leftToRight else root.right\n\n\nclass Solution:\n def findTarget(self, root: TreeNode | None, k: int) -> bool:\n if not root:\n return False\n\n left = BSTIterator(root, True)\n right = BSTIterator(root, False)\n\n l = left.next()\n r = right.next()\n while l < r:\n summ = l + r\n if summ == k:\n return True\n if summ < k:\n l = left.next()\n else:\n r = right.next()\n\n return False\n", | |
| "title": "653. Two Sum IV - Input is a BST", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 666 | |
| }, | |
| { | |
| "code": "class Solution:\n def constructMaximumBinaryTree(self, nums: list[int]) -> TreeNode | None:\n def build(i: int, j: int) -> TreeNode | None:\n if i > j:\n return None\n\n maxNum = max(nums[i:j + 1])\n maxIndex = nums.index(maxNum)\n\n root = TreeNode(maxNum)\n root.left = build(i, maxIndex - 1)\n root.right = build(maxIndex + 1, j)\n return root\n\n return build(0, len(nums) - 1)\n", | |
| "title": "654. Maximum Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 667 | |
| }, | |
| { | |
| "code": "class Solution:\n def printTree(self, root: TreeNode | None) -> list[list[str]]:\n def maxHeight(root: TreeNode | None) -> int:\n if not root:\n return 0\n return 1 + max(maxHeight(root.left), maxHeight(root.right))\n\n def dfs(root: TreeNode | None, row: int, left: int, right: int) -> None:\n if not root:\n return\n\n mid = (left + right) // 2\n ans[row][mid] = str(root.val)\n dfs(root.left, row + 1, left, mid - 1)\n dfs(root.right, row + 1, mid + 1, right)\n\n m = maxHeight(root)\n n = pow(2, m) - 1\n ans = [[''] * n for _ in range(m)]\n dfs(root, 0, 0, len(ans[0]) - 1)\n return ans\n", | |
| "title": "655. Print Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 668 | |
| }, | |
| { | |
| "code": "class Solution:\n def cheapestJump(self, coins: list[int], maxJump: int) -> list[int]:\n if coins[-1] == -1:\n return []\n\n n = len(coins)\n # dp[i] := the minimum cost to jump from i to n - 1\n dp = [math.inf] * n\n next = [-1] * n\n\n dp[-1] = coins[-1]\n\n for i in reversed(range(n - 1)):\n if coins[i] == -1:\n continue\n for j in range(i + 1, min(i + maxJump + 1, n)):\n if dp[j] == math.inf:\n continue\n cost = coins[i] + dp[j]\n if cost < dp[i]:\n dp[i] = cost\n next[i] = j\n\n if dp[0] == math.inf:\n return []\n return self._constructPath(next, 0)\n\n def _constructPath(self, next: list[int], i: int) -> list[int]:\n ans = []\n while i != -1:\n ans.append(i + 1) # 1-indexed\n i = next[i]\n return ans\n", | |
| "title": "656. Coin Path", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 669 | |
| }, | |
| { | |
| "code": "class Solution:\n def judgeCircle(self, moves: str) -> bool:\n return moves.count('R') == moves.count('L') and moves.count('U') == moves.count('D')\n", | |
| "title": "657. Robot Return to Origin", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 670 | |
| }, | |
| { | |
| "code": "class Solution:\n def findClosestElements(self, arr: list[int], k: int, x: int) -> list[int]:\n l = 0\n r = len(arr) - k\n\n while l < r:\n m = (l + r) // 2\n if x - arr[m] <= arr[m + k] - x:\n r = m\n else:\n l = m + 1\n\n return arr[l:l + k]\n", | |
| "title": "658. Find K Closest Elements", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 671 | |
| }, | |
| { | |
| "code": "class Solution:\n def newInteger(self, n: int) -> int:\n ans = []\n while n:\n ans.append(str(n % 9))\n n //= 9\n return ''.join(reversed(ans))\n", | |
| "title": "660. Remove 9", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 672 | |
| }, | |
| { | |
| "code": "class Solution:\n def imageSmoother(self, M: list[list[int]]) -> list[list[int]]:\n m = len(M)\n n = len(M[0])\n ans = [[0 for j in range(n)] for i in range(m)]\n\n for i in range(m):\n for j in range(n):\n ones = 0\n count = 0\n for y in range(max(0, i - 1), min(m, i + 2)):\n for x in range(max(0, j - 1), min(n, j + 2)):\n ones += M[y][x]\n count += 1\n ans[i][j] = ones // count\n\n return ans\n", | |
| "title": "661. Image Smoother", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 673 | |
| }, | |
| { | |
| "code": "class Solution:\n def checkEqualTree(self, root: TreeNode | None) -> bool:\n if not root:\n return False\n\n seen = set()\n\n def dfs(root: TreeNode | None) -> int:\n if not root:\n return 0\n\n summ = root.val + dfs(root.left) + dfs(root.right)\n seen.add(summ)\n return summ\n\n summ = root.val + dfs(root.left) + dfs(root.right)\n return summ % 2 == 0 and summ // 2 in seen\n", | |
| "title": "663. Equal Tree Partition", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 674 | |
| }, | |
| { | |
| "code": "class Solution:\n def checkPossibility(self, nums: list[int]) -> bool:\n j = None\n\n for i in range(len(nums) - 1):\n if nums[i] > nums[i + 1]:\n if j is not None:\n return False\n j = i\n\n return (j is None or j == 0 or j == len(nums) - 2 or\n nums[j - 1] <= nums[j + 1] or nums[j] <= nums[j + 2])\n", | |
| "title": "665. Non-decreasing Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 675 | |
| }, | |
| { | |
| "code": "class Solution:\n def pathSum(self, nums: list[int]) -> int:\n ans = 0\n tree = [[-1] * 8 for _ in range(4)]\n\n for num in nums:\n d = num // 100 - 1\n p = (num % 100) // 10 - 1\n v = num % 10\n tree[d][p] = v\n\n def dfs(i: int, j: int, path: int) -> None:\n nonlocal ans\n if tree[i][j] == -1:\n return\n if i == 3 or max(tree[i + 1][j * 2], tree[i + 1][j * 2 + 1]) == -1:\n ans += path + tree[i][j]\n return\n\n dfs(i + 1, j * 2, path + tree[i][j])\n dfs(i + 1, j * 2 + 1, path + tree[i][j])\n\n dfs(0, 0, 0)\n return ans\n", | |
| "title": "666. Path Sum IV", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 676 | |
| }, | |
| { | |
| "code": "class Solution:\n def constructArray(self, n: int, k: int) -> list[int]:\n ans = list(range(1, n - k + 1))\n\n for i in range(k):\n if i % 2 == 0:\n ans.append(n - i // 2)\n else:\n ans.append(n - k + (i + 1) // 2)\n\n return ans\n", | |
| "title": "667. Beautiful Arrangement II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 677 | |
| }, | |
| { | |
| "code": "class Solution:\n def maximumSwap(self, num: int) -> int:\n s = list(str(num))\n dict = {c: i for i, c in enumerate(s)}\n\n for i, c in enumerate(s):\n for digit in reversed(string.digits):\n if digit <= c:\n break\n if digit in dict and dict[digit] > i:\n s[i], s[dict[digit]] = digit, s[i]\n return int(''.join(s))\n\n return num\n", | |
| "title": "670. Maximum Swap", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 678 | |
| }, | |
| { | |
| "code": "class Solution:\n def flipLights(self, n: int, m: int) -> int:\n n = min(n, 3)\n\n if m == 0:\n return 1\n if m == 1:\n return [2, 3, 4][n - 1]\n if m == 2:\n return [2, 4, 7][n - 1]\n\n return [2, 4, 8][n - 1]\n", | |
| "title": "672. Bulb Switcher II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 679 | |
| }, | |
| { | |
| "code": "class Solution:\n def findNumberOfLIS(self, nums: list[int]) -> int:\n ans = 0\n maxLength = 0\n # length[i] := the length of the LIS ending in nums[i]\n length = [1] * len(nums)\n # count[i] := the number of LIS's ending in nums[i]\n count = [1] * len(nums)\n\n # Calculate the `length` and `count` arrays.\n for i, num in enumerate(nums):\n for j in range(i):\n if nums[j] < num:\n if length[i] < length[j] + 1:\n length[i] = length[j] + 1\n count[i] = count[j]\n elif length[i] == length[j] + 1:\n count[i] += count[j]\n\n # Get the number of LIS.\n for i, l in enumerate(length):\n if l > maxLength:\n maxLength = l\n ans = count[i]\n elif l == maxLength:\n ans += count[i]\n\n return ans\n", | |
| "title": "673. Number of Longest Increasing Subsequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 680 | |
| }, | |
| { | |
| "code": "class Solution:\n def findLengthOfLCIS(self, nums: list[int]) -> int:\n ans = 0\n j = 0\n\n for i in range(len(nums)):\n if i > 0 and nums[i] <= nums[i - 1]:\n j = i\n ans = max(ans, i - j + 1)\n\n return ans\n", | |
| "title": "674. Longest Continuous Increasing Subsequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 681 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: dict[str, TrieNode] = {}\n self.isWord = False\n\n\nclass MagicDictionary:\n def __init__(self):\n self.root = TrieNode()\n\n def buildDict(self, dictionary: list[str]) -> None:\n for word in dictionary:\n self._insert(word)\n\n def search(self, searchWord: str) -> bool:\n node: TrieNode = self.root\n for i, c in enumerate(searchWord):\n for letter in string.ascii_lowercase:\n if letter == c:\n continue\n if letter not in node.children:\n continue\n child = node.children[letter]\n # Replace the searchWord[i] with `letter`, then check if\n # searchWord[i + 1..n) matches `child`.\n if self._find(child, searchWord, i + 1):\n return True\n if c not in node.children:\n return False\n node = node.children[c]\n return False\n\n def _insert(self, word: str) -> None:\n node: TrieNode = self.root\n for c in word:\n node = node.children.setdefault(c, TrieNode())\n node.isWord = True\n\n def _find(self, node: TrieNode, word: str, i: int) -> bool:\n for c in word[i:]:\n if c not in node.children:\n return False\n node = node.children[c]\n return node.isWord\n", | |
| "title": "676. Implement Magic Dictionary", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 682 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: dict[str, TrieNode] = {}\n self.sum = 0\n\n\nclass MapSum:\n def __init__(self):\n self.root = TrieNode()\n self.keyToVal = {}\n\n def insert(self, key: str, val: int) -> None:\n diff = val - self.keyToVal.get(key, 0)\n node: TrieNode = self.root\n for c in key:\n node = node.children.setdefault(c, TrieNode())\n node.sum += diff\n self.keyToVal[key] = val\n\n def sum(self, prefix: str) -> int:\n node: TrieNode = self.root\n for c in prefix:\n if c not in node.children:\n return 0\n node = node.children[c]\n return node.sum\n", | |
| "title": "677. Map Sum Pairs", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 683 | |
| }, | |
| { | |
| "code": "class Solution:\n def checkValidString(self, s: str) -> bool:\n low = 0\n high = 0\n\n for c in s:\n if c == '(':\n low += 1\n high += 1\n elif c == ')':\n if low > 0:\n low -= 1\n high -= 1\n else:\n if low > 0:\n low -= 1\n high += 1\n if high < 0:\n return False\n\n return low == 0\n", | |
| "title": "678. Valid Parenthesis String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 684 | |
| }, | |
| { | |
| "code": "class Solution:\n def judgePoint24(self, nums: list[int]) -> bool:\n def generate(a: float, b: float) -> list[float]:\n return [a * b,\n math.inf if b == 0 else a / b,\n math.inf if a == 0 else b / a,\n a + b, a - b, b - a]\n\n def dfs(nums: list[float]) -> bool:\n if len(nums) == 1:\n return abs(nums[0] - 24.0) < 0.001\n\n for i, j in itertools.combinations(range(len(nums)), 2):\n for num in generate(nums[i], nums[j]):\n nextRound = [num]\n for k in range(len(nums)):\n if k == i or k == j:\n continue\n nextRound.append(nums[k])\n if dfs(nextRound):\n return True\n\n return False\n\n return dfs(nums)\n", | |
| "title": "679. 24 Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 685 | |
| }, | |
| { | |
| "code": "class Solution:\n def validPalindrome(self, s: str) -> bool:\n def validPalindrome(l: int, r: int) -> bool:\n return all(s[i] == s[r - i + l] for i in range(l, (l + r) // 2 + 1))\n\n n = len(s)\n\n for i in range(n // 2):\n if s[i] != s[~i]:\n return validPalindrome(i + 1, n - 1 - i) or validPalindrome(i, n - 2 - i)\n\n return True\n", | |
| "title": "680. Valid Palindrome II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 686 | |
| }, | |
| { | |
| "code": "class Solution:\n def nextClosestTime(self, time: str) -> str:\n ans = list(time)\n digits = sorted(ans)\n\n def nextClosest(digit: str, limit: str) -> str:\n next = bisect_right(digits, digit)\n return digits[0] if next == 4 or digits[next] > limit else digits[next]\n\n ans[4] = nextClosest(ans[4], '9')\n if time[4] < ans[4]:\n return ''.join(ans)\n\n ans[3] = nextClosest(ans[3], '5')\n if time[3] < ans[3]:\n return ''.join(ans)\n\n ans[1] = nextClosest(ans[1], '3' if ans[0] == '2' else '9')\n if time[1] < ans[1]:\n return ''.join(ans)\n\n ans[0] = nextClosest(ans[0], '2')\n return ''.join(ans)\n", | |
| "title": "681. Next Closest Time", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 687 | |
| }, | |
| { | |
| "code": "class Solution:\n def calPoints(self, operations: list[str]) -> int:\n scores = []\n\n for operation in operations:\n match operation:\n case '+':\n scores.append(scores[-1] + scores[-2])\n case 'D':\n scores.append(scores[-1] * 2)\n case 'C':\n scores.pop()\n case default:\n scores.append(int(operation))\n\n return sum(scores)\n", | |
| "title": "682. Baseball Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 688 | |
| }, | |
| { | |
| "code": "class Solution:\n def kEmptySlots(self, bulbs: list[int], k: int) -> int:\n n = len(bulbs)\n ans = math.inf\n # day[i] := the day when bulbs[i] is turned on\n day = [0] * n\n\n for i, bulb in enumerate(bulbs):\n day[bulb - 1] = i + 1\n\n # Find a subarray of day[l..r], where its length is k + 2.\n # For each l < i < r, day[i] > max(day[l], day[r]).\n l = 0\n r = l + k + 1\n i = 1\n while r < n:\n if i == r:\n ans = min(ans, max(day[l], day[r]))\n l = i\n r = i + k + 1\n elif day[i] < max(day[l], day[r]):\n l = i\n r = i + k + 1\n i += 1\n\n return -1 if ans == math.inf else ans\n", | |
| "title": "683. K Empty Slots", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 689 | |
| }, | |
| { | |
| "code": "class UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> bool:\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return False\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n return True\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def findRedundantConnection(self, edges: list[list[int]]) -> list[int]:\n uf = UnionFind(len(edges) + 1)\n\n for edge in edges:\n u, v = edge\n if not uf.unionByRank(u, v):\n return edge\n", | |
| "title": "684. Redundant Connection", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 690 | |
| }, | |
| { | |
| "code": "class UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> bool:\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return False\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n return True\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def findRedundantDirectedConnection(\n self, edges: list[list[int]],\n ) -> list[int]:\n ids = [0] * (len(edges) + 1)\n nodeWithTwoParents = 0\n\n for _, v in edges:\n ids[v] += 1\n if ids[v] == 2:\n nodeWithTwoParents = v\n\n def findRedundantDirectedConnection(skippedEdgeIndex: int) -> list[int]:\n uf = UnionFind(len(edges) + 1)\n\n for i, edge in enumerate(edges):\n if i == skippedEdgeIndex:\n continue\n if not uf.unionByRank(edge[0], edge[1]):\n return edge\n\n return []\n\n # If there is no edge with two ids, don't skip any edge.\n if nodeWithTwoParents == 0:\n return findRedundantDirectedConnection(-1)\n\n for i in reversed(range(len(edges))):\n _, v = edges[i]\n if v == nodeWithTwoParents:\n # Try to delete the edges[i].\n if not findRedundantDirectedConnection(i):\n return edges[i]\n", | |
| "title": "685. Redundant Connection II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 691 | |
| }, | |
| { | |
| "code": "class Solution:\n def repeatedStringMatch(self, a: str, b: str) -> int:\n n = math.ceil(len(b) / len(a))\n s = a * n\n if b in s:\n return n\n if b in s + a:\n return n + 1\n return -1\n", | |
| "title": "686. Repeated String Match", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 692 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestUnivaluePath(self, root: TreeNode | None) -> int:\n ans = 0\n\n def longestUnivaluePathDownFrom(root: TreeNode | None) -> int:\n nonlocal ans\n if not root:\n return 0\n\n l = longestUnivaluePathDownFrom(root.left)\n r = longestUnivaluePathDownFrom(root.right)\n arrowLeft = l + 1 if root.left and root.left.val == root.val else 0\n arrowRight = r + 1 if root.right and root.right.val == root.val else 0\n ans = max(ans, arrowLeft + arrowRight)\n return max(arrowLeft, arrowRight)\n\n longestUnivaluePathDownFrom(root)\n return ans\n", | |
| "title": "687. Longest Univalue Path", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 693 | |
| }, | |
| { | |
| "code": "class Solution:\n def knightProbability(self, n: int, k: int, row: int, column: int) -> float:\n DIRS = ((1, 2), (2, 1), (2, -1), (1, -2),\n (-1, -2), (-2, -1), (-2, 1), (-1, 2))\n # dp[i][j] := the probability to stand on (i, j)\n dp = [[0] * n for _ in range(n)]\n dp[row][column] = 1.0\n\n for _ in range(k):\n newDp = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if 0 <= x < n and 0 <= y < n:\n newDp[i][j] += dp[x][y]\n dp = newDp\n\n return sum(map(sum, dp)) / 8**k\n", | |
| "title": "688. Knight Probability in Chessboard", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 694 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxSumOfThreeSubarrays(self, nums: list[int], k: int) -> list[int]:\n n = len(nums) - k + 1\n # sums[i] := sum(nums[i..i + k))\n sums = [0] * n\n # l[i] := the index in [0..i] that has the maximum sums[i]\n l = [0] * n\n # r[i] := the index in [i..n) that has the maximum sums[i]\n r = [0] * n\n\n summ = 0\n for i, num in enumerate(nums):\n summ += num\n if i >= k:\n summ -= nums[i - k]\n if i >= k - 1:\n sums[i - k + 1] = summ\n\n maxIndex = 0\n for i in range(n):\n if sums[i] > sums[maxIndex]:\n maxIndex = i\n l[i] = maxIndex\n\n maxIndex = n - 1\n for i in range(n - 1, -1, -1):\n if sums[i] >= sums[maxIndex]:\n maxIndex = i\n r[i] = maxIndex\n\n ans = [-1, -1, -1]\n\n for i in range(k, n - k):\n if (ans[0] == -1 or\n sums[ans[0]] + sums[ans[1]] + sums[ans[2]] <\n sums[l[i - k]] + sums[i] + sums[r[i + k]]):\n ans[0] = l[i - k]\n ans[1] = i\n ans[2] = r[i + k]\n\n return ans\n", | |
| "title": "689. Maximum Sum of 3 Non-Overlapping Subarrays", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 695 | |
| }, | |
| { | |
| "code": "class Solution:\n def getImportance(self, employees: list['Employee'], id: int) -> int:\n idToEmployee = {employee.id: employee for employee in employees}\n\n def dfs(id: int) -> int:\n values = idToEmployee[id].importance\n for subId in idToEmployee[id].subordinates:\n values += dfs(subId)\n return values\n\n return dfs(id)\n", | |
| "title": "690. Employee Importance", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 696 | |
| }, | |
| { | |
| "code": "class Solution:\n def minStickers(self, stickers: list[str], target: str) -> int:\n maxMask = 1 << len(target)\n # dp[i] := the minimum number of stickers to spell out i, where i is the\n # bit mask of target\n dp = [math.inf] * maxMask\n dp[0] = 0\n\n for mask in range(maxMask):\n if dp[mask] == math.inf:\n continue\n # Try to expand from `mask` by using each sticker.\n for sticker in stickers:\n superMask = mask\n for c in sticker:\n for i, t in enumerate(target):\n # Try to apply it on a missing letter.\n if c == t and not (superMask >> i & 1):\n superMask |= 1 << i\n break\n dp[superMask] = min(dp[superMask], dp[mask] + 1)\n\n return -1 if dp[-1] == math.inf else dp[-1]\n", | |
| "title": "691. Stickers to Spell Word", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 697 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass(frozen=True)\nclass T:\n word: str\n freq: int\n\n def __lt__(self, other):\n if self.freq == other.freq:\n return self.word > other.word\n return self.freq < other.freq\n\n\nclass Solution:\n def topKFrequent(self, words: list[str], k: int) -> list[str]:\n ans = []\n heap = []\n\n for word, freq in collections.Counter(words).items():\n heapq.heappush(heap, T(word, freq))\n if len(heap) > k:\n heapq.heappop(heap)\n\n while heap:\n ans.append(heapq.heappop(heap).word)\n\n return ans[::-1]\n", | |
| "title": "692. Top K Frequent Words", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 698 | |
| }, | |
| { | |
| "code": "class Solution:\n def hasAlternatingBits(self, n: int) -> bool:\n # n = 0b010101\n # n >> 2 = 0b000101\n # n ^ (n >> 2) = 0b010000 = a\n # a - 1 = 0b001111\n # a & (a - 1) = 0\n a = n ^ (n >> 2)\n return (a & (a - 1)) == 0\n", | |
| "title": "693. Binary Number with Alternating Bits", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 699 | |
| }, | |
| { | |
| "code": "class Solution:\n def numDistinctIslands(self, grid: list[list[int]]) -> int:\n seen = set()\n\n def dfs(i: int, j: int, i0: int, j0: int):\n if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]):\n return\n if grid[i][j] == 0 or (i, j) in seen:\n return\n\n seen.add((i, j))\n island.append((i - i0, j - j0))\n dfs(i + 1, j, i0, j0)\n dfs(i - 1, j, i0, j0)\n dfs(i, j + 1, i0, j0)\n dfs(i, j - 1, i0, j0)\n\n islands = set() # all the different islands\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n island = []\n dfs(i, j, i, j)\n if island:\n islands.add(frozenset(island))\n\n return len(islands)\n", | |
| "title": "694. Number of Distinct Islands", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 700 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxAreaOfIsland(self, grid: list[list[int]]) -> int:\n def dfs(i: int, j: int) -> int:\n if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]):\n return 0\n if grid[i][j] != 1:\n return 0\n\n grid[i][j] = 2\n\n return 1 + dfs(i + 1, j) + dfs(i - 1, j) + dfs(i, j + 1) + dfs(i, j - 1)\n\n return max(dfs(i, j) for i in range(len(grid)) for j in range(len(grid[0])))\n", | |
| "title": "695. Max Area of Island", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 701 | |
| }, | |
| { | |
| "code": "class Solution:\n def countBinarySubstrings(self, s: str) -> int:\n ans = 0\n prevCount = 0\n equals = 1\n\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n equals += 1\n else:\n ans += min(prevCount, equals)\n prevCount = equals\n equals = 1\n\n return ans + min(prevCount, equals)\n", | |
| "title": "696. Count Binary Substrings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 702 | |
| }, | |
| { | |
| "code": "class Solution:\n def findShortestSubArray(self, nums: list[int]) -> int:\n ans = 0\n degree = 0\n debut = {}\n count = collections.Counter()\n\n for i, num in enumerate(nums):\n debut.setdefault(num, i)\n count[num] += 1\n if count[num] > degree:\n degree = count[num]\n ans = i - debut[num] + 1\n elif count[num] == degree:\n ans = min(ans, i - debut[num] + 1)\n\n return ans\n", | |
| "title": "697. Degree of an Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312228, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 703 | |
| }, | |
| { | |
| "code": "class Solution:\n def canPartitionKSubsets(self, nums: list[int], k: int) -> bool:\n summ = sum(nums)\n if summ % k != 0:\n return False\n\n target = summ // k # the target sum of each subset\n if any(num > target for num in nums):\n return False\n\n def dfs(s: int, remainingGroups: int, currSum: int, used: int) -> bool:\n if remainingGroups == 0:\n return True\n if currSum > target:\n return False\n if currSum == target: # Find a valid group, so fresh start.\n return dfs(0, remainingGroups - 1, 0, used)\n\n for i in range(s, len(nums)):\n if used >> i & 1:\n continue\n if dfs(i + 1, remainingGroups, currSum + nums[i], used | 1 << i):\n return True\n\n return False\n\n nums.sort(reverse=True)\n return dfs(0, k, 0, 0)\n", | |
| "title": "698. Partition to K Equal Sum Subsets", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 704 | |
| }, | |
| { | |
| "code": "class Solution:\n def searchBST(self, root: TreeNode | None, val: int) -> TreeNode | None:\n if not root:\n return None\n if root.val == val:\n return root\n if root.val > val:\n return self.searchBST(root.left, val)\n return self.searchBST(root.right, val)\n", | |
| "title": "700. Search in a Binary Search Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 705 | |
| }, | |
| { | |
| "code": "class Solution:\n def insertIntoBST(self, root: TreeNode | None, val: int) -> TreeNode | None:\n if not root:\n return TreeNode(val)\n if root.val > val:\n root.left = self.insertIntoBST(root.left, val)\n else:\n root.right = self.insertIntoBST(root.right, val)\n return root\n", | |
| "title": "701. Insert into a Binary Search Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 706 | |
| }, | |
| { | |
| "code": "# \"\"\"\n# This is ArrayReader's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n# Class ArrayReader:\n# def get(self, index: int) -> int:\n\nclass Solution:\n def search(self, reader: 'ArrayReader', target: int) -> int:\n l = bisect.bisect_left(range(10**4), target,\n key=lambda m: reader.get(m))\n return l if reader.get(l) == target else -1\n", | |
| "title": "702. Search in a Sorted Array of Unknown Size", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 707 | |
| }, | |
| { | |
| "code": "class Solution:\n def search(self, nums: list[int], target: int) -> int:\n i = bisect.bisect_left(nums, target)\n return -1 if i == len(nums) or nums[i] != target else i\n", | |
| "title": "704. Binary Search", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 708 | |
| }, | |
| { | |
| "code": "class MyHashSet:\n def __init__(self):\n self.set = [False] * 1000001\n\n def add(self, key: int) -> None:\n self.set[key] = True\n\n def remove(self, key: int) -> None:\n self.set[key] = False\n\n def contains(self, key: int) -> bool:\n return self.set[key]\n", | |
| "title": "705. Design HashSet", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 709 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass\nclass ListNode:\n val: int\n next: ListNode | None = None\n\n\nclass MyLinkedList:\n def __init__(self):\n self.length = 0\n self.dummy = ListNode(0)\n\n def get(self, index: int) -> int:\n if index < 0 or index >= self.length:\n return -1\n curr = self.dummy.next\n for _ in range(index):\n curr = curr.next\n return curr.val\n\n def addAtHead(self, val: int) -> None:\n curr = self.dummy.next\n self.dummy.next = ListNode(val)\n self.dummy.next.next = curr\n self.length += 1\n\n def addAtTail(self, val: int) -> None:\n curr = self.dummy\n while curr.next:\n curr = curr.next\n curr.next = ListNode(val)\n self.length += 1\n\n def addAtIndex(self, index: int, val: int) -> None:\n if index > self.length:\n return\n curr = self.dummy\n for _ in range(index):\n curr = curr.next\n temp = curr.next\n curr.next = ListNode(val)\n curr.next.next = temp\n self.length += 1\n\n def deleteAtIndex(self, index: int) -> None:\n if index < 0 or index >= self.length:\n return\n curr = self.dummy\n for _ in range(index):\n curr = curr.next\n temp = curr.next\n curr.next = temp.next\n self.length -= 1\n", | |
| "title": "707. Design Linked List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 710 | |
| }, | |
| { | |
| "code": "class Solution:\n def toLowerCase(self, str: str) -> str:\n return ''.join(chr(ord(c) + 32) if 'A' <= c <= 'Z' else c for c in str)\n", | |
| "title": "709. To Lower Case", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 711 | |
| }, | |
| { | |
| "code": "class Solution:\n def __init__(self, n: int, blacklist: list[int]):\n self.validRange = n - len(blacklist)\n self.dict = {}\n\n maxAvailable = n - 1\n\n for b in blacklist:\n self.dict[b] = -1\n\n for b in blacklist:\n if b < self.validRange:\n # Find the slot that haven't been used.\n while maxAvailable in self.dict:\n maxAvailable -= 1\n self.dict[b] = maxAvailable\n maxAvailable -= 1\n\n def pick(self) -> int:\n value = random.randint(0, self.validRange - 1)\n\n if value in self.dict:\n return self.dict[value]\n\n return value\n", | |
| "title": "710. Random Pick with Blacklist", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 712 | |
| }, | |
| { | |
| "code": "class Solution:\n def numDistinctIslands2(self, grid: list[list[int]]) -> int:\n seen = set()\n\n def dfs(i: int, j: int):\n if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]):\n return\n if grid[i][j] == 0 or (i, j) in seen:\n return\n\n seen.add((i, j))\n island.append((i, j))\n dfs(i + 1, j)\n dfs(i - 1, j)\n dfs(i, j + 1)\n dfs(i, j - 1)\n\n def normalize(island: list[tuple]) -> list[tuple]:\n # points[i] := 8 different rotations/reflections of an island\n points = [[] for _ in range(8)]\n\n for i, j in island:\n points[0].append((i, j))\n points[1].append((i, -j))\n points[2].append((-i, j))\n points[3].append((-i, -j))\n points[4].append((j, i))\n points[5].append((j, -i))\n points[6].append((-j, i))\n points[7].append((-j, -i))\n\n points = [sorted(p) for p in points]\n\n # Normalize each p by substracting p[1..7] with p[0].\n for p in points:\n for i in range(1, len(island)):\n p[i] = (p[i][0] - p[0][0],\n p[i][1] - p[0][1])\n p[0] = (0, 0)\n\n return sorted(points)[0]\n\n islands = set() # all the islands with different shapes\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n island = []\n dfs(i, j)\n if island:\n islands.add(frozenset(normalize(island)))\n\n return len(islands)\n", | |
| "title": "711. Number of Distinct Islands II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 713 | |
| }, | |
| { | |
| "code": "class Solution:\n def numSubarrayProductLessThanK(self, nums: list[int], k: int) -> int:\n if k <= 1:\n return 0\n\n ans = 0\n prod = 1\n\n j = 0\n for i, num in enumerate(nums):\n prod *= num\n while prod >= k:\n prod /= nums[j]\n j += 1\n ans += i - j + 1\n\n return ans\n", | |
| "title": "713. Subarray Product Less Than K", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 714 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxProfit(self, prices: list[int], fee: int) -> int:\n sell = 0\n hold = -math.inf\n\n for price in prices:\n sell = max(sell, hold + price)\n hold = max(hold, sell - price - fee)\n\n return sell\n", | |
| "title": "714. Best Time to Buy and Sell Stock with Transaction Fee", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 715 | |
| }, | |
| { | |
| "code": "class RangeModule:\n def __init__(self):\n self.A = []\n\n def addRange(self, left: int, right: int) -> None:\n i = bisect_left(self.A, left)\n j = bisect_right(self.A, right)\n self.A[i:j] = [left] * (i % 2 == 0) + [right] * (j % 2 == 0)\n\n def queryRange(self, left: int, right: int) -> bool:\n i = bisect_right(self.A, left)\n j = bisect_left(self.A, right)\n return i == j and i % 2 == 1\n\n def removeRange(self, left: int, right: int) -> None:\n i = bisect_left(self.A, left)\n j = bisect_right(self.A, right)\n self.A[i:j] = [left] * (i % 2 == 1) + [right] * (j % 2 == 1)\n", | |
| "title": "715. Range Module", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 716 | |
| }, | |
| { | |
| "code": "class Solution:\n def isOneBitCharacter(self, bits: list[int]) -> bool:\n i = 0\n while i < len(bits) - 1:\n i += bits[i] + 1\n\n return i == len(bits) - 1\n", | |
| "title": "717. 1-bit and 2-bit Characters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 717 | |
| }, | |
| { | |
| "code": "class Solution:\n def findLength(self, nums1: list[int], nums2: list[int]) -> int:\n ans = 0\n dp = [0] * (len(nums2) + 1)\n\n for a in reversed(nums1):\n for j, b in enumerate(nums2): # The order is important.\n dp[j] = dp[j + 1] + 1 if a == b else 0\n ans = max(ans, dp[j])\n\n return ans\n", | |
| "title": "718. Maximum Length of Repeated Subarray", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 718 | |
| }, | |
| { | |
| "code": "class Solution:\n def smallestDistancePair(self, nums: list[int], k: int) -> int:\n nums.sort()\n\n def numPairDistancesNoGreaterThan(m: int) -> int:\n count = 0\n j = 1\n # For each index i, find the first index j s.t. nums[j] > nums[i] + m,\n # so numPairDistancesNoGreaterThan for the index i will be j - i - 1.\n for i, num in enumerate(nums):\n while j < len(nums) and nums[j] <= num + m:\n j += 1\n count += j - i - 1\n return count\n\n return bisect.bisect_left(range(nums[-1] - nums[0]), k,\n key=numPairDistancesNoGreaterThan)\n", | |
| "title": "719. Find K-th Smallest Pair Distance", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 719 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestWord(self, words: list[str]) -> str:\n root = {}\n\n for word in words:\n node = root\n for c in word:\n if c not in node:\n node[c] = {}\n node = node[c]\n node['word'] = word\n\n def dfs(node: dict) -> str:\n ans = node['word'] if 'word' in node else ''\n\n for child in node:\n if 'word' in node[child] and len(node[child]['word']) > 0:\n childWord = dfs(node[child])\n if len(childWord) > len(ans) or (\n len(childWord) == len(ans) and childWord < ans):\n ans = childWord\n\n return ans\n\n return dfs(root)\n", | |
| "title": "720. Longest Word in Dictionary", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 720 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeComments(self, source: list[str]) -> list[str]:\n ans = []\n commenting = False\n modified = ''\n\n for line in source:\n i = 0\n while i < len(line):\n if i + 1 == len(line):\n if not commenting:\n modified += line[i]\n i += 1\n break\n twoChars = line[i:i + 2]\n if twoChars == '/*' and not commenting:\n commenting = True\n i += 2\n elif twoChars == '*/' and commenting:\n commenting = False\n i += 2\n elif twoChars == '//':\n if not commenting:\n break\n else:\n i += 2\n else:\n if not commenting:\n modified += line[i]\n i += 1\n if modified and not commenting:\n ans.append(modified)\n modified = ''\n\n return ans\n", | |
| "title": "722. Remove Comments", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 721 | |
| }, | |
| { | |
| "code": "class Solution:\n def pivotIndex(self, nums: list[int]) -> int:\n summ = sum(nums)\n prefix = 0\n\n for i, num in enumerate(nums):\n if prefix == summ - prefix - num:\n return i\n prefix += num\n\n return -1\n", | |
| "title": "724. Find Pivot Index", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 722 | |
| }, | |
| { | |
| "code": "class Solution:\n def splitListToParts(self, root: ListNode, k: int) -> list[ListNode]:\n ans = [[] for _ in range(k)]\n length = 0\n curr = root\n while curr:\n length += 1\n curr = curr.next\n subLength = length // k\n remainder = length % k\n\n prev = None\n head = root\n\n for i in range(k):\n ans[i] = head\n for j in range(subLength + (1 if remainder > 0 else 0)):\n prev = head\n head = head.next\n if prev:\n prev.next = None\n remainder -= 1\n\n return ans\n", | |
| "title": "725. Split Linked List in Parts", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 723 | |
| }, | |
| { | |
| "code": "class Solution:\n def countOfAtoms(self, formula: str) -> str:\n def parse() -> dict:\n ans = collections.defaultdict(int)\n\n nonlocal i\n while i < n:\n if formula[i] == '(':\n i += 1\n for elem, freq in parse().items():\n ans[elem] += freq\n elif formula[i] == ')':\n i += 1\n numStart = i\n while i < n and formula[i].isdigit():\n i += 1\n factor = int(formula[numStart:i])\n for elem, freq in ans.items():\n ans[elem] *= factor\n return ans\n elif formula[i].isupper():\n elemStart = i\n i += 1\n while i < n and formula[i].islower():\n i += 1\n elem = formula[elemStart:i]\n numStart = i\n while i < n and formula[i].isdigit():\n i += 1\n num = 1 if i == numStart else int(\n formula[numStart:i])\n ans[elem] += num\n\n return ans\n\n n = len(formula)\n\n ans = \"\"\n i = 0\n count = parse()\n\n for elem in sorted(count.keys()):\n ans += elem\n if count[elem] > 1:\n ans += str(count[elem])\n\n return ans\n", | |
| "title": "726. Number of Atoms", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 724 | |
| }, | |
| { | |
| "code": "class Solution:\n def selfDividingNumbers(self, left: int, right: int) -> list[int]:\n return [num for num in range(left, right + 1) if all(n != 0 and num % n == 0 for n in map(int, str(num)))]\n", | |
| "title": "728. Self Dividing Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 725 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n start: int\n end: int\n left = None\n right = None\n\n\nclass Tree:\n def __init__(self):\n self.root = None\n\n def insert(self, node: Node, root: Node = None) -> bool:\n if not root:\n if not self.root:\n self.root = node\n return True\n else:\n root = self.root\n\n if node.start >= root.end:\n if not root.right:\n root.right = node\n return True\n return self.insert(node, root.right)\n elif node.end <= root.start:\n if not root.left:\n root.left = node\n return True\n return self.insert(node, root.left)\n else:\n return False\n\n\nclass MyCalendar:\n def __init__(self):\n self.tree = Tree()\n\n def book(self, start: int, end: int) -> bool:\n return self.tree.insert(Node(start, end))\n", | |
| "title": "729. My Calendar I", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 726 | |
| }, | |
| { | |
| "code": "class Solution:\n def countPalindromicSubsequences(self, s: str) -> int:\n MOD = 1_000_000_007\n n = len(s)\n # dp[i][j] := the number of different non-empty palindromic subsequences in\n # s[i..j]\n dp = [[0] * n for _ in range(n)]\n\n for i in range(n):\n dp[i][i] = 1\n\n for d in range(1, n):\n for i in range(n - d):\n j = i + d\n if s[i] == s[j]:\n lo = i + 1\n hi = j - 1\n while lo <= hi and s[lo] != s[i]:\n lo += 1\n while lo <= hi and s[hi] != s[i]:\n hi -= 1\n if lo > hi:\n dp[i][j] = dp[i + 1][j - 1] * 2 + 2\n elif lo == hi:\n dp[i][j] = dp[i + 1][j - 1] * 2 + 1\n else:\n dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1]\n else:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]\n dp[i][j] = (dp[i][j] + MOD) % MOD\n\n return dp[0][n - 1]\n", | |
| "title": "730. Count Different Palindromic Subsequences", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 727 | |
| }, | |
| { | |
| "code": "from sortedcontainers import SortedDict\n\n\nclass MyCalendarThree:\n def __init__(self):\n self.line = SortedDict()\n\n def book(self, start: int, end: int) -> int:\n self.line[start] = self.line.get(start, 0) + 1\n self.line[end] = self.line.get(end, 0) - 1\n\n ans = 0\n activeEvents = 0\n\n for count in self.line.values():\n activeEvents += count\n ans = max(ans, activeEvents)\n\n return ans\n", | |
| "title": "732. My Calendar III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 728 | |
| }, | |
| { | |
| "code": "class Solution:\n def floodFill(self, image: list[list[int]],\n sr: int, sc: int, newColor: int) -> list[list[int]]:\n startColor = image[sr][sc]\n seen = set()\n\n def dfs(i: int, j: int) -> None:\n if i < 0 or i == len(image) or j < 0 or j == len(image[0]):\n return\n if image[i][j] != startColor or (i, j) in seen:\n return\n\n image[i][j] = newColor\n seen.add((i, j))\n\n dfs(i + 1, j)\n dfs(i - 1, j)\n dfs(i, j + 1)\n dfs(i, j - 1)\n\n dfs(sr, sc)\n return image\n", | |
| "title": "733. Flood Fill", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 729 | |
| }, | |
| { | |
| "code": "class Solution:\n def areSentencesSimilar(\n self,\n sentence1: list[str],\n sentence2: list[str],\n similarPairs: list[list[str]],\n ) -> bool:\n if len(sentence1) != len(sentence2):\n return False\n\n # map[key] := all the similar words of key\n map = collections.defaultdict(set)\n\n for a, b in similarPairs:\n map[a].add(b)\n map[b].add(a)\n\n for word1, word2 in zip(sentence1, sentence2):\n if word1 == word2:\n continue\n if word1 not in map:\n return False\n if word2 not in map[word1]:\n return False\n\n return True\n", | |
| "title": "734. Sentence Similarity", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 730 | |
| }, | |
| { | |
| "code": "class Solution:\n def asteroidCollision(self, asteroids: list[int]) -> list[int]:\n stack = []\n\n for a in asteroids:\n if a > 0:\n stack.append(a)\n else: # a < 0\n # Destroy the previous positive one(s).\n while stack and stack[-1] > 0 and stack[-1] < -a:\n stack.pop()\n if not stack or stack[-1] < 0:\n stack.append(a)\n elif stack[-1] == -a:\n stack.pop() # Both asteroids explode.\n else: # stack[-1] > the current asteroid.\n pass # Destroy the current asteroid, so do nothing.\n\n return stack\n", | |
| "title": "735. Asteroid Collision", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 731 | |
| }, | |
| { | |
| "code": "class Solution:\n def evaluate(self, expression: str) -> int:\n def evaluate(e: str, prevScope: dict) -> int:\n if e[0].isdigit() or e[0] == '-':\n return int(e)\n if e in prevScope:\n return prevScope[e]\n\n scope = prevScope.copy()\n nextExpression = e[e.index(' ') + 1:-1]\n tokens = parse(nextExpression)\n\n if e[1] == 'm': # 'mult'\n return evaluate(tokens[0], scope) * evaluate(tokens[1], scope)\n if e[1] == 'a': # 'add'\n return evaluate(tokens[0], scope) + evaluate(tokens[1], scope)\n\n # 'let'\n for i in range(0, len(tokens) - 2, 2):\n scope[tokens[i]] = evaluate(tokens[i + 1], scope)\n\n return evaluate(tokens[-1], scope)\n\n def parse(e: str):\n tokens = []\n s = ''\n opened = 0\n\n for c in e:\n if c == '(':\n opened += 1\n elif c == ')':\n opened -= 1\n if opened == 0 and c == ' ':\n tokens.append(s)\n s = ''\n else:\n s += c\n\n if len(s) > 0:\n tokens.append(s)\n return tokens\n\n return evaluate(expression, {})\n", | |
| "title": "736. Parse Lisp Expression", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 732 | |
| }, | |
| { | |
| "code": "class Solution:\n def areSentencesSimilarTwo(\n self,\n words1: list[str],\n words2: list[str],\n pairs: list[list[str]],\n ) -> bool:\n if len(words1) != len(words2):\n return False\n\n # graph[key] := all the similar words of key\n graph = collections.defaultdict(set)\n\n for a, b in pairs:\n graph[a].add(b)\n graph[b].add(a)\n\n def dfs(word1: str, word2: str, seen: set) -> bool:\n if word1 in graph[word2]:\n return True\n\n seen.add(word1)\n\n for child in graph[word1]:\n if child in seen:\n continue\n if dfs(child, word2, seen):\n return True\n\n return False\n\n for word1, word2 in zip(words1, words2):\n if word1 == word2:\n continue\n if word1 not in graph:\n return False\n if not dfs(word1, word2, set()):\n return False\n\n return True\n", | |
| "title": "737. Sentence Similarity II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 733 | |
| }, | |
| { | |
| "code": "class Solution:\n def dailyTemperatures(self, temperatures: list[int]) -> list[int]:\n ans = [0] * len(temperatures)\n stack = [] # a decreasing stack\n\n for i, temperature in enumerate(temperatures):\n while stack and temperature > temperatures[stack[-1]]:\n index = stack.pop()\n ans[index] = i - index\n stack.append(i)\n\n return ans\n", | |
| "title": "739. Daily Temperatures", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 734 | |
| }, | |
| { | |
| "code": "class Solution:\n def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n graph = [[] for _ in range(n)]\n\n for u, v, w in times:\n graph[u - 1].append((v - 1, w))\n\n return self._dijkstra(graph, k - 1)\n\n def _dijkstra(self, graph: list[list[tuple[int, int]]], src: int) -> int:\n dist = [math.inf] * len(graph)\n\n dist[src] = 0\n minHeap = [(dist[src], src)] # (d, u)\n\n while minHeap:\n d, u = heapq.heappop(minHeap)\n if d > dist[u]:\n continue\n for v, w in graph[u]:\n if d + w < dist[v]:\n dist[v] = d + w\n heapq.heappush(minHeap, (dist[v], v))\n\n maxDist = max(dist)\n return maxDist if maxDist != math.inf else -1\n", | |
| "title": "743. Network Delay Time", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 735 | |
| }, | |
| { | |
| "code": "class Solution:\n def nextGreatestLetter(self, letters: list[str], target: str) -> str:\n l = bisect.bisect_right(range(len(letters)), target,\n key=lambda m: letters[m])\n return letters[l % len(letters)]\n", | |
| "title": "744. Find Smallest Letter Greater Than Target", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 736 | |
| }, | |
| { | |
| "code": "class Solution:\n def minCostClimbingStairs(self, cost: list[int]) -> int:\n cost.append(0)\n\n for i in range(2, len(cost)):\n cost[i] += min(cost[i - 1], cost[i - 2])\n\n return cost[-1]\n", | |
| "title": "746. Min Cost Climbing Stairs", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 737 | |
| }, | |
| { | |
| "code": "class Solution:\n def dominantIndex(self, nums: list[int]) -> int:\n mx = 0\n secondMax = 0\n\n for i, num in enumerate(nums):\n if num > mx:\n secondMax = mx\n mx = num\n ans = i\n elif num > secondMax:\n secondMax = num\n\n return ans if mx >= 2 * secondMax else -1\n", | |
| "title": "747. Largest Number At Least Twice of Others", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 738 | |
| }, | |
| { | |
| "code": "class Solution:\n def shortestCompletingWord(self, licensePlate: str, words: list[str]) -> str:\n def isMatch(word: str) -> bool:\n wordCount = collections.Counter(word)\n return False if any(\n wordCount[i] < count[i] for i in string.ascii_letters) else True\n\n ans = '*' * 16\n count = collections.defaultdict(int)\n\n for c in licensePlate:\n if c.isalpha():\n count[c.lower()] += 1\n\n for word in words:\n if len(word) < len(ans) and isMatch(word):\n ans = word\n\n return ans\n", | |
| "title": "748. Shortest Completing Word", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 739 | |
| }, | |
| { | |
| "code": "class Solution:\n def ipToCIDR(self, ip: str, n: int) -> list[str]:\n ans = []\n num = self._getNum(ip.split('.'))\n\n while n > 0:\n lowbit = num & -num\n count = self._maxLow(n) if lowbit == 0 else self._firstFit(lowbit, n)\n ans.append(self._getCIDR(num, self._getPrefix(count)))\n n -= count\n num += count\n\n return ans\n\n def _getNum(self, x: list[str]) -> int:\n num = 0\n for i in range(4):\n num = num * 256 + int(x[i])\n return num\n\n def _maxLow(self, n: int) -> int | None:\n \"\"\"Returns the maximum i s.t. 2^i < n.\"\"\"\n for i in range(32):\n if 1 << i + 1 > n:\n return 1 << i\n\n def _firstFit(self, lowbit: int, n: int) -> int:\n while lowbit > n:\n lowbit >>= 1\n return lowbit\n\n def _getCIDR(self, num: int, prefix: int) -> str:\n d = num & 255\n num >>= 8\n c = num & 255\n num >>= 8\n b = num & 255\n num >>= 8\n a = num & 255\n return '.'.join([str(s) for s in [a, b, c, d]]) + '/' + str(prefix)\n\n def _getPrefix(self, count: int) -> int | None:\n \"\"\"\n e.g. count = 8 = 2^3 . prefix = 32 - 3 = 29\n count = 1 = 2^0 . prefix = 32 - 0 = 32\n \"\"\"\n for i in range(32):\n if count == 1 << i:\n return 32 - i\n", | |
| "title": "751. IP to CIDR", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 740 | |
| }, | |
| { | |
| "code": "class Solution:\n def crackSafe(self, n: int, k: int) -> str:\n passwordSize = k**n\n path = '0' * n\n seen = set()\n seen.add(path)\n\n def dfs(path: str) -> str:\n if len(seen) == passwordSize:\n return path\n\n for c in map(str, range(k)):\n node = path[-n + 1:] + c if n > 1 else c\n if node not in seen:\n seen.add(node)\n res = dfs(path + c)\n if res:\n return res\n seen.remove(node)\n\n return dfs(path)\n", | |
| "title": "753. Cracking the Safe", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 741 | |
| }, | |
| { | |
| "code": "class Solution:\n def reachNumber(self, target: int) -> int:\n ans = 0\n pos = 0\n target = abs(target)\n\n while pos < target:\n ans += 1\n pos += ans\n\n while (pos - target) % 2 == 1:\n ans += 1\n pos += ans\n\n return ans\n", | |
| "title": "754. Reach a Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 742 | |
| }, | |
| { | |
| "code": "class Solution:\n def pourWater(self, heights: list[int], volume: int, k: int) -> list[int]:\n i = k\n\n while volume > 0:\n volume -= 1\n while i > 0 and heights[i] >= heights[i - 1]:\n i -= 1\n while i + 1 < len(heights) and heights[i] >= heights[i + 1]:\n i += 1\n while i > k and heights[i] == heights[i - 1]:\n i -= 1\n heights[i] += 1\n\n return heights\n", | |
| "title": "755. Pour Water", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 743 | |
| }, | |
| { | |
| "code": "class Solution:\n def pyramidTransition(self, bottom: str, allowed: list[str]) -> bool:\n prefixToBlocks = collections.defaultdict(list)\n\n for a in allowed:\n prefixToBlocks[a[:2]].append(a[2])\n\n def dfs(row: str, nextRow: str, i: int) -> bool:\n if len(row) == 1:\n return True\n if len(nextRow) + 1 == len(row):\n return dfs(nextRow, '', 0)\n\n for c in prefixToBlocks[row[i:i + 2]]:\n if dfs(row, nextRow + c, i + 1):\n return True\n\n return False\n\n return dfs(bottom, '', 0)\n", | |
| "title": "756. Pyramid Transition Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 744 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: dict[str, TrieNode] = {}\n self.isWord = False\n\n\nclass Solution:\n def boldWords(self, words: list[str], s: str) -> str:\n n = len(s)\n ans = []\n # bold[i] := True if s[i] should be bolded\n bold = [0] * n\n root = TrieNode()\n\n def insert(word: str) -> None:\n node = root\n for c in word:\n if c not in node.children:\n node.children[c] = TrieNode()\n node = node.children[c]\n node.isWord = True\n\n def find(s: str, i: int) -> int:\n node = root\n ans = -1\n for j in range(i, len(s)):\n node = node.children.setdefault(s[j], TrieNode())\n if node.isWord:\n ans = j\n return ans\n\n for word in words:\n insert(word)\n\n boldEnd = -1 # `s[i..boldEnd]` should be bolded.\n for i in range(n):\n boldEnd = max(boldEnd, find(s, i))\n bold[i] = boldEnd >= i\n\n # Construct the with bold tags\n i = 0\n while i < n:\n if bold[i]:\n j = i\n while j < n and bold[j]:\n j += 1\n # `s[i..j)` should be bolded.\n ans.append('<b>' + s[i:j] + '</b>')\n i = j\n else:\n ans.append(s[i])\n i += 1\n\n return ''.join(ans)\n", | |
| "title": "758. Bold Words in String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 745 | |
| }, | |
| { | |
| "code": "class Solution:\n def employeeFreeTime(self, schedule: '[[Interval]]') -> '[Interval]':\n ans = []\n intervals = []\n\n for s in schedule:\n intervals.extend(s)\n\n intervals.sort(key=lambda x: x.start)\n\n prevEnd = intervals[0].end\n\n for interval in intervals:\n if interval.start > prevEnd:\n ans.append(Interval(prevEnd, interval.start))\n prevEnd = max(prevEnd, interval.end)\n\n return ans\n", | |
| "title": "759. Employee Free Time", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 746 | |
| }, | |
| { | |
| "code": "class Solution:\n def anagramMappings(self, nums1: list[int], nums2: list[int]) -> list[int]:\n numToIndices = collections.defaultdict(list)\n\n for i, num in enumerate(nums2):\n numToIndices[num].append(i)\n\n return [numToIndices[num].pop() for num in nums1]\n", | |
| "title": "760. Find Anagram Mappings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 747 | |
| }, | |
| { | |
| "code": "class Solution:\n def makeLargestSpecial(self, s: str) -> str:\n specials = []\n count = 0\n\n i = 0\n for j, c in enumerate(s):\n count += 1 if c == '1' else -1\n if count == 0:\n specials.append(\n '1' + self.makeLargestSpecial(s[i + 1:j]) + '0')\n i = j + 1\n\n return ''.join(sorted(specials)[::-1])\n", | |
| "title": "761. Special Binary String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 748 | |
| }, | |
| { | |
| "code": "class Solution:\n def partitionLabels(self, s: str) -> list[int]:\n ans = []\n letterToRightmostIndex = {c: i for i, c in enumerate(s)}\n\n l = 0 # the leftmost index of the current running string\n r = 0 # the rightmost index of the current running string\n\n for i, c in enumerate(s):\n r = max(r, letterToRightmostIndex[c])\n if i == r:\n ans.append(r - l + 1)\n l = r + 1\n\n return ans\n", | |
| "title": "763. Partition Labels", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 749 | |
| }, | |
| { | |
| "code": "class Solution:\n def isToeplitzMatrix(self, matrix: list[list[int]]) -> bool:\n for i in range(len(matrix) - 1):\n for j in range(len(matrix[0]) - 1):\n if matrix[i][j] != matrix[i + 1][j + 1]:\n return False\n\n return True\n", | |
| "title": "766. Toeplitz Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 750 | |
| }, | |
| { | |
| "code": "class Solution:\n def reorganizeString(self, s: str) -> str:\n n = len(s)\n count = collections.Counter(s)\n maxCount = max(count.values())\n\n if maxCount > (n + 1) // 2:\n return ''\n\n if maxCount == (n + 1) // 2:\n maxLetter = max(count, key=count.get)\n ans = [maxLetter if i % 2 == 0 else '' for i in range(n)]\n del count[maxLetter]\n i = 1\n else:\n ans = [''] * n\n i = 0\n\n for c, freq in count.items():\n for _ in range(freq):\n ans[i] = c\n i += 2\n if i >= n:\n i = 1\n\n return ''.join(ans)\n", | |
| "title": "767. Reorganize String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 751 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxChunksToSorted(self, arr: list[int]) -> int:\n n = len(arr)\n ans = 0\n mx = -math.inf\n mn = [arr[-1]] * n\n\n for i in reversed(range(n - 1)):\n mn[i] = min(mn[i + 1], arr[i])\n\n for i in range(n - 1):\n mx = max(mx, arr[i])\n if mx <= mn[i + 1]:\n ans += 1\n\n return ans + 1\n", | |
| "title": "768. Max Chunks To Make Sorted II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 752 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxChunksToSorted(self, arr: list[int]) -> int:\n ans = 0\n mx = -math.inf\n\n for i, a in enumerate(arr):\n mx = max(mx, a)\n if mx == i:\n ans += 1\n\n return ans\n", | |
| "title": "769. Max Chunks To Make Sorted", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 753 | |
| }, | |
| { | |
| "code": "class Poly:\n def __init__(self, term: str = None, coef: int = None):\n if term and coef:\n self.terms = collections.Counter({term: coef})\n else:\n self.terms = collections.Counter()\n\n def __add__(self, other):\n for term, coef in other.terms.items():\n self.terms[term] += coef\n return self\n\n def __sub__(self, other):\n for term, coef in other.terms.items():\n self.terms[term] -= coef\n return self\n\n def __mul__(self, other):\n res = Poly()\n for a, aCoef in self.terms.items():\n for b, bCoef in other.terms.items():\n res.terms[self._merge(a, b)] += aCoef * bCoef\n return res\n\n # Def __str__(self):\n # res = []\n # for term, coef in self.terms.items():\n # res.append(term + ': ' + str(coef))\n # return '{' + ', '.join(res) + '}'\n\n def toList(self) -> list[str]:\n for term in list(self.terms.keys()):\n if not self.terms[term]:\n del self.terms[term]\n\n def cmp(term: str) -> tuple:\n # the minimum degree is the last\n if term == '1':\n return (0,)\n var = term.split('*')\n # the maximum degree is the first\n # Break ties by their lexicographic orders.\n return (-len(var), term)\n\n def concat(term: str) -> str:\n if term == '1':\n return str(self.terms[term])\n return str(self.terms[term]) + '*' + term\n\n terms = list(self.terms.keys())\n terms.sort(key=cmp)\n return [concat(term) for term in terms]\n\n def _merge(self, a: str, b: str) -> str:\n if a == '1':\n return b\n if b == '1':\n return a\n res = []\n A = a.split('*')\n B = b.split('*')\n i = 0 # A's index\n j = 0 # B's index\n while i < len(A) and j < len(B):\n if A[i] < B[j]:\n res.append(A[i])\n i += 1\n else:\n res.append(B[j])\n j += 1\n return '*'.join(res + A[i:] + B[j:])\n\n\nclass Solution:\n def basicCalculatorIV(\n self,\n expression: str,\n evalvars: list[str],\n evalints: list[int],\n ) -> list[str]:\n tokens = list(self._getTokens(expression))\n evalMap = {a: b for a, b in zip(evalvars, evalints)}\n\n for i, token in enumerate(tokens):\n if token in evalMap:\n tokens[i] = str(evalMap[token])\n\n postfix = self._infixToPostfix(tokens)\n return self._evaluate(postfix).toList()\n\n def _getTokens(self, s: str) -> Iterator[str]:\n i = 0\n for j, c in enumerate(s):\n if c == ' ':\n if i < j:\n yield s[i:j]\n i = j + 1\n elif c in '()+-*':\n if i < j:\n yield s[i:j]\n yield c\n i = j + 1\n if i < len(s):\n yield s[i:]\n\n def _infixToPostfix(self, tokens: list[str]) -> list[str]:\n postfix = []\n ops = []\n\n def precedes(prevOp: str, currOp: str) -> bool:\n if prevOp == '(':\n return False\n return prevOp == '*' or currOp in '+-'\n\n for token in tokens:\n if token == '(':\n ops.append(token)\n elif token == ')':\n while ops[-1] != '(':\n postfix.append(ops.pop())\n ops.pop()\n elif token in '+-*': # isOperator(token)\n while ops and precedes(ops[-1], token):\n postfix.append(ops.pop())\n ops.append(token)\n else: # isOperand(token)\n postfix.append(token)\n return postfix + ops[::-1]\n\n def _evaluate(self, postfix: list[str]) -> Poly:\n polys: list[Poly] = []\n for token in postfix:\n if token in '+-*':\n b = polys.pop()\n a = polys.pop()\n if token == '+':\n polys.append(a + b)\n elif token == '-':\n polys.append(a - b)\n else: # token == '*'\n polys.append(a * b)\n elif token.lstrip('-').isnumeric():\n polys.append(Poly(\"1\", int(token)))\n else:\n polys.append(Poly(token, 1))\n return polys[0]\n", | |
| "title": "770. Basic Calculator IV", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 754 | |
| }, | |
| { | |
| "code": "class Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n jewelsSet = set(jewels)\n return sum(stone in jewelsSet for stone in stones)\n", | |
| "title": "771. Jewels and Stones", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 755 | |
| }, | |
| { | |
| "code": "class Solution:\n def calculate(self, s: str) -> int:\n nums = []\n ops = []\n\n def calc():\n b = nums.pop()\n a = nums.pop()\n op = ops.pop()\n if op == '+':\n nums.append(a + b)\n elif op == '-':\n nums.append(a - b)\n elif op == '*':\n nums.append(a * b)\n else: # op == '/'\n nums.append(int(a / b))\n\n def precedes(prev: str, curr: str) -> bool:\n \"\"\"\n Returns True if the previous character is a operator and the priority of\n the previous operator >= the priority of the current character (operator).\n \"\"\"\n if prev == '(':\n return False\n return prev in '*/' or curr in '+-'\n\n i = 0\n hasPrevNum = False\n\n while i < len(s):\n c = s[i]\n if c.isdigit():\n num = int(c)\n while i + 1 < len(s) and s[i + 1].isdigit():\n num = num * 10 + int(s[i + 1])\n i += 1\n nums.append(num)\n hasPrevNum = True\n elif c == '(':\n ops.append('(')\n hasPrevNum = False\n elif c == ')':\n while ops[-1] != '(':\n calc()\n ops.pop() # Pop '('\n elif c in '+-*/':\n if not hasPrevNum: # Handle input like \"-1-(-1)\"\n num.append(0)\n while ops and precedes(ops[-1], c):\n calc()\n ops.append(c)\n i += 1\n\n while ops:\n calc()\n\n return nums.pop()\n", | |
| "title": "772. Basic Calculator III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 756 | |
| }, | |
| { | |
| "code": "class Solution:\n def minmaxGasDist(self, stations: list[int], k: int) -> float:\n ERR = 1e-6\n l = 0\n r = stations[-1] - stations[0]\n\n def possible(k: int, m: float) -> bool:\n \"\"\"\n Returns True if can use <= k gas stations to ensure that each adjacent\n distance between gas stations <= m.\n \"\"\"\n for a, b in zip(stations, stations[1:]):\n diff = b - a\n if diff > m:\n k -= math.ceil(diff / m) - 1\n if k < 0:\n return False\n return True\n\n while r - l > ERR:\n m = (l + r) / 2\n if possible(k, m):\n r = m\n else:\n l = m\n\n return l\n", | |
| "title": "774. Minimize Max Distance to Gas Station", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 757 | |
| }, | |
| { | |
| "code": "class Solution:\n def isIdealPermutation(self, nums: list[int]) -> bool:\n for i, num in enumerate(nums):\n if abs(num - i) > 1:\n return False\n return True\n", | |
| "title": "775. Global and Local Inversions", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 758 | |
| }, | |
| { | |
| "code": "class Solution:\n def splitBST(self, root: TreeNode | None, target: int) -> list[TreeNode | None]:\n if not root:\n return None, None\n if root.val > target:\n left, right = self.splitBST(root.left, target)\n root.left = right\n return left, root\n else: # root.val <= target\n left, right = self.splitBST(root.right, target)\n root.right = left\n return root, right\n", | |
| "title": "776. Split BST", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 759 | |
| }, | |
| { | |
| "code": "class Solution:\n def canTransform(self, start: str, end: str) -> bool:\n if start.replace('X', '') != end.replace('X', ''):\n return False\n\n i = 0 # start's index\n j = 0 # end's index\n\n while i < len(start) and j < len(end):\n while i < len(start) and start[i] == 'X':\n i += 1\n while j < len(end) and end[j] == 'X':\n j += 1\n if i == len(start) and j == len(end):\n return True\n if i == len(start) or j == len(end):\n return False\n # L can only move to left.\n if start[i] == 'L' and i < j:\n return False\n # R can only move to right.\n if start[i] == 'R' and i > j:\n return False\n i += 1\n j += 1\n\n return True\n", | |
| "title": "777. Swap Adjacent in LR String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 760 | |
| }, | |
| { | |
| "code": "class Solution:\n def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:\n while sx < tx and sy < ty:\n tx, ty = tx % ty, ty % tx\n\n return (sx == tx and sy <= ty and (ty - sy) % tx == 0 or\n sy == ty and sx <= tx and (tx - sx) % ty == 0)\n", | |
| "title": "780. Reaching Points", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 761 | |
| }, | |
| { | |
| "code": "class Solution:\n def numRabbits(self, answers: list[int]) -> int:\n ans = 0\n count = collections.Counter()\n\n for answer in answers:\n if count[answer] % (answer + 1) == 0:\n ans += answer + 1\n count[answer] += 1\n\n return ans\n", | |
| "title": "781. Rabbits in Forest", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 762 | |
| }, | |
| { | |
| "code": "class Solution:\n def movesToChessboard(self, board: list[list[int]]) -> int:\n n = len(board)\n\n if any(board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]\n for i in range(n) for j in range(n)):\n return -1\n\n rowSum = sum(board[0])\n colSum = sum(board[i][0] for i in range(n))\n\n if rowSum != n // 2 and rowSum != (n + 1) // 2:\n return -1\n if colSum != n // 2 and colSum != (n + 1) // 2:\n return -1\n\n rowSwaps = sum(board[i][0] == (i & 1) for i in range(n))\n colSwaps = sum(board[0][i] == (i & 1) for i in range(n))\n\n if n % 2 == 1:\n if rowSwaps % 2 == 1:\n rowSwaps = n - rowSwaps\n if colSwaps % 2 == 1:\n colSwaps = n - colSwaps\n else:\n rowSwaps = min(rowSwaps, n - rowSwaps)\n colSwaps = min(colSwaps, n - colSwaps)\n\n return (rowSwaps + colSwaps) // 2\n", | |
| "title": "782. Transform to Chessboard", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 763 | |
| }, | |
| { | |
| "code": "from enum import Enum\n\n\nclass Color(Enum):\n WHITE = 0\n RED = 1\n GREEN = 2\n\n\nclass Solution:\n def isBipartite(self, graph: list[list[int]]) -> bool:\n colors = [Color.WHITE] * len(graph)\n\n def isValidColor(u: int, color: Color) -> bool:\n # The painted color should be same as `color`.\n if colors[u] != Color.WHITE:\n return colors[u] == color\n\n colors[u] = color\n\n # All the children should have valid colors.\n childrenColor = Color.RED if colors[u] == Color.GREEN else Color.GREEN\n return all(isValidColor(v, childrenColor) for v in graph[u])\n\n return all(colors[i] != Color.WHITE or isValidColor(i, Color.RED)\n for i in range(len(graph)))\n", | |
| "title": "785. Is Graph Bipartite?", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 764 | |
| }, | |
| { | |
| "code": "class Solution:\n def kthSmallestPrimeFraction(self, arr: list[int], k: int) -> list[int]:\n n = len(arr)\n ans = [0, 1]\n l = 0\n r = 1\n\n while True:\n m = (l + r) / 2\n ans[0] = 0\n count = 0\n j = 1\n\n for i in range(n):\n while j < n and arr[i] > m * arr[j]:\n j += 1\n count += n - j\n if j == n:\n break\n if ans[0] * arr[j] < ans[1] * arr[i]:\n ans[0] = arr[i]\n ans[1] = arr[j]\n\n if count < k:\n l = m\n elif count > k:\n r = m\n else:\n return ans\n", | |
| "title": "786. K-th Smallest Prime Fraction", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 765 | |
| }, | |
| { | |
| "code": "class Solution:\n def findCheapestPrice(\n self,\n n: int,\n flights: list[list[int]],\n src: int,\n dst: int,\n k: int,\n ) -> int:\n graph = [[] for _ in range(n)]\n\n for u, v, w in flights:\n graph[u].append((v, w))\n\n return self._dijkstra(graph, src, dst, k)\n\n def _dijkstra(\n self,\n graph: list[list[tuple[int, int]]],\n src: int,\n dst: int,\n k: int,\n ) -> int:\n dist = [[math.inf] * (k + 2) for _ in range(len(graph))]\n\n dist[src][k + 1] = 0\n minHeap = [(dist[src][k + 1], src, k + 1)] # (d, u, stops)\n\n while minHeap:\n d, u, stops = heapq.heappop(minHeap)\n if u == dst:\n return d\n if stops == 0 or d > dist[u][stops]:\n continue\n for v, w in graph[u]:\n if d + w < dist[v][stops - 1]:\n dist[v][stops - 1] = d + w\n heapq.heappush(minHeap, (dist[v][stops - 1], v, stops - 1))\n\n return -1\n", | |
| "title": "787. Cheapest Flights Within K Stops", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 766 | |
| }, | |
| { | |
| "code": "class Solution:\n def rotatedDigits(self, n: int) -> int:\n def isGoodNumber(i: int) -> bool:\n isRotated = False\n\n for c in str(i):\n if c == '0' or c == '1' or c == '8':\n continue\n if c == '2' or c == '5' or c == '6' or c == '9':\n isRotated = True\n else:\n return False\n\n return isRotated\n\n return sum(isGoodNumber(i) for i in range(1, n + 1))\n", | |
| "title": "788. Rotated Digits", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 767 | |
| }, | |
| { | |
| "code": "class Solution:\n def escapeGhosts(self, ghosts: list[list[int]], target: list[int]) -> bool:\n ghostSteps = min(abs(x - target[0]) +\n abs(y - target[1]) for x, y in ghosts)\n\n return abs(target[0]) + abs(target[1]) < ghostSteps\n", | |
| "title": "789. Escape The Ghosts", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 768 | |
| }, | |
| { | |
| "code": "class Solution:\n def numTilings(self, n: int) -> int:\n MOD = 1_000_000_007\n dp = [0, 1, 2, 5] + [0] * 997\n\n for i in range(4, n + 1):\n dp[i] = 2 * dp[i - 1] + dp[i - 3]\n\n return dp[n] % MOD\n", | |
| "title": "790. Domino and Tromino Tiling", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 769 | |
| }, | |
| { | |
| "code": "class Solution:\n def customSortString(self, order: str, s: str) -> str:\n ans = \"\"\n count = [0] * 26\n\n for c in s:\n count[ord(c) - ord('a')] += 1\n\n for c in order:\n while count[ord(c) - ord('a')] > 0:\n ans += c\n count[ord(c) - ord('a')] -= 1\n\n for c in string.ascii_lowercase:\n for _ in range(count[ord(c) - ord('a')]):\n ans += c\n\n return ans\n", | |
| "title": "791. Custom Sort String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 770 | |
| }, | |
| { | |
| "code": "class Solution:\n def numMatchingSubseq(self, s: str, words: list[str]) -> int:\n ans = 0\n # [(i, j)] := words[i] and the letter words[i][j] is waiting for\n bucket = [[] for _ in range(26)]\n\n # For each word, it's waiting for word[0].\n for i, word in enumerate(words):\n bucket[ord(word[0]) - ord('a')].append((i, 0))\n\n for c in s:\n # Let prevBucket = bucket[c] and clear bucket[c].\n index = ord(c) - ord('a')\n prevBucket = bucket[index]\n bucket[index] = []\n for i, j in prevBucket:\n j += 1\n if j == len(words[i]): # All the letters in words[i] are matched.\n ans += 1\n else:\n bucket[ord(words[i][j]) - ord('a')].append((i, j))\n\n return ans\n", | |
| "title": "792. Number of Matching Subsequences", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 771 | |
| }, | |
| { | |
| "code": "class Solution:\n def validTicTacToe(self, board: list[str]) -> bool:\n def isWin(c: str) -> bool:\n return (any(row.count(c) == 3 for row in board) or\n any(row.count(c) == 3 for row in list(zip(*board))) or\n all(board[i][i] == c for i in range(3)) or\n all(board[i][2 - i] == c for i in range(3)))\n\n countX = sum(row.count('X') for row in board)\n countO = sum(row.count('O') for row in board)\n\n if countX < countO or countX - countO > 1:\n return False\n if isWin('X') and countX == countO or isWin('O') and countX != countO:\n return False\n\n return True\n", | |
| "title": "794. Valid Tic-Tac-Toe State", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 772 | |
| }, | |
| { | |
| "code": "class Solution:\n def numSubarrayBoundedMax(\n self,\n nums: list[int],\n left: int,\n right: int,\n ) -> int:\n ans = 0\n l = -1\n r = -1\n\n for i, num in enumerate(nums):\n if num > right: # Handle the reset value.\n l = i\n if num >= left: # Handle the reset and the needed value.\n r = i\n ans += r - l\n\n return ans\n", | |
| "title": "795. Number of Subarrays with Bounded Maximum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 773 | |
| }, | |
| { | |
| "code": "class Solution:\n def rotateString(self, s: str, goal: str) -> bool:\n return len(s) == len(goal) and goal in s + s\n", | |
| "title": "796. Rotate String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 774 | |
| }, | |
| { | |
| "code": "class Solution:\n def allPathsSourceTarget(self, graph: list[list[int]]) -> list[list[int]]:\n ans = []\n\n def dfs(u: int, path: list[int]) -> None:\n if u == len(graph) - 1:\n ans.append(path)\n return\n\n for v in graph[u]:\n dfs(v, path + [v])\n\n dfs(0, [0])\n return ans\n", | |
| "title": "797. All Paths From Source to Target", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 775 | |
| }, | |
| { | |
| "code": "class Solution:\n def similarRGB(self, color: str) -> str:\n SHORTHANDS = ['00', '11', '22', '33', '44', '55', '66', '77', '88', '99',\n 'aa', 'bb', 'cc', 'dd', 'ee', 'ff']\n ans = ['#']\n\n for i in range(1, len(color), 2):\n currValue = int(color[i:i + 2], 16)\n closestShorthand = min(SHORTHANDS,\n key=lambda x: (currValue - int(x, 16))**2)\n ans.append(closestShorthand)\n\n return ''.join(ans)\n", | |
| "title": "800. Similar RGB Color", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 776 | |
| }, | |
| { | |
| "code": "class Solution:\n def minSwap(self, nums1: list[int], nums2: list[int]) -> int:\n keepAt = [math.inf] * len(nums1)\n swapAt = [math.inf] * len(nums1)\n keepAt[0] = 0\n swapAt[0] = 1\n\n for i in range(1, len(nums1)):\n if nums1[i] > nums1[i - 1] and nums2[i] > nums2[i - 1]:\n keepAt[i] = keepAt[i - 1]\n swapAt[i] = swapAt[i - 1] + 1\n if nums1[i] > nums2[i - 1] and nums2[i] > nums1[i - 1]:\n keepAt[i] = min(keepAt[i], swapAt[i - 1])\n swapAt[i] = min(swapAt[i], keepAt[i - 1] + 1)\n\n return min(keepAt[-1], swapAt[-1])\n", | |
| "title": "801. Minimum Swaps To Make Sequences Increasing", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 777 | |
| }, | |
| { | |
| "code": "from enum import Enum\n\n\nclass State(Enum):\n INIT = 0\n VISITING = 1\n VISITED = 2\n\n\nclass Solution:\n def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n states = [State.INIT] * len(graph)\n\n def hasCycle(u: int) -> bool:\n if states[u] == State.VISITING:\n return True\n if states[u] == State.VISITED:\n return False\n states[u] = State.VISITING\n if any(hasCycle(v) for v in graph[u]):\n return True\n states[u] = State.VISITED\n return False\n\n return [i for i in range(len(graph)) if not hasCycle(i)]\n", | |
| "title": "802. Find Eventual Safe States", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 778 | |
| }, | |
| { | |
| "code": "class Solution:\n def uniqueMorseRepresentations(self, words: list[str]) -> int:\n morse = [\".-\", \"-...\", \"-.-.\", \"-..\", \".\", \"..-.\", \"--.\", \"....\", \"..\",\n \".---\", \"-.-\", \".-..\", \"--\", \"-.\", \"---\", \".--.\", \"--.-\", \".-.\",\n \"...\", \"-\", \"..-\", \"...-\", \".--\", \"-..-\", \"-.--\", \"--..\"]\n transformations = set()\n\n for word in words:\n transformation = ''.join(\n morse[ord(c) - ord('a')] for c in word)\n transformations.add(transformation)\n\n return len(transformations)\n", | |
| "title": "804. Unique Morse Code Words", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 779 | |
| }, | |
| { | |
| "code": "class Solution:\n def splitArraySameAverage(self, nums: list[int]) -> bool:\n n = len(nums)\n summ = sum(nums)\n if not any(i * summ % n == 0 for i in range(1, n // 2 + 1)):\n return False\n\n sums = [set() for _ in range(n // 2 + 1)]\n sums[0].add(0)\n\n for num in nums:\n for i in range(n // 2, 0, -1):\n for val in sums[i - 1]:\n sums[i].add(num + val)\n\n for i in range(1, n // 2 + 1):\n if i * summ % n == 0 and i * summ // n in sums[i]:\n return True\n\n return False\n", | |
| "title": "805. Split Array With Same Average", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 780 | |
| }, | |
| { | |
| "code": "class Solution:\n def numberOfLines(self, widths: list[int], s: str) -> list[int]:\n numLines = 1\n runningWidth = 0\n\n for c in s:\n width = widths[ord(c) - ord('a')]\n if runningWidth + width <= 100:\n runningWidth += width\n else:\n numLines += 1\n runningWidth = width\n\n return [numLines, runningWidth]\n", | |
| "title": "806. Number of Lines To Write String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 781 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxIncreaseKeepingSkyline(self, grid: list[list[int]]) -> int:\n rowMax = list(map(max, grid))\n colMax = list(map(max, zip(*grid)))\n return sum(min(i, j) for i in rowMax for j in colMax) - sum(map(sum, grid))\n", | |
| "title": "807. Max Increase to Keep City Skyline", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 782 | |
| }, | |
| { | |
| "code": "class Solution:\n def soupServings(self, n: int) -> float:\n @functools.lru_cache(None)\n def dfs(a: int, b: int) -> float:\n if a <= 0 and b <= 0:\n return 0.5\n if a <= 0:\n return 1.0\n if b <= 0:\n return 0.0\n return 0.25 * (dfs(a - 4, b) +\n dfs(a - 3, b - 1) +\n dfs(a - 2, b - 2) +\n dfs(a - 1, b - 3))\n\n return 1 if n >= 4800 else dfs((n + 24) // 25, (n + 24) // 25)\n", | |
| "title": "808. Soup Servings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 783 | |
| }, | |
| { | |
| "code": "class Solution:\n def expressiveWords(self, s: str, words: list[str]) -> int:\n def isStretchy(word: str) -> bool:\n n = len(s)\n m = len(word)\n\n j = 0\n for i in range(n):\n if j < m and s[i] == word[j]:\n j += 1\n elif i > 1 and s[i] == s[i - 1] == s[i - 2]:\n continue\n elif 0 < i < n - 1 and s[i - 1] == s[i] == s[i + 1]:\n continue\n else:\n return False\n\n return j == m\n\n return sum(isStretchy(word) for word in words)\n", | |
| "title": "809. Expressive Words", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 784 | |
| }, | |
| { | |
| "code": "class Solution:\n def xorGame(self, nums: list[int]) -> bool:\n return functools.reduce(operator.xor, nums) == 0 or len(nums) % 2 == 0\n", | |
| "title": "810. Chalkboard XOR Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 785 | |
| }, | |
| { | |
| "code": "class Solution:\n def subdomainVisits(self, cpdomains: list[str]) -> list[str]:\n ans = []\n count = collections.Counter()\n\n for cpdomain in cpdomains:\n num, domains = cpdomain.split()\n num, domains = int(num), domains.split('.')\n for i in reversed(range(len(domains))):\n count['.'.join(domains[i:])] += num\n\n return [str(freq) + ' ' + domain for domain, freq in count.items()]\n", | |
| "title": "811. Subdomain Visit Count", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 786 | |
| }, | |
| { | |
| "code": "class Solution:\n def largestTriangleArea(self, points: list[list[int]]) -> float:\n ans = 0\n\n for Ax, Ay in points:\n for Bx, By in points:\n for Cx, Cy in points:\n ans = max(ans, 0.5 * abs((Bx - Ax) * (Cy - Ay) -\n (Cx - Ax) * (By - Ay)))\n\n return ans\n", | |
| "title": "812. Largest Triangle Area", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 787 | |
| }, | |
| { | |
| "code": "class Solution:\n def pruneTree(self, root: TreeNode | None) -> TreeNode | None:\n if not root:\n return None\n root.left = self.pruneTree(root.left)\n root.right = self.pruneTree(root.right)\n if not root.left and not root.right and not root.val:\n return None\n return root\n", | |
| "title": "814. Binary Tree Pruning", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 788 | |
| }, | |
| { | |
| "code": "class Solution:\n def numBusesToDestination(\n self,\n routes: list[list[int]],\n source: int,\n target: int,\n ) -> int:\n if source == target:\n return 0\n\n graph = collections.defaultdict(list)\n usedBuses = set()\n\n for i in range(len(routes)):\n for route in routes[i]:\n graph[route].append(i)\n\n q = collections.deque([source])\n\n step = 1\n while q:\n for _ in range(len(q)):\n for bus in graph[q.popleft()]:\n if bus in usedBuses:\n continue\n usedBuses.add(bus)\n for nextRoute in routes[bus]:\n if nextRoute == target:\n return step\n q.append(nextRoute)\n step += 1\n\n return -1\n", | |
| "title": "815. Bus Routes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 789 | |
| }, | |
| { | |
| "code": "class Solution:\n def ambiguousCoordinates(self, s: str) -> list[str]:\n def splits(s: str) -> list[str]:\n if not s or len(s) > 1 and s[0] == s[-1] == '0':\n return []\n if s[-1] == '0':\n return [s]\n if s[0] == '0':\n return [s[0] + '.' + s[1:]]\n return [s] + [s[:i] + '.' + s[i:] for i in range(1, len(s))]\n\n ans = []\n s = s[1:-1]\n\n for i in range(1, len(s)):\n for x in splits(s[:i]):\n for y in splits(s[i:]):\n ans.append('(%s, %s)' % (x, y))\n\n return ans\n", | |
| "title": "816. Ambiguous Coordinates", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 790 | |
| }, | |
| { | |
| "code": "class Solution:\n def numComponents(self, head: ListNode | None, nums: list[int]) -> int:\n ans = 0\n numsSet = set(nums)\n\n while head:\n if head.val in numsSet and (\n head.next == None or head.next.val not in numsSet):\n ans += 1\n head = head.next\n\n return ans\n", | |
| "title": "817. Linked List Components", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 791 | |
| }, | |
| { | |
| "code": "class Solution:\n def mostCommonWord(self, paragraph: str, banned: list[str]) -> str:\n banned = set(banned)\n words = re.findall(r'\\w+', paragraph.lower())\n return collections.Counter(\n word for word in words if word not in banned).most_common(1)[0][0]\n", | |
| "title": "819. Most Common Word", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 792 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: dict[str, TrieNode] = {}\n self.depth = 0\n\n\nclass Solution:\n def minimumLengthEncoding(self, words: list[str]) -> int:\n root = TrieNode()\n leaves = []\n\n def insert(word: str) -> TrieNode:\n node = root\n for c in reversed(word):\n node = node.children.setdefault(c, TrieNode())\n node.depth = len(word)\n return node\n\n for word in set(words):\n leaves.append(insert(word))\n\n return sum(leaf.depth + 1 for leaf in leaves\n if not len(leaf.children))\n", | |
| "title": "820. Short Encoding of Words", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 793 | |
| }, | |
| { | |
| "code": "class Solution:\n def shortestToChar(self, s: str, c: str) -> list[int]:\n n = len(s)\n ans = [0] * n\n prev = -n\n\n for i in range(n):\n if s[i] == c:\n prev = i\n ans[i] = i - prev\n\n for i in range(prev - 1, -1, -1):\n if s[i] == c:\n prev = i\n ans[i] = min(ans[i], prev - i)\n\n return ans\n", | |
| "title": "821. Shortest Distance to a Character", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 794 | |
| }, | |
| { | |
| "code": "class Solution:\n def flipgame(self, fronts: list[int], backs: list[int]) -> int:\n same = {front\n for front, back in zip(fronts, backs)\n if front == back}\n return min([num for num in fronts + backs\n if num not in same] or [0])\n", | |
| "title": "822. Card Flipping Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 795 | |
| }, | |
| { | |
| "code": "class Solution:\n def numFactoredBinaryTrees(self, arr: list[int]) -> int:\n MOD = 1_000_000_007\n n = len(arr)\n # dp[i] := the number of binary trees with arr[i] as the root\n dp = [1] * n\n arr.sort()\n numToIndex = {a: i for i, a in enumerate(arr)}\n\n for i, root in enumerate(arr): # arr[i] is the root\n for j in range(i):\n if root % arr[j] == 0: # arr[j] is the left subtree\n right = root // arr[j]\n if right in numToIndex:\n dp[i] += dp[j] * dp[numToIndex[right]]\n dp[i] %= MOD\n\n return sum(dp) % MOD\n", | |
| "title": "823. Binary Trees With Factors", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 796 | |
| }, | |
| { | |
| "code": "class Solution:\n def toGoatLatin(self, sentence: str) -> str:\n ans = []\n VOWELS = 'aeiouAEIOU'\n\n i = 1\n for word in sentence.split():\n if i > 1:\n ans.append(' ')\n if word[0] in VOWELS:\n ans.append(word)\n else:\n ans.append(word[1:] + word[0])\n ans.append('ma' + 'a' * i)\n i += 1\n\n return ''.join(ans)\n", | |
| "title": "824. Goat Latin", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 797 | |
| }, | |
| { | |
| "code": "class Solution:\n def numFriendRequests(self, ages: list[int]) -> int:\n ans = 0\n count = [0] * 121\n\n for age in ages:\n count[age] += 1\n\n for i in range(15, 121):\n ans += count[i] * (count[i] - 1)\n\n for i in range(15, 121):\n for j in range(i // 2 + 8, i):\n ans += count[i] * count[j]\n\n return ans\n", | |
| "title": "825. Friends Of Appropriate Ages", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 798 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxProfitAssignment(\n self,\n difficulty: list[int],\n profit: list[int],\n worker: list[int],\n ) -> int:\n ans = 0\n jobs = sorted(zip(difficulty, profit))\n worker.sort(reverse=1)\n\n i = 0\n maxProfit = 0\n\n for w in sorted(worker):\n while i < len(jobs) and w >= jobs[i][0]:\n maxProfit = max(maxProfit, jobs[i][1])\n i += 1\n ans += maxProfit\n\n return ans\n", | |
| "title": "826. Most Profit Assigning Work", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 799 | |
| }, | |
| { | |
| "code": "class Solution:\n def uniqueLetterString(self, s: str) -> int:\n ans = 0\n # lastSeen[c] := the index of the last time ('a' + i) appeared\n lastSeen = collections.defaultdict(lambda: -1)\n # prevSeen[c] := the previous index of the last time ('a' + i) appeared\n prevLastSeen = collections.defaultdict(lambda: -1)\n\n for i, c in enumerate(s):\n if c in lastSeen:\n ans += (i - lastSeen[c]) * (lastSeen[c] - prevLastSeen[c])\n prevLastSeen[c] = lastSeen[c]\n lastSeen[c] = i\n\n for c in string.ascii_uppercase:\n ans += (len(s) - lastSeen[c]) * (lastSeen[c] - prevLastSeen[c])\n\n return ans\n", | |
| "title": "828. Count Unique Characters of All Substrings of a Given String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 800 | |
| }, | |
| { | |
| "code": "class Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n ans = 0\n i = 1\n triangleNum = 1\n while triangleNum <= n:\n if (n - triangleNum) % i == 0:\n ans += 1\n i += 1\n triangleNum += i\n return ans\n", | |
| "title": "829. Consecutive Numbers Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 801 | |
| }, | |
| { | |
| "code": "class Solution:\n def largeGroupPositions(self, s: str) -> list[list[int]]:\n n = len(s)\n ans = []\n i = 0\n j = 0\n\n while i < n:\n while j < n and s[j] == s[i]:\n j += 1\n if j - i >= 3:\n ans.append([i, j - 1])\n i = j\n\n return ans\n", | |
| "title": "830. Positions of Large Groups", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 802 | |
| }, | |
| { | |
| "code": "class Solution:\n def maskPII(self, s: str) -> str:\n atIndex = s.find('@')\n if atIndex != -1:\n s = s.lower()\n return s[0] + '*' * 5 + s[atIndex - 1:]\n\n ans = ''.join(c for c in s if c.isdigit())\n\n if len(ans) == 10:\n return '***-***-' + ans[-4:]\n return '+' + '*' * (len(ans) - 10) + '-***-***-' + ans[-4:]\n", | |
| "title": "831. Masking Personal Information", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 803 | |
| }, | |
| { | |
| "code": "class Solution:\n def flipAndInvertImage(self, A: list[list[int]]) -> list[list[int]]:\n n = len(A)\n\n for i in range(n):\n for j in range((n + 2) // 2):\n A[i][j], A[i][n - j - 2] = A[i][n - j - 1] ^ 2, A[i][j] ^ 1\n\n return A\n", | |
| "title": "832. Flipping an Image", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 804 | |
| }, | |
| { | |
| "code": "class Solution:\n def findReplaceString(\n self,\n s: str,\n indices: list[int],\n sources: list[str],\n targets: list[str]\n ) -> str:\n for index, source, target in sorted(zip(indices, sources, targets),\n reverse=True):\n if s[index:index + len(source)] == source:\n s = s[:index] + target + s[index + len(source):]\n return s\n", | |
| "title": "833. Find And Replace in String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 805 | |
| }, | |
| { | |
| "code": "class Solution:\n def sumOfDistancesInTree(self, n: int, edges: list[list[int]]) -> list[int]:\n ans = [0] * n\n count = [1] * n\n tree = [set() for _ in range(n)]\n\n for u, v in edges:\n tree[u].add(v)\n tree[v].add(u)\n\n def postorder(u: int, prev: int) -> None:\n for v in tree[u]:\n if v == prev:\n continue\n postorder(v, u)\n count[u] += count[v]\n ans[u] += ans[v] + count[v]\n\n def preorder(u: int, prev: int) -> None:\n for v in tree[u]:\n if v == prev:\n continue\n # count[v] us are 1 step closer from v than prev.\n # (n - count[v]) us are 1 step farther from v than prev.\n ans[v] = ans[u] - count[v] + (n - count[v])\n preorder(v, u)\n\n postorder(0, -1)\n preorder(0, -1)\n return ans\n", | |
| "title": "834. Sum of Distances in Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 806 | |
| }, | |
| { | |
| "code": "class Solution:\n def largestOverlap(self, img1: list[list[int]], img2: list[list[int]]) -> int:\n MAGIC = 100\n ones1 = [(i, j)\n for i, row in enumerate(img1)\n for j, num in enumerate(row)\n if num == 1]\n ones2 = [(i, j)\n for i, row in enumerate(img2)\n for j, num in enumerate(row)\n if num == 1]\n offsetCount = collections.Counter()\n\n for ax, ay in ones1:\n for bx, by in ones2:\n offsetCount[(ax - bx) * MAGIC + (ay - by)] += 1\n\n return max(offsetCount.values()) if offsetCount else 0\n", | |
| "title": "835. Image Overlap", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 807 | |
| }, | |
| { | |
| "code": "class Solution:\n def isRectangleOverlap(self, rec1: list[int], rec2: list[int]) -> bool:\n return rec1[0] < rec2[2] and rec2[0] < rec1[2] and rec1[1] < rec2[3] and rec2[1] < rec1[3]\n", | |
| "title": "836. Rectangle Overlap", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 808 | |
| }, | |
| { | |
| "code": "class Solution:\n def new21Game(self, n: int, k: int, maxPts: int) -> float:\n # When the game ends, the point is in [k..k - 1 maxPts].\n # P = 1, if n >= k - 1 + maxPts\n # P = 0, if n < k (note that the constraints already have k <= n)\n if k == 0 or n >= k - 1 + maxPts:\n return 1.0\n\n ans = 0.0\n dp = [1.0] + [0] * n # dp[i] := the probability to have i points\n windowSum = dp[0] # P(i - 1) + P(i - 2) + ... + P(i - maxPts)\n\n for i in range(1, n + 1):\n # The probability to get i points is\n # P(i) = [P(i - 1) + P(i - 2) + ... + P(i - maxPts)] / maxPts\n dp[i] = windowSum / maxPts\n if i < k:\n windowSum += dp[i]\n else: # The game ends.\n ans += dp[i]\n if i - maxPts >= 0:\n windowSum -= dp[i - maxPts]\n\n return ans\n", | |
| "title": "837. New 21 Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 809 | |
| }, | |
| { | |
| "code": "class Solution:\n def pushDominoes(self, dominoes: str) -> str:\n ans = list(dominoes)\n L = -1\n R = -1\n\n for i in range(len(dominoes) + 1):\n if i == len(dominoes) or dominoes[i] == 'R':\n if L < R:\n while R < i:\n ans[R] = 'R'\n R += 1\n R = i\n elif dominoes[i] == 'L':\n if R < L or (L, R) == (-1, -1):\n if (L, R) == (-1, -1):\n L += 1\n while L < i:\n ans[L] = 'L'\n L += 1\n else:\n l = R + 1\n r = i - 1\n while l < r:\n ans[l] = 'R'\n ans[r] = 'L'\n l += 1\n r -= 1\n L = i\n\n return ''.join(ans)\n", | |
| "title": "838. Push Dominoes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 810 | |
| }, | |
| { | |
| "code": "class Solution:\n def numMagicSquaresInside(self, grid: list[list[int]]) -> int:\n def isMagic(i: int, j: int) -> int:\n s = \"\".join(str(grid[i + num // 3][j + num % 3])\n for num in [0, 1, 2, 5, 8, 7, 6, 3])\n return s in \"43816729\" * 2 or s in \"43816729\"[::-1] * 2\n\n ans = 0\n\n for i in range(len(grid) - 2):\n for j in range(len(grid[0]) - 2):\n if grid[i][j] % 2 == 0 and grid[i + 1][j + 1] == 5:\n ans += isMagic(i, j)\n\n return ans\n", | |
| "title": "840. Magic Squares In Grid", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 811 | |
| }, | |
| { | |
| "code": "class Solution:\n def canVisitAllRooms(self, rooms: list[list[int]]) -> bool:\n seen = [False] * len(rooms)\n\n def dfs(node: int) -> None:\n seen[node] = True\n for child in rooms[node]:\n if not seen[child]:\n dfs(child)\n\n dfs(0)\n return all(seen)\n", | |
| "title": "841. Keys and Rooms", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 812 | |
| }, | |
| { | |
| "code": "# \"\"\"\n# This is Master's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n# Class Master:\n# def guess(self, word: str) -> int:\n\nclass Solution:\n def findSecretWord(self, words: list[str], master: 'Master') -> None:\n for _ in range(10):\n guessedWord = words[random.randint(0, len(words) - 1)]\n matches = master.guess(guessedWord)\n if matches == 6:\n break\n words = [\n word for word in words\n if sum(c1 == c2 for c1, c2 in zip(guessedWord, word)) == matches]\n", | |
| "title": "843. Guess the Word", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 813 | |
| }, | |
| { | |
| "code": "class Solution:\n def backspaceCompare(self, s: str, t: str) -> bool:\n i = len(s) - 1 # s' index\n j = len(t) - 1 # t's index\n\n while True:\n # Delete characters of s if needed.\n backspace = 0\n while i >= 0 and (s[i] == '#' or backspace > 0):\n backspace += 1 if s[i] == '#' else -1\n i -= 1\n # Delete characters of t if needed.\n backspace = 0\n while j >= 0 and (t[j] == '#' or backspace > 0):\n backspace += 1 if t[j] == '#' else -1\n j -= 1\n if i >= 0 and j >= 0 and s[i] == t[j]:\n i -= 1\n j -= 1\n else:\n break\n\n return i == -1 and j == -1\n", | |
| "title": "844. Backspace String Compare", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 814 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestMountain(self, arr: list[int]) -> int:\n ans = 0\n i = 0\n\n while i + 1 < len(arr):\n while i + 1 < len(arr) and arr[i] == arr[i + 1]:\n i += 1\n\n increasing = 0\n decreasing = 0\n\n while i + 1 < len(arr) and arr[i] < arr[i + 1]:\n increasing += 1\n i += 1\n\n while i + 1 < len(arr) and arr[i] > arr[i + 1]:\n decreasing += 1\n i += 1\n\n if increasing > 0 and decreasing > 0:\n ans = max(ans, increasing + decreasing + 1)\n\n return ans\n", | |
| "title": "845. Longest Mountain in Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 815 | |
| }, | |
| { | |
| "code": "class Solution:\n def isNStraightHand(self, hand: list[int], groupSize: int) -> bool:\n count = collections.Counter(hand)\n\n for start in sorted(count):\n value = count[start]\n if value > 0:\n for i in range(start, start + groupSize):\n count[i] -= value\n if count[i] < 0:\n return False\n\n return True\n", | |
| "title": "846. Hand of Straights", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 816 | |
| }, | |
| { | |
| "code": "class Solution:\n def shortestPathLength(self, graph: list[list[int]]) -> int:\n n = len(graph)\n goal = (1 << n) - 1\n q = collections.deque() # (u, state)\n seen = set()\n\n for i in range(n):\n q.append((i, 1 << i))\n\n step = 0\n while q:\n for _ in range(len(q)):\n u, state = q.popleft()\n if state == goal:\n return step\n if (u, state) in seen:\n continue\n seen.add((u, state))\n for v in graph[u]:\n q.append((v, state | 1 << v))\n step += 1\n\n return -1\n", | |
| "title": "847. Shortest Path Visiting All Nodes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 817 | |
| }, | |
| { | |
| "code": "class Solution:\n def shiftingLetters(self, s: str, shifts: list[int]) -> str:\n ans = []\n\n for i in reversed(range(len(shifts) - 1)):\n shifts[i] += shifts[i + 1]\n\n for c, shift in zip(s, shifts):\n ans.append(chr((ord(c) - ord('a') + shift) % 26 + ord('a')))\n\n return ''.join(ans)\n", | |
| "title": "848. Shifting Letters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 818 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxDistToClosest(self, seats: list[int]) -> int:\n n = len(seats)\n ans = 0\n j = -1\n\n for i in range(n):\n if seats[i] == 1:\n ans = i if j == -1 else max(ans, (i - j) // 2)\n j = i\n\n return max(ans, n - j - 1)\n", | |
| "title": "849. Maximize Distance to Closest Person", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 819 | |
| }, | |
| { | |
| "code": "class Solution:\n def rectangleArea(self, rectangles: list[list[int]]) -> int:\n events = []\n\n for x1, y1, x2, y2 in rectangles:\n events.append((x1, y1, y2, 's'))\n events.append((x2, y1, y2, 'e'))\n\n events.sort(key=lambda x: x[0])\n\n ans = 0\n prevX = 0\n yPairs = []\n\n def getHeight(yPairs: list[tuple[int, int]]) -> int:\n height = 0\n prevY = 0\n\n for y1, y2 in yPairs:\n prevY = max(prevY, y1)\n if y2 > prevY:\n height += y2 - prevY\n prevY = y2\n\n return height\n\n for currX, y1, y2, type in events:\n if currX > prevX:\n width = currX - prevX\n ans += width * getHeight(yPairs)\n prevX = currX\n if type == 's':\n yPairs.append((y1, y2))\n yPairs.sort()\n else: # type == 'e'\n yPairs.remove((y1, y2))\n\n return ans % (10**9 + 7)\n", | |
| "title": "850. Rectangle Area II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 820 | |
| }, | |
| { | |
| "code": "class Solution:\n def loudAndRich(self, richer: list[list[int]], quiet: list[int]) -> list[int]:\n graph = [[] for _ in range(len(quiet))]\n\n for v, u in richer:\n graph[u].append(v)\n\n @functools.lru_cache(None)\n def dfs(u: int) -> int:\n ans = u\n\n for v in graph[u]:\n res = dfs(v)\n if quiet[res] < quiet[ans]:\n ans = res\n\n return ans\n\n return map(dfs, range(len(graph)))\n", | |
| "title": "851. Loud and Rich", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 821 | |
| }, | |
| { | |
| "code": "class Solution:\n def peakIndexInMountainArray(self, arr: list[int]) -> int:\n l = 0\n r = len(arr) - 1\n\n while l < r:\n m = (l + r) // 2\n if arr[m] >= arr[m + 1]:\n r = m\n else:\n l = m + 1\n\n return l\n", | |
| "title": "852. Peak Index in a Mountain Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 822 | |
| }, | |
| { | |
| "code": "class Solution:\n def carFleet(self, target: int, position: list[int], speed: list[int]) -> int:\n ans = 0\n times = [\n float(target - p) / s for p, s in sorted(zip(position, speed),\n reverse=True)]\n maxTime = 0 # the time of the slowest car to reach the target\n\n for time in times:\n # A car needs more time to reach the target, so it becomes the slowest.\n if time > maxTime:\n maxTime = time\n ans += 1\n\n return ans\n", | |
| "title": "853. Car Fleet", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 823 | |
| }, | |
| { | |
| "code": "class Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n q = collections.deque([s1])\n seen = {s1}\n\n step = 0\n while q:\n for _ in range(len(q)):\n curr = q.popleft()\n if curr == s2:\n return step\n for child in self._getChildren(curr, s2):\n if child in seen:\n continue\n q.append(child)\n seen.add(child)\n step += 1\n\n return -1\n\n def _getChildren(self, curr: str, target: str) -> list[str]:\n children = []\n s = list(curr)\n i = 0 # the first index s.t. curr[i] != target[i]\n while curr[i] == target[i]:\n i += 1\n\n for j in range(i + 1, len(s)):\n if s[j] == target[i]:\n s[i], s[j] = s[j], s[i]\n children.append(''.join(s))\n s[i], s[j] = s[j], s[i]\n\n return children\n", | |
| "title": "854. K-Similar Strings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 824 | |
| }, | |
| { | |
| "code": "class Solution:\n def scoreOfParentheses(self, s: str) -> int:\n ans = 0\n layer = 0\n\n for a, b in itertools.pairwise(s):\n if a + b == '()':\n ans += 1 << layer\n layer += 1 if a == '(' else -1\n\n return ans\n", | |
| "title": "856. Score of Parentheses", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 825 | |
| }, | |
| { | |
| "code": "class Solution:\n def mincostToHireWorkers(\n self,\n quality: list[int],\n wage: list[int],\n k: int,\n ) -> float:\n ans = math.inf\n qualitySum = 0\n # (wagePerQuality, quality) sorted by wagePerQuality\n workers = sorted((w / q, q) for q, w in zip(quality, wage))\n maxHeap = []\n\n for wagePerQuality, q in workers:\n heapq.heappush(maxHeap, -q)\n qualitySum += q\n if len(maxHeap) > k:\n qualitySum += heapq.heappop(maxHeap)\n if len(maxHeap) == k:\n ans = min(ans, qualitySum * wagePerQuality)\n\n return ans\n", | |
| "title": "857. Minimum Cost to Hire K Workers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 826 | |
| }, | |
| { | |
| "code": "class Solution:\n def mirrorReflection(self, p: int, q: int) -> int:\n while p % 2 == 0 and q % 2 == 0:\n p //= 2\n q //= 2\n\n if p % 2 == 0:\n return 2\n if q % 2 == 0:\n return 0\n return 1\n", | |
| "title": "858. Mirror Reflection", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 827 | |
| }, | |
| { | |
| "code": "class Solution:\n def buddyStrings(self, s: str, goal: str) -> bool:\n if len(s) != len(goal):\n return False\n if s == goal and len(set(s)) < len(s):\n return True\n diffIndices = [i for i, (a, b) in enumerate(zip(s, goal))\n if a != b]\n return (len(diffIndices) == 2 and\n s[diffIndices[0]] == goal[diffIndices[1]] and\n s[diffIndices[1]] == goal[diffIndices[0]])\n", | |
| "title": "859. Buddy Strings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 828 | |
| }, | |
| { | |
| "code": "class Solution:\n def lemonadeChange(self, bills: list[int]) -> bool:\n fives = 0\n tens = 0\n\n for bill in bills:\n if bill == 5:\n fives += 1\n elif bill == 10:\n fives -= 1\n tens += 1\n else: # bill == 20\n if tens > 0:\n tens -= 1\n fives -= 1\n else:\n fives -= 3\n if fives < 0:\n return False\n\n return True\n", | |
| "title": "860. Lemonade Change", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 829 | |
| }, | |
| { | |
| "code": "class Solution:\n def matrixScore(self, grid: list[list[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n ans = m # All the cells in the first column are 1.\n\n for j in range(1, n):\n # The best strategy is flipping the rows with a leading 0..\n onesCount = sum(grid[i][j] == grid[i][0] for i in range(m))\n ans = ans * 2 + max(onesCount, m - onesCount)\n\n return ans\n", | |
| "title": "861. Score After Flipping Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 830 | |
| }, | |
| { | |
| "code": "class Solution:\n def shortestSubarray(self, nums: list[int], k: int) -> int:\n n = len(nums)\n ans = n + 1\n dq = collections.deque()\n prefix = list(itertools.accumulate(nums, initial=0))\n\n for i in range(n + 1):\n while dq and prefix[i] - prefix[dq[0]] >= k:\n ans = min(ans, i - dq.popleft())\n while dq and prefix[i] <= prefix[dq[-1]]:\n dq.pop()\n dq.append(i)\n\n return ans if ans <= n else -1\n", | |
| "title": "862. Shortest Subarray with Sum at Least K", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 831 | |
| }, | |
| { | |
| "code": "class Solution:\n def primePalindrome(self, n: int) -> int:\n def getPalindromes(n: int) -> int:\n length = n // 2\n for i in range(10**(length - 1), 10**length):\n s = str(i)\n for j in range(10):\n yield int(s + str(j) + s[::-1])\n\n def isPrime(num: int) -> bool:\n return not any(num % i == 0 for i in range(2, int(num**0.5 + 1)))\n\n if n <= 2:\n return 2\n if n == 3:\n return 3\n if n <= 5:\n return 5\n if n <= 7:\n return 7\n if n <= 11:\n return 11\n\n nLength = len(str(n))\n\n while True:\n for num in getPalindromes(nLength):\n if num >= n and isPrime(num):\n return num\n nLength += 1\n", | |
| "title": "866. Prime Palindrome", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 832 | |
| }, | |
| { | |
| "code": "class Solution:\n def transpose(self, A: list[list[int]]) -> list[list[int]]:\n ans = [[0] * len(A) for _ in range(len(A[0]))]\n\n for i in range(len(A)):\n for j in range(len(A[0])):\n ans[j][i] = A[i][j]\n\n return ans\n", | |
| "title": "867. Transpose Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 833 | |
| }, | |
| { | |
| "code": "class Solution:\n def binaryGap(self, n: int) -> int:\n ans = 0\n d = -32 # the distance between any two 1s\n\n while n:\n if n % 2 == 1:\n ans = max(ans, d)\n d = 0\n n //= 2\n d += 1\n\n return ans\n", | |
| "title": "868. Binary Gap", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 834 | |
| }, | |
| { | |
| "code": "class Solution:\n def reorderedPowerOf2(self, n: int) -> bool:\n count = collections.Counter(str(n))\n return any(Counter(str(1 << i)) == count for i in range(30))\n", | |
| "title": "869. Reordered Power of 2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 835 | |
| }, | |
| { | |
| "code": "from sortedcontainers import SortedList\n\n\nclass Solution:\n def advantageCount(self, nums1: list[int], nums2: list[int]) -> list[int]:\n sl = SortedList(nums1)\n\n for i, num in enumerate(nums2):\n index = 0 if sl[-1] <= num else sl.bisect_right(num)\n nums1[i] = sl[index]\n del sl[index]\n\n return nums1\n", | |
| "title": "870. Advantage Shuffle", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 836 | |
| }, | |
| { | |
| "code": "class Solution:\n def minRefuelStops(\n self,\n target: int,\n startFuel: int,\n stations: list[list[int]],\n ) -> int:\n ans = 0\n i = 0 # station's index\n curr = startFuel\n maxHeap = []\n\n while curr < target:\n # Add all the reachable stops to maxHeap\n while i < len(stations) and stations[i][0] <= curr:\n heapq.heappush(maxHeap, -stations[i][1])\n i += 1\n if not maxHeap: # Can't be refueled.\n return -1\n curr -= heapq.heappop(maxHeap) # Pop out the largest gas.\n ans += 1 # Then, refuel once.\n\n return ans\n", | |
| "title": "871. Minimum Number of Refueling Stops", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 837 | |
| }, | |
| { | |
| "code": "class Solution:\n def leafSimilar(self, root1: TreeNode | None, root2: TreeNode | None) -> bool:\n def dfs(root: TreeNode | None) -> None:\n if not root:\n return\n if not root.left and not root.right:\n yield root.val\n return\n\n yield from dfs(root.left)\n yield from dfs(root.right)\n\n return list(dfs(root1)) == list(dfs(root2))\n", | |
| "title": "872. Leaf-Similar Trees", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 838 | |
| }, | |
| { | |
| "code": "class Solution:\n def lenLongestFibSubseq(self, arr: list[int]) -> int:\n n = len(arr)\n ans = 0\n numToIndex = {a: i for i, a in enumerate(arr)}\n dp = [[2] * n for _ in range(n)]\n\n for j in range(n):\n for k in range(j + 1, n):\n ai = arr[k] - arr[j]\n if ai < arr[j] and ai in numToIndex:\n i = numToIndex[ai]\n dp[j][k] = dp[i][j] + 1\n ans = max(ans, dp[j][k])\n\n return ans\n", | |
| "title": "873. Length of Longest Fibonacci Subsequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 839 | |
| }, | |
| { | |
| "code": "class Solution:\n def robotSim(self, commands: list[int], obstacles: list[list[int]]) -> int:\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n ans = 0\n d = 0 # 0 := north, 1 := east, 2 := south, 3 := west\n x = 0 # the start x\n y = 0 # the start y\n obstaclesSet = {(x, y) for x, y in obstacles}\n\n for command in commands:\n if command == -1:\n d = (d + 1) % 4\n elif command == -2:\n d = (d + 3) % 4\n else:\n for _ in range(command):\n if (x + DIRS[d][0], y + DIRS[d][1]) in obstaclesSet:\n break\n x += DIRS[d][0]\n y += DIRS[d][1]\n ans = max(ans, x * x + y * y)\n\n return ans\n", | |
| "title": "874. Walking Robot Simulation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 840 | |
| }, | |
| { | |
| "code": "class Solution:\n def minEatingSpeed(self, piles: list[int], h: int) -> int:\n def eatHours(m: int) -> bool:\n \"\"\"Returns the hours to eat all the piles with speed m.\"\"\"\n return sum((pile - 1) // m + 1 for pile in piles)\n l = 1\n r = max(piles)\n return bisect.bisect_left(range(l, r), True,\n key=lambda m: eatHours(m) <= h) + l\n", | |
| "title": "875. Koko Eating Bananas", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 841 | |
| }, | |
| { | |
| "code": "class Solution:\n def middleNode(self, head: ListNode) -> ListNode:\n slow = head\n fast = head\n\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n\n return slow\n", | |
| "title": "876. Middle of the Linked List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 842 | |
| }, | |
| { | |
| "code": "class Solution:\n def stoneGame(self, piles: list[int]) -> bool:\n n = len(piles)\n dp = piles.copy()\n\n for d in range(1, n):\n for j in range(n - 1, d - 1, -1):\n i = j - d\n dp[j] = max(piles[i] - dp[j], piles[j] - dp[j - 1])\n\n return dp[n - 1] > 0\n", | |
| "title": "877. Stone Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 843 | |
| }, | |
| { | |
| "code": "class Solution:\n def nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n lcm = a * b // math.gcd(a, b)\n l = min(a, b)\n r = min(a, b) * n\n ans = bisect.bisect_left(range(l, r), n,\n key=lambda m: m // a + m // b - m // lcm) + l\n return ans % (10**9 + 7)\n", | |
| "title": "878. Nth Magical Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 844 | |
| }, | |
| { | |
| "code": "class Solution:\n def decodeAtIndex(self, s: str, k: int) -> str:\n size = 0\n\n for c in s:\n if c.isdigit():\n size *= int(c)\n else:\n size += 1\n\n for c in reversed(s):\n k %= size\n if k == 0 and c.isalpha():\n return c\n if c.isdigit():\n size //= int(c)\n else:\n size -= 1\n", | |
| "title": "880. Decoded String at Index", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 845 | |
| }, | |
| { | |
| "code": "class Solution:\n def numRescueBoats(self, people: list[int], limit: int) -> int:\n ans = 0\n i = 0\n j = len(people) - 1\n\n people.sort()\n\n while i <= j:\n remain = limit - people[j]\n j -= 1\n if people[i] <= remain:\n i += 1\n ans += 1\n\n return ans\n", | |
| "title": "881. Boats to Save People", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 846 | |
| }, | |
| { | |
| "code": "class Solution:\n def reachableNodes(\n self,\n edges: list[list[int]],\n maxMoves: int,\n n: int,\n ) -> int:\n graph = [[] for _ in range(n)]\n dist = [maxMoves + 1] * n\n\n for u, v, cnt in edges:\n graph[u].append((v, cnt))\n graph[v].append((u, cnt))\n\n reachableNodes = self._dijkstra(graph, 0, maxMoves, dist)\n reachableSubnodes = 0\n\n for u, v, cnt in edges:\n # the number of reachable nodes of (u, v) from `u`\n a = 0 if dist[u] > maxMoves else min(maxMoves - dist[u], cnt)\n # the number of reachable nodes of (u, v) from `v`\n b = 0 if dist[v] > maxMoves else min(maxMoves - dist[v], cnt)\n reachableSubnodes += min(a + b, cnt)\n\n return reachableNodes + reachableSubnodes\n\n def _dijkstra(\n self,\n graph: list[list[tuple[int, int]]],\n src: int,\n maxMoves: int,\n dist: list[int],\n ) -> int:\n dist[src] = 0\n minHeap = [(dist[src], src)] # (d, u)\n\n while minHeap:\n d, u = heapq.heappop(minHeap)\n # Already took `maxMoves` to reach `u`, so can't explore anymore.\n if dist[u] >= maxMoves:\n break\n if d > dist[u]:\n continue\n for v, w in graph[u]:\n newDist = d + w + 1\n if newDist < dist[v]:\n dist[v] = newDist\n heapq.heappush(minHeap, (newDist, v))\n\n return sum(d <= maxMoves for d in dist)\n", | |
| "title": "882. Reachable Nodes In Subdivided Graph", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 847 | |
| }, | |
| { | |
| "code": "class Solution:\n def projectionArea(self, grid: list[list[int]]) -> int:\n return sum(\n a > 0 for row in grid for a in row) + sum(\n max(row) for row in grid) + sum(\n max(col) for col in zip(*grid))\n", | |
| "title": "883. Projection Area of 3D Shapes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 848 | |
| }, | |
| { | |
| "code": "class Solution:\n def uncommonFromSentences(self, A: str, B: str) -> list[str]:\n count = collections.Counter((A + ' ' + B).split())\n return [word for word, freq in count.items() if freq == 1]\n", | |
| "title": "884. Uncommon Words from Two Sentences", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 849 | |
| }, | |
| { | |
| "code": "class Solution:\n def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> list[list[int]]:\n dx = [1, 0, -1, 0]\n dy = [0, 1, 0, -1]\n ans = [[rStart, cStart]]\n i = 0\n\n while len(ans) < rows * cols:\n for _ in range(i // 2 + 1):\n rStart += dy[i % 4]\n cStart += dx[i % 4]\n if 0 <= rStart < rows and 0 <= cStart < cols:\n ans.append([rStart, cStart])\n i += 1\n\n return ans\n", | |
| "title": "885. Spiral Matrix III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 850 | |
| }, | |
| { | |
| "code": "from enum import Enum\n\n\nclass Color(Enum):\n WHITE = 0\n RED = 1\n GREEN = 2\n\n\nclass Solution:\n def possibleBipartition(self, n: int, dislikes: list[list[int]]) -> bool:\n graph = [[] for _ in range(n + 1)]\n colors = [Color.WHITE] * (n + 1)\n\n for u, v in dislikes:\n graph[u].append(v)\n graph[v].append(u)\n\n # Reduce to 785. Is Graph Bipartite?\n def isValidColor(u: int, color: Color) -> bool:\n # Always paint red for a white node.\n if colors[u] != Color.WHITE:\n return colors[u] == color\n\n colors[u] = color # Always paint the node with `color`.\n\n # All the children should have valid colors.\n childrenColor = Color.RED if colors[u] == Color.GREEN else Color.GREEN\n return all(isValidColor(v, childrenColor) for v in graph[u])\n\n return all(colors[i] != Color.WHITE or isValidColor(i, Color.RED)\n for i in range(1, n + 1))\n", | |
| "title": "886. Possible Bipartition", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 851 | |
| }, | |
| { | |
| "code": "class Solution:\n def superEggDrop(self, k: int, n: int) -> int:\n moves = 0\n dp = [[0] * (k + 1) for _ in range(n + 1)]\n\n while dp[moves][k] < n:\n moves += 1\n for eggs in range(1, k + 1):\n dp[moves][eggs] = (dp[moves - 1][eggs - 1] +\n dp[moves - 1][eggs] + 1)\n\n return moves\n", | |
| "title": "887. Super Egg Drop", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 852 | |
| }, | |
| { | |
| "code": "class Solution:\n def fairCandySwap(\n self,\n aliceSizes: list[int],\n bobSizes: list[int],\n ) -> list[int]:\n diff = (sum(aliceSizes) - sum(bobSizes)) // 2\n bobSizesSet = set(bobSizes)\n\n for aliceSize in aliceSizes:\n target = aliceSize - diff\n if target in bobSizesSet:\n return [aliceSize, target]\n", | |
| "title": "888. Fair Candy Swap", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 853 | |
| }, | |
| { | |
| "code": "class Solution:\n def constructFromPrePost(\n self,\n pre: list[int],\n post: list[int],\n ) -> TreeNode | None:\n postToIndex = {num: i for i, num in enumerate(post)}\n\n def build(preStart: int, preEnd: int, postStart: int, postEnd: int) -> TreeNode | None:\n if preStart > preEnd:\n return None\n if preStart == preEnd:\n return TreeNode(pre[preStart])\n\n rootVal = pre[preStart]\n leftRootVal = pre[preStart + 1]\n leftRootPostIndex = postToIndex[leftRootVal]\n leftSize = leftRootPostIndex - postStart + 1\n\n root = TreeNode(rootVal)\n root.left = build(preStart + 1, preStart + leftSize,\n postStart, leftRootPostIndex)\n root.right = build(preStart + leftSize + 1, preEnd,\n leftRootPostIndex + 1, postEnd - 1)\n return root\n\n return build(0, len(pre) - 1, 0, len(post) - 1)\n", | |
| "title": "889. Construct Binary Tree from Preorder and Postorder Traversal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 854 | |
| }, | |
| { | |
| "code": "class Solution:\n def findAndReplacePattern(self, words: list[str], pattern: str) -> list[str]:\n def isIsomorphic(w: str, p: str) -> bool:\n return [*map(w.index, w)] == [*map(p.index, p)]\n return [word for word in words if isIsomorphic(word, pattern)]\n", | |
| "title": "890. Find and Replace Pattern", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 855 | |
| }, | |
| { | |
| "code": "class Solution:\n def sumSubseqWidths(self, nums: list[int]) -> int:\n MOD = 1_000_000_007\n n = len(nums)\n ans = 0\n exp = 1\n\n nums.sort()\n\n for i in range(n):\n ans += (nums[i] - nums[n - 1 - i]) * exp\n ans %= MOD\n exp = exp * 2 % MOD\n\n return ans\n", | |
| "title": "891. Sum of Subsequence Widths", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 856 | |
| }, | |
| { | |
| "code": "class Solution:\n def surfaceArea(self, grid: list[list[int]]) -> int:\n ans = 0\n\n for i in range(len(grid)):\n for j in range(len(grid)):\n if grid[i][j]:\n ans += grid[i][j] * 4 + 2\n if i > 0:\n ans -= min(grid[i][j], grid[i - 1][j]) * 2\n if j > 0:\n ans -= min(grid[i][j], grid[i][j - 1]) * 2\n\n return ans\n", | |
| "title": "892. Surface Area of 3D Shapes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 857 | |
| }, | |
| { | |
| "code": "class Solution:\n def numSpecialEquivGroups(self, words: list[str]) -> int:\n return len({''.join(sorted(word[::2])) + ''.join(sorted(word[1::2]))\n for word in words})\n", | |
| "title": "893. Groups of Special-Equivalent Strings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 858 | |
| }, | |
| { | |
| "code": "class Solution:\n @functools.lru_cache(None)\n def allPossibleFBT(self, n: int) -> list[TreeNode | None]:\n if n % 2 == 0:\n return []\n if n == 1:\n return [TreeNode(0)]\n\n ans = []\n\n for leftCount in range(n):\n rightCount = n - 1 - leftCount\n for left in self.allPossibleFBT(leftCount):\n for right in self.allPossibleFBT(rightCount):\n ans.append(TreeNode(0))\n ans[-1].left = left\n ans[-1].right = right\n\n return ans\n", | |
| "title": "894. All Possible Full Binary Trees", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 859 | |
| }, | |
| { | |
| "code": "class FreqStack:\n def __init__(self):\n self.maxFreq = 0\n self.count = collections.Counter()\n self.countToStack = collections.defaultdict(list)\n\n def push(self, val: int) -> None:\n self.count[val] += 1\n self.countToStack[self.count[val]].append(val)\n self.maxFreq = max(self.maxFreq, self.count[val])\n\n def pop(self) -> int:\n val = self.countToStack[self.maxFreq].pop()\n self.count[val] -= 1\n if not self.countToStack[self.maxFreq]:\n self.maxFreq -= 1\n return val\n", | |
| "title": "895. Maximum Frequency Stack", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 860 | |
| }, | |
| { | |
| "code": "class Solution:\n def isMonotonic(self, nums: list[int]) -> bool:\n increasing = True\n decreasing = True\n\n for i in range(1, len(nums)):\n increasing &= nums[i - 1] <= nums[i]\n decreasing &= nums[i - 1] >= nums[i]\n\n return increasing or decreasing\n", | |
| "title": "896. Monotonic Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 861 | |
| }, | |
| { | |
| "code": "class Solution:\n def increasingBST(self, root: TreeNode, tail: TreeNode = None) -> TreeNode:\n if not root:\n return tail\n\n res = self.increasingBST(root.left, root)\n root.left = None\n root.right = self.increasingBST(root.right, tail)\n return res\n", | |
| "title": "897. Increasing Order Search Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 862 | |
| }, | |
| { | |
| "code": "class Solution:\n def orderlyQueue(self, s: str, k: int) -> str:\n return (''.join(sorted(s)) if k > 1\n else min(s[i:] + s[:i] for i in range(len(s))))\n", | |
| "title": "899. Orderly Queue", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 863 | |
| }, | |
| { | |
| "code": "class RLEIterator:\n def __init__(self, encoding: list[int]):\n self.encoding = encoding\n self.index = 0\n\n def next(self, n: int) -> int:\n while self.index < len(self.encoding) and self.encoding[self.index] < n:\n n -= self.encoding[self.index]\n self.index += 2\n\n if self.index == len(self.encoding):\n return -1\n\n self.encoding[self.index] -= n\n return self.encoding[self.index + 1]\n", | |
| "title": "900. RLE Iterator", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 864 | |
| }, | |
| { | |
| "code": "class StockSpanner:\n def __init__(self):\n self.stack = [] # (price, span)\n\n def next(self, price: int) -> int:\n span = 1\n while self.stack and self.stack[-1][0] <= price:\n span += self.stack.pop()[1]\n self.stack.append((price, span))\n return span\n", | |
| "title": "901. Online Stock Span", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 865 | |
| }, | |
| { | |
| "code": "class Solution:\n def atMostNGivenDigitSet(self, digits: list[str], n: int) -> int:\n ans = 0\n num = str(n)\n\n for i in range(1, len(num)):\n ans += pow(len(digits), i)\n\n for i, c in enumerate(num):\n dHasSameNum = False\n for digit in digits:\n if digit[0] < c:\n ans += pow(len(digits), len(num) - i - 1)\n elif digit[0] == c:\n dHasSameNum = True\n if not dHasSameNum:\n return ans\n\n return ans + 1\n", | |
| "title": "902. Numbers At Most N Given Digit Set", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 866 | |
| }, | |
| { | |
| "code": "class Solution:\n def totalFruit(self, fruits: list[int]) -> int:\n ans = 0\n count = collections.defaultdict(int)\n\n l = 0\n for r, fruit in enumerate(fruits):\n count[fruit] += 1\n while len(count) > 2:\n count[fruits[l]] -= 1\n if count[fruits[l]] == 0:\n del count[fruits[l]]\n l += 1\n ans = max(ans, r - l + 1)\n\n return ans\n", | |
| "title": "904. Fruit Into Baskets", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 867 | |
| }, | |
| { | |
| "code": "class Solution:\n def sortArrayByParity(self, nums: list[int]) -> list[int]:\n l = 0\n r = len(nums) - 1\n\n while l < r:\n if nums[l] % 2 == 1 and nums[r] % 2 == 0:\n nums[l], nums[r] = nums[r], nums[l]\n if nums[l] % 2 == 0:\n l += 1\n if nums[r] % 2 == 1:\n r -= 1\n\n return nums\n", | |
| "title": "905. Sort Array By Parity", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 868 | |
| }, | |
| { | |
| "code": "class Solution:\n def superpalindromesInRange(self, left: str, right: str) -> int:\n def nextPalindrome(num: int) -> int:\n s = str(num)\n n = len(s)\n\n half = s[0:(n + 1) // 2]\n reversedHalf = half[:n // 2][::-1]\n candidate = int(half + reversedHalf)\n if candidate >= num:\n return candidate\n\n half = str(int(half) + 1)\n reversedHalf = half[:n // 2][::-1]\n return int(half + reversedHalf)\n\n def isPalindrome(num: int) -> bool:\n s = str(num)\n l = 0\n r = len(s) - 1\n\n while l < r:\n if s[l] != s[r]:\n return False\n l += 1\n r -= 1\n\n return True\n\n ans = 0\n l = int(left)\n r = int(right)\n i = math.isqrt(l)\n\n while i * i <= r:\n palindrome = nextPalindrome(i)\n squared = palindrome**2\n if squared <= r and isPalindrome(squared):\n ans += 1\n i = palindrome + 1\n\n return ans\n", | |
| "title": "906. Super Palindromes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 869 | |
| }, | |
| { | |
| "code": "class Solution:\n def sumSubarrayMins(self, arr: list[int]) -> int:\n MOD = 1_000_000_007\n n = len(arr)\n ans = 0\n # prevMin[i] := index k s.t. arr[k] is the previous minimum in arr[:i]\n prevMin = [-1] * n\n # nextMin[i] := index k s.t. arr[k] is the next minimum in arr[i + 1:]\n nextMin = [n] * n\n stack = []\n\n for i, a in enumerate(arr):\n while stack and arr[stack[-1]] > a:\n index = stack.pop()\n nextMin[index] = i\n if stack:\n prevMin[i] = stack[-1]\n stack.append(i)\n\n for i, a in enumerate(arr):\n ans += a * (i - prevMin[i]) * (nextMin[i] - i)\n ans %= MOD\n\n return ans\n", | |
| "title": "907. Sum of Subarray Minimums", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 870 | |
| }, | |
| { | |
| "code": "class Solution:\n def smallestRangeI(self, nums: list[int], k: int) -> int:\n return max(0, max(nums) - min(nums) - 2 * k)\n", | |
| "title": "908. Smallest Range I", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 871 | |
| }, | |
| { | |
| "code": "class Solution:\n def snakesAndLadders(self, board: list[list[int]]) -> int:\n n = len(board)\n q = collections.deque([1])\n seen = set()\n arr = [0] * (1 + n * n) # 2D -> 1D\n\n for i in range(n):\n for j in range(n):\n arr[(n - 1 - i) * n + (n - j if (n - i) % 2 == 0 else j + 1)] = board[i][j]\n\n step = 1\n while q:\n for _ in range(len(q)):\n curr = q.popleft()\n for next in range(curr + 1, min(curr + 6, n * n) + 1):\n dest = arr[next] if arr[next] > 0 else next\n if dest == n * n:\n return step\n if dest in seen:\n continue\n q.append(dest)\n seen.add(dest)\n step += 1\n\n return -1\n", | |
| "title": "909. Snakes and Ladders", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 872 | |
| }, | |
| { | |
| "code": "class Solution:\n def smallestRangeII(self, nums: list[int], k: int) -> int:\n nums.sort()\n\n ans = nums[-1] - nums[0]\n left = nums[0] + k\n right = nums[-1] - k\n\n for a, b in itertools.pairwise(nums):\n mn = min(left, b - k)\n mx = max(right, a + k)\n ans = min(ans, mx - mn)\n\n return ans\n", | |
| "title": "910. Smallest Range II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 873 | |
| }, | |
| { | |
| "code": "class TopVotedCandidate:\n def __init__(self, persons: list[int], times: list[int]):\n self.times = times\n self.timeToLead = {}\n count = collections.Counter() # {person: voted}\n lead = -1\n\n for person, time in zip(persons, times):\n count[person] += 1\n if count[person] >= count[lead]:\n lead = person\n self.timeToLead[time] = lead\n\n def q(self, t: int) -> int:\n i = bisect_right(self.times, t)\n return self.timeToLead[self.times[i - 1]]\n", | |
| "title": "911. Online Election", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 874 | |
| }, | |
| { | |
| "code": "class Solution:\n def sortArray(self, nums: list[int]) -> list[int]:\n self._mergeSort(nums, 0, len(nums) - 1)\n return nums\n\n def _mergeSort(self, nums: list[int], l: int, r: int) -> None:\n if l >= r:\n return\n\n def merge(nums: list[int], l: int, m: int, r: int) -> None:\n sorted = [0] * (r - l + 1)\n k = 0 # sorted's index\n i = l # left's index\n j = m + 1 # right's index\n\n while i <= m and j <= r:\n if nums[i] < nums[j]:\n sorted[k] = nums[i]\n k += 1\n i += 1\n else:\n sorted[k] = nums[j]\n k += 1\n j += 1\n\n # Put the possible remaining left part into the sorted array.\n while i <= m:\n sorted[k] = nums[i]\n k += 1\n i += 1\n\n # Put the possible remaining right part into the sorted array.\n while j <= r:\n sorted[k] = nums[j]\n k += 1\n j += 1\n\n nums[l:l + len(sorted)] = sorted\n\n m = (l + r) // 2\n self._mergeSort(nums, l, m)\n self._mergeSort(nums, m + 1, r)\n merge(nums, l, m, r)\n", | |
| "title": "912. Sort an Array_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 875 | |
| }, | |
| { | |
| "code": "class Solution:\n def sortArray(self, nums: list[int]) -> list[int]:\n self._heapSort(nums)\n return nums\n\n def _heapSort(self, nums: list[int]) -> None:\n def maxHeapify(nums: list[int], i: int, heapSize: int) -> None:\n l = 2 * i + 1\n r = 2 * i + 2\n largest = i\n if l < heapSize and nums[largest] < nums[l]:\n largest = l\n if r < heapSize and nums[largest] < nums[r]:\n largest = r\n if largest != i:\n nums[largest], nums[i] = nums[i], nums[largest]\n maxHeapify(nums, largest, heapSize)\n\n def buildMaxHeap(nums: list[int]) -> None:\n for i in range(len(nums) // 2, -1, -1):\n maxHeapify(nums, i, len(nums))\n\n buildMaxHeap(nums)\n heapSize = len(nums)\n for i in reversed(range(1, len(nums))):\n nums[i], nums[0] = nums[0], nums[i]\n heapSize -= 1\n maxHeapify(nums, 0, heapSize)\n", | |
| "title": "912. Sort an Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 876 | |
| }, | |
| { | |
| "code": "from enum import IntEnum\n\n\nclass State(IntEnum):\n DRAW = 0\n MOUSE_WIN = 1\n CAT_WIN = 2\n\n\nclass Solution:\n def catMouseGame(self, graph: list[list[int]]) -> int:\n n = len(graph)\n # result of (cat, mouse, move)\n # move := 0 (mouse) // 1 (cat)\n states = [[[0] * 2 for _ in range(n)] for _ in range(n)]\n outDegree = [[[0] * 2 for _ in range(n)] for _ in range(n)]\n q = collections.deque() # (cat, mouse, move, state)\n\n for cat in range(n):\n for mouse in range(n):\n outDegree[cat][mouse][0] = len(graph[mouse])\n outDegree[cat][mouse][1] = len(graph[cat]) - graph[cat].count(0)\n\n # Start from the states s.t. the winner can be determined.\n for cat in range(1, n):\n for move in range(2):\n # Mouse is in the hole.\n states[cat][0][move] = int(State.MOUSE_WIN)\n q.append((cat, 0, move, int(State.MOUSE_WIN)))\n # Cat catches mouse.\n states[cat][cat][move] = int(State.CAT_WIN)\n q.append((cat, cat, move, int(State.CAT_WIN)))\n\n while q:\n cat, mouse, move, state = q.popleft()\n if cat == 2 and mouse == 1 and move == 0:\n return state\n prevMove = move ^ 1\n for prev in graph[cat if prevMove else mouse]:\n prevCat = prev if prevMove else cat\n if prevCat == 0: # invalid\n continue\n prevMouse = mouse if prevMove else prev\n # The state has been determined.\n if states[prevCat][prevMouse][prevMove]:\n continue\n if (prevMove == 0 and state == int(State.MOUSE_WIN) or\n prevMove == 1 and state == int(State.CAT_WIN)):\n states[prevCat][prevMouse][prevMove] = state\n q.append((prevCat, prevMouse, prevMove, state))\n else:\n outDegree[prevCat][prevMouse][prevMove] -= 1\n if outDegree[prevCat][prevMouse][prevMove] == 0:\n states[prevCat][prevMouse][prevMove] = state\n q.append((prevCat, prevMouse, prevMove, state))\n\n return states[2][1][0]\n", | |
| "title": "913. Cat and Mouse", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 877 | |
| }, | |
| { | |
| "code": "class Solution:\n def hasGroupsSizeX(self, deck: list[int]) -> bool:\n count = collections.Counter(deck)\n return functools.reduce(math.gcd, count.values()) >= 2\n", | |
| "title": "914. X of a Kind in a Deck of Cards", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 878 | |
| }, | |
| { | |
| "code": "class Solution:\n def partitionDisjoint(self, nums: list[int]) -> int:\n n = len(nums)\n mn = [0] * (n - 1) + [nums[-1]]\n mx = -math.inf\n\n for i in range(n - 2, - 1, -1):\n mn[i] = min(mn[i + 1], nums[i])\n\n for i, num in enumerate(nums):\n mx = max(mx, num)\n if mx <= mn[i + 1]:\n return i + 1\n", | |
| "title": "915. Partition Array into Disjoint Intervals", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 879 | |
| }, | |
| { | |
| "code": "class Solution:\n def wordSubsets(self, A: list[str], B: list[str]) -> list[str]:\n count = collections.Counter()\n\n for b in B:\n count = count | collections.Counter(b)\n\n return [a for a in A if collections.Counter(a) & count == count]\n", | |
| "title": "916. Word Subsets", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 880 | |
| }, | |
| { | |
| "code": "class Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n ans = list(s)\n i = 0\n j = len(s) - 1\n\n while i < j:\n while i < j and not s[i].isalpha():\n i += 1\n while i < j and not s[j].isalpha():\n j -= 1\n ans[i], ans[j] = ans[j], ans[i]\n i += 1\n j -= 1\n\n return ''.join(ans)\n", | |
| "title": "917. Reverse Only Letters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 881 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxSubarraySumCircular(self, nums: list[int]) -> int:\n totalSum = 0\n currMaxSum = 0\n currMinSum = 0\n maxSum = -math.inf\n minSum = math.inf\n\n for num in nums:\n totalSum += num\n currMaxSum = max(currMaxSum + num, num)\n currMinSum = min(currMinSum + num, num)\n maxSum = max(maxSum, currMaxSum)\n minSum = min(minSum, currMinSum)\n\n return maxSum if maxSum < 0 else max(maxSum, totalSum - minSum)\n", | |
| "title": "918. Maximum Sum Circular Subarray", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 882 | |
| }, | |
| { | |
| "code": "class CBTInserter:\n def __init__(self, root: TreeNode | None):\n self.tree = [root]\n for node in self.tree:\n if node.left:\n self.tree.append(node.left)\n if node.right:\n self.tree.append(node.right)\n\n def insert(self, v: int) -> int:\n n = len(self.tree)\n self.tree.append(TreeNode(v))\n parent = self.tree[(n - 1) // 2]\n if n % 2 == 1:\n parent.left = self.tree[-1]\n else:\n parent.right = self.tree[-1]\n return parent.val\n\n def get_root(self) -> TreeNode | None:\n return self.tree[0]\n", | |
| "title": "919. Complete Binary Tree Inserter", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 883 | |
| }, | |
| { | |
| "code": "class Solution:\n def minAddToMakeValid(self, s: str) -> int:\n l = 0\n r = 0\n\n for c in s:\n if c == '(':\n l += 1\n else:\n if l == 0:\n r += 1\n else:\n l -= 1\n\n return l + r\n", | |
| "title": "921. Minimum Add to Make Parentheses Valid", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 884 | |
| }, | |
| { | |
| "code": "class Solution:\n def sortArrayByParityII(self, nums: list[int]) -> list[int]:\n n = len(nums)\n\n i = 0\n j = 1\n while i < n:\n while i < n and nums[i] % 2 == 0:\n i += 2\n while j < n and nums[j] % 2 == 1:\n j += 2\n if i < n:\n nums[i], nums[j] = nums[j], nums[i]\n\n return nums\n", | |
| "title": "922. Sort Array By Parity II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 885 | |
| }, | |
| { | |
| "code": "class Solution:\n def threeSumMulti(self, arr: list[int], target: int) -> int:\n MOD = 1_000_000_007\n ans = 0\n count = collections.Counter(arr)\n\n for i, x in count.items():\n for j, y in count.items():\n k = target - i - j\n if k not in count:\n continue\n if i == j and j == k:\n ans = (ans + x * (x - 1) * (x - 2) // 6) % MOD\n elif i == j and j != k:\n ans = (ans + x * (x - 1) // 2 * count[k]) % MOD\n elif i < j and j < k:\n ans = (ans + x * y * count[k]) % MOD\n\n return ans % MOD\n", | |
| "title": "923. 3Sum With Multiplicity", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 886 | |
| }, | |
| { | |
| "code": "class Solution:\n def isLongPressedName(self, name: str, typed: str) -> bool:\n i = 0\n\n for j, t in enumerate(typed):\n if i < len(name) and name[i] == t:\n i += 1\n elif j == 0 or t != typed[j - 1]:\n return False\n\n return i == len(name)\n", | |
| "title": "925. Long Pressed Name", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 887 | |
| }, | |
| { | |
| "code": "class Solution:\n def minFlipsMonoIncr(self, s: str) -> int:\n # the number of characters to be flilpped to make the substring so far\n # monotone increasing\n dp = 0\n count1 = 0\n\n for c in s:\n if c == '0':\n # 1. Flip '0'.\n # 2. Keep '0' and flip all the previous 1s.\n dp = min(dp + 1, count1)\n else:\n count1 += 1\n\n return dp\n", | |
| "title": "926. Flip String to Monotone Increasing", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 888 | |
| }, | |
| { | |
| "code": "class Solution:\n def threeEqualParts(self, arr: list[int]) -> list[int]:\n ones = sum(a == 1 for a in arr)\n\n if ones == 0:\n return [0, len(arr) - 1]\n if ones % 3 != 0:\n return [-1, -1]\n\n k = ones // 3\n i = 0\n\n for i in range(len(arr)):\n if arr[i] == 1:\n first = i\n break\n\n gapOnes = k\n\n for j in range(i + 1, len(arr)):\n if arr[j] == 1:\n gapOnes -= 1\n if gapOnes == 0:\n second = j\n break\n\n gapOnes = k\n\n for i in range(j + 1, len(arr)):\n if arr[i] == 1:\n gapOnes -= 1\n if gapOnes == 0:\n third = i\n break\n\n while third < len(arr) and arr[first] == arr[second] == arr[third]:\n first += 1\n second += 1\n third += 1\n\n if third == len(arr):\n return [first - 1, second]\n return [-1, -1]\n", | |
| "title": "927. Three Equal Parts", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 889 | |
| }, | |
| { | |
| "code": "class Solution:\n def numUniqueEmails(self, emails: list[str]) -> int:\n seen = set()\n\n for email in emails:\n local, domain = email.split('@')\n local = local.split('+')[0].replace('.', '')\n seen.add(local + '@' + domain)\n\n return len(seen)\n", | |
| "title": "929. Unique Email Addresses", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 890 | |
| }, | |
| { | |
| "code": "class Solution:\n def numSubarraysWithSum(self, nums: list[int], goal: int) -> int:\n def numSubarraysWithSumAtMost(goal: int) -> int:\n res = 0\n count = 0\n l = 0\n r = 0\n\n while r < len(nums):\n count += nums[r]\n r += 1\n while l < r and count > goal:\n count -= nums[l]\n l += 1\n # nums[l..r), nums[l + 1..r), ..., nums[r - 1]\n res += r - l\n\n return res\n\n return numSubarraysWithSumAtMost(goal) - numSubarraysWithSumAtMost(goal - 1)\n", | |
| "title": "930. Binary Subarrays With Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312229, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 891 | |
| }, | |
| { | |
| "code": "class Solution:\n def minFallingPathSum(self, A: list[list[int]]) -> int:\n n = len(A)\n\n for i in range(1, n):\n for j in range(n):\n mn = math.inf\n for k in range(max(0, j - 1), min(n, j + 2)):\n mn = min(mn, A[i - 1][k])\n A[i][j] += mn\n\n return min(A[-1])\n", | |
| "title": "931. Minimum Falling Path Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 892 | |
| }, | |
| { | |
| "code": "class Solution:\n def beautifulArray(self, n: int) -> list[int]:\n arr = [i for i in range(1, n + 1)]\n\n def partition(l: int, r: int, mask: int) -> int:\n nextSwapped = l\n for i in range(l, r + 1):\n if arr[i] & mask:\n arr[i], arr[nextSwapped] = arr[nextSwapped], arr[i]\n nextSwapped += 1\n return nextSwapped - 1\n\n def divide(l: int, r: int, mask: int) -> None:\n if l >= r:\n return\n m = partition(l, r, mask)\n divide(l, m, mask << 1)\n divide(m + 1, r, mask << 1)\n\n divide(0, n - 1, 1)\n return arr\n", | |
| "title": "932. Beautiful Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 893 | |
| }, | |
| { | |
| "code": "class RecentCounter:\n def __init__(self):\n self.q = collections.deque()\n\n def ping(self, t: int) -> int:\n self.q.append(t)\n while self.q[0] < t - 3000:\n self.q.popleft()\n return len(self.q)\n", | |
| "title": "933. Number of Recent Calls", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 894 | |
| }, | |
| { | |
| "code": "class Solution:\n def knightDialer(self, n: int) -> int:\n DIRS = ((1, 2), (2, 1), (2, -1), (1, -2),\n (-1, -2), (-2, -1), (-2, 1), (-1, 2))\n MOD = 1_000_000_007\n\n # dp[i][j] := the number of ways stand on (i, j)\n dp = [[1] * 3 for _ in range(4)]\n dp[3][0] = dp[3][2] = 0\n\n for _ in range(n - 1):\n newDp = [[0] * 3 for _ in range(4)]\n for i in range(4):\n for j in range(3):\n if (i, j) in ((3, 0), (3, 2)):\n continue\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x >= 4 or y < 0 or y >= 3:\n continue\n if (x, y) in ((3, 0), (3, 2)):\n continue\n newDp[x][y] = (newDp[x][y] + dp[i][j]) % MOD\n dp = newDp\n\n return sum(map(sum, dp)) % MOD\n", | |
| "title": "935. Knight Dialer", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 895 | |
| }, | |
| { | |
| "code": "class Solution:\n def movesToStamp(self, stamp: str, target: str) -> list[int]:\n def stampify(s: int) -> int:\n \"\"\"\n Stamps target[i..i + |stamp|) and returns the number of newly stamped\n characters.\n e.g. stampify(\"abc\", \"ababc\", 2) returns 3 because target becomes \"ab***\".\n \"\"\"\n stampified = len(stamp)\n\n for i, st in enumerate(stamp):\n if target[s + i] == '*': # It's already been stamped.\n stampified -= 1\n elif target[s + i] != st: # We can't stamp on the index i.\n return 0\n\n for i in range(s, s + len(stamp)):\n target[i] = '*'\n\n return stampified\n\n ans = []\n target = list(target)\n # stamped[i] := True if we already stamped target by stamping on index i\n stamped = [False] * len(target)\n stampedCount = 0 # Our goal is to make stampedCount = |target|.\n\n while stampedCount < len(target):\n isStamped = False\n # Try to stamp target[i..i + |stamp|) for each index.\n for i in range(len(target) - len(stamp) + 1):\n if stamped[i]:\n continue\n stampified = stampify(i)\n if stampified == 0:\n continue\n stampedCount += stampified\n isStamped = True\n stamped[i] = True\n ans.append(i)\n # After trying to stamp on each index, we can't find a valid stamp.\n if not isStamped:\n return []\n\n return ans[::-1]\n", | |
| "title": "936. Stamping The Sequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 896 | |
| }, | |
| { | |
| "code": "class Solution:\n def reorderLogFiles(self, logs: list[str]) -> list[str]:\n digitLogs = []\n letterLogs = []\n\n for log in logs:\n i = log.index(' ')\n if log[i + 1].isdigit():\n digitLogs.append(log)\n else:\n letterLogs.append((log[:i], log[i + 1:]))\n\n letterLogs.sort(key=lambda x: (x[1], x[0]))\n return [identifier + ' ' + letters for identifier, letters in letterLogs] + digitLogs\n", | |
| "title": "937. Reorder Data in Log Files", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 897 | |
| }, | |
| { | |
| "code": "class Solution:\n def minAreaRect(self, points: list[list[int]]) -> int:\n ans = math.inf\n xToYs = collections.defaultdict(set)\n\n for x, y in points:\n xToYs[x].add(y)\n\n for i in range(len(points)):\n for j in range(i):\n x1, y1 = points[i]\n x2, y2 = points[j]\n if x1 == x2 or y1 == y2:\n continue\n if y2 in xToYs[x1] and y1 in xToYs[x2]:\n ans = min(ans, abs(x1 - x2) * abs(y1 - y2))\n\n return ans if ans < math.inf else 0\n", | |
| "title": "939. Minimum Area Rectangle", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 898 | |
| }, | |
| { | |
| "code": "class Solution:\n def distinctSubseqII(self, s: str) -> int:\n MOD = 1_000_000_007\n # endsIn[i] := the number of subsequence that end in ('a' + i)\n endsIn = [0] * 26\n\n for c in s:\n endsIn[ord(c) - ord('a')] = (sum(endsIn) + 1) % MOD\n\n return sum(endsIn) % MOD\n", | |
| "title": "940. Distinct Subsequences II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 899 | |
| }, | |
| { | |
| "code": "class Solution:\n def validMountainArray(self, arr: list[int]) -> bool:\n if len(arr) < 3:\n return False\n\n l = 0\n r = len(arr) - 1\n\n while l + 1 < len(arr) and arr[l] < arr[l + 1]:\n l += 1\n while r > 0 and arr[r] < arr[r - 1]:\n r -= 1\n\n return l > 0 and r < len(arr) - 1 and l == r\n", | |
| "title": "941. Valid Mountain Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 900 | |
| }, | |
| { | |
| "code": "class Solution:\n def diStringMatch(self, s: str) -> list[int]:\n ans = []\n mn = 0\n mx = len(s)\n\n for c in s:\n if c == 'I':\n ans.append(mn)\n mn += 1\n else:\n ans.append(mx)\n mx -= 1\n\n return ans + [mn]\n", | |
| "title": "942. DI String Match", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 901 | |
| }, | |
| { | |
| "code": "class Solution:\n def minDeletionSize(self, strs: list[str]) -> int:\n ans = 0\n\n for j in range(len(strs[0])):\n for i in range(len(strs) - 1):\n if strs[i][j] > strs[i + 1][j]:\n ans += 1\n break\n\n return ans\n", | |
| "title": "944. Delete Columns to Make Sorted", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 902 | |
| }, | |
| { | |
| "code": "class Solution:\n def minIncrementForUnique(self, nums: list[int]) -> int:\n ans = 0\n minAvailable = 0\n\n for num in sorted(nums):\n ans += max(minAvailable - num, 0)\n minAvailable = max(minAvailable, num) + 1\n\n return ans\n", | |
| "title": "945. Minimum Increment to Make Array Unique", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 903 | |
| }, | |
| { | |
| "code": "class Solution:\n def validateStackSequences(\n self,\n pushed: list[int],\n popped: list[int],\n ) -> bool:\n stack = []\n i = 0 # popped's index\n\n for x in pushed:\n stack.append(x)\n while stack and stack[-1] == popped[i]:\n stack.pop()\n i += 1\n\n return not stack\n", | |
| "title": "946. Validate Stack Sequences", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 904 | |
| }, | |
| { | |
| "code": "class Solution:\n def bagOfTokensScore(self, tokens: list[int], power: int) -> int:\n ans = 0\n score = 0\n q = collections.deque(sorted(tokens))\n\n while q and (power >= q[0] or score):\n while q and power >= q[0]:\n # Play the smallest face up.\n power -= q.popleft()\n score += 1\n ans = max(ans, score)\n if q and score:\n # Play the largest face down.\n power += q.pop()\n score -= 1\n\n return ans\n", | |
| "title": "948. Bag of Tokens", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 905 | |
| }, | |
| { | |
| "code": "class Solution:\n def largestTimeFromDigits(self, arr: list[int]) -> str:\n for time in itertools.permutations(sorted(arr, reverse=True)):\n if time[:2] < (2, 4) and time[2] < 6:\n return '%d%d:%d%d' % time\n return ''\n", | |
| "title": "949. Largest Time for Given Digits", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 906 | |
| }, | |
| { | |
| "code": "class Solution:\n def deckRevealedIncreasing(self, deck: list[int]) -> list[int]:\n dq = collections.deque()\n\n for card in reversed(sorted(deck)):\n dq.rotate()\n dq.appendleft(card)\n\n return list(dq)\n", | |
| "title": "950. Reveal Cards In Increasing Order", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 907 | |
| }, | |
| { | |
| "code": "class Solution:\n def flipEquiv(self, root1: TreeNode | None, root2: TreeNode | None) -> bool:\n if not root1:\n return not root2\n if not root2:\n return not root1\n if root1.val != root2.val:\n return False\n return (self.flipEquiv(root1.left, root2.left) and\n self.flipEquiv(root1.right, root2.right) or\n self.flipEquiv(root1.left, root2.right) and\n self.flipEquiv(root1.right, root2.left))\n", | |
| "title": "951. Flip Equivalent Binary Trees", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 908 | |
| }, | |
| { | |
| "code": "class UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self.find(u)\n j = self.find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def largestComponentSize(self, nums: list[int]) -> int:\n ans = 0\n uf = UnionFind(max(nums) + 1)\n count = collections.Counter()\n\n for num in nums:\n for x in range(2, math.isqrt(num) + 1):\n if num % x == 0:\n uf.unionByRank(num, x)\n uf.unionByRank(num, num // x)\n\n for num in nums:\n numRoot = uf.find(num)\n count[numRoot] += 1\n ans = max(ans, count[numRoot])\n\n return ans\n", | |
| "title": "952. Largest Component Size by Common Factor", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 909 | |
| }, | |
| { | |
| "code": "class Solution:\n def isAlienSorted(self, words: list[str], order: str) -> bool:\n dict = {c: i for i, c in enumerate(order)}\n words = [[dict[c] for c in word] for word in words]\n return all(w1 <= w2 for w1, w2 in zip(words, words[1:]))\n", | |
| "title": "953. Verifying an Alien Dictionary", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 910 | |
| }, | |
| { | |
| "code": "class Solution:\n def canReorderDoubled(self, arr: list[int]) -> bool:\n count = collections.Counter(arr)\n\n for key in sorted(count, key=abs):\n if count[key] > count[2 * key]:\n return False\n count[2 * key] -= count[key]\n\n return True\n", | |
| "title": "954. Array of Doubled Pairs", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 911 | |
| }, | |
| { | |
| "code": "class Solution:\n def prisonAfterNDays(self, cells: list[int], n: int) -> list[int]:\n nextDayCells = [0] * len(cells)\n day = 0\n\n while n > 0:\n n -= 1\n for i in range(1, len(cells) - 1):\n nextDayCells[i] = 1 if cells[i - 1] == cells[i + 1] else 0\n if day == 0:\n firstDayCells = nextDayCells.copy()\n elif nextDayCells == firstDayCells:\n n %= day\n cells = nextDayCells.copy()\n day += 1\n\n return cells\n", | |
| "title": "957. Prison Cells After N Days", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 912 | |
| }, | |
| { | |
| "code": "class Solution:\n def repeatedNTimes(self, nums: list[int]) -> int:\n for i in range(len(nums) - 2):\n if nums[i] == nums[i + 1] or nums[i] == nums[i + 2]:\n return nums[i]\n return nums[-1]\n", | |
| "title": "961. N-Repeated Element in Size 2N Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 913 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxWidthRamp(self, nums: list[int]) -> int:\n ans = 0\n stack = []\n\n for i, num in enumerate(nums):\n if stack == [] or num <= nums[stack[-1]]:\n stack.append(i)\n\n for i, num in reversed(list(enumerate(nums))):\n while stack and num >= nums[stack[-1]]:\n ans = max(ans, i - stack.pop())\n\n return ans\n", | |
| "title": "962. Maximum Width Ramp", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 914 | |
| }, | |
| { | |
| "code": "class Solution:\n def minAreaFreeRect(self, points: list[list[int]]) -> float:\n ans = math.inf\n # For each A, B pair points, {hash(A, B): (ax, ay, bx, by)}.\n centerToPoints = collections.defaultdict(list)\n\n for ax, ay in points:\n for bx, by in points:\n center = ((ax + bx) / 2, (ay + by) / 2)\n centerToPoints[center].append((ax, ay, bx, by))\n\n def dist(px: int, py: int, qx: int, qy: int) -> float:\n return (px - qx)**2 + (py - qy)**2\n\n # For all pair points \"that share the same center\".\n for points in centerToPoints.values():\n for ax, ay, _, _ in points:\n for cx, cy, dx, dy in points:\n # AC is perpendicular to AD.\n # AC dot AD = (cx - ax, cy - ay) dot (dx - ax, dy - ay) == 0.\n if (cx - ax) * (dx - ax) + (cy - ay) * (dy - ay) == 0:\n squaredArea = dist(ax, ay, cx, cy) * dist(ax, ay, dx, dy)\n if squaredArea > 0:\n ans = min(ans, squaredArea)\n\n return 0 if ans == math.inf else math.sqrt(ans)\n", | |
| "title": "963. Minimum Area Rectangle II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 915 | |
| }, | |
| { | |
| "code": "class Solution:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n @functools.lru_cache(None)\n def dfs(target):\n if x > target:\n return min(2 * target - 1, 2 * (x - target))\n if x == target:\n return 0\n\n prod = x\n n = 0\n while prod < target:\n prod *= x\n n += 1\n if prod == target:\n return n\n\n ans = dfs(target - prod // x) + n\n if prod < 2 * target:\n ans = min(ans, dfs(prod - target) + n + 1)\n return ans\n\n return dfs(target)\n", | |
| "title": "964. Least Operators to Express Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 916 | |
| }, | |
| { | |
| "code": "class Solution:\n def isUnivalTree(self, root: TreeNode | None) -> bool:\n if not root:\n return True\n if root.left and root.left.val != root.val:\n return False\n if root.right and root.right.val != root.val:\n return False\n return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)\n", | |
| "title": "965. Univalued Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 917 | |
| }, | |
| { | |
| "code": "class Solution:\n def spellchecker(self, wordlist: list[str], queries: list[str]) -> list[str]:\n def lowerKey(word: str) -> str:\n return '$' + ''.join([c.lower() for c in word])\n\n def vowelKey(word: str) -> str:\n return ''.join(['*' if c.lower() in 'aeiou' else c.lower() for c in word])\n\n ans = []\n dict = {}\n\n for word in wordlist:\n dict.setdefault(word, word)\n dict.setdefault(lowerKey(word), word)\n dict.setdefault(vowelKey(word), word)\n\n for query in queries:\n if query in dict:\n ans.append(dict[query])\n elif lowerKey(query) in dict:\n ans.append(dict[lowerKey(query)])\n elif vowelKey(query) in dict:\n ans.append(dict[vowelKey(query)])\n else:\n ans.append('')\n\n return ans\n", | |
| "title": "966. Vowel Spellchecker", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 918 | |
| }, | |
| { | |
| "code": "class Solution:\n def pancakeSort(self, arr: list[int]) -> list[int]:\n ans = []\n\n for target in range(len(arr), 0, -1):\n index = arr.index(target)\n arr[:index + 1] = arr[:index + 1][::-1]\n arr[:target] = arr[:target][::-1]\n ans.append(index + 1)\n ans.append(target)\n\n return ans\n", | |
| "title": "969. Pancake Sorting", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 919 | |
| }, | |
| { | |
| "code": "class Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> list[int]:\n xs = {x**i for i in range(20) if x**i < bound}\n ys = {y**i for i in range(20) if y**i < bound}\n return list({i + j for i in xs for j in ys if i + j <= bound})\n", | |
| "title": "970. Powerful Integers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 920 | |
| }, | |
| { | |
| "code": "class Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n ratios = [1, 1 / 9, 1 / 99, 1 / 999, 1 / 9999]\n\n def valueOf(s: str) -> float:\n if s.find('(') == -1:\n return float(s)\n\n # Get the indices.\n leftParenIndex = s.find('(')\n rightParenIndex = s.find(')')\n dotIndex = s.find('.')\n\n # integerAndNonRepeating := <IntegerPart><.><NonRepeatingPart>\n integerAndNonRepeating = float(s[:leftParenIndex])\n nonRepeatingLength = leftParenIndex - dotIndex - 1\n\n # repeating := <RepeatingPart>\n repeating = int(s[leftParenIndex + 1:rightParenIndex])\n repeatingLength = rightParenIndex - leftParenIndex - 1\n return integerAndNonRepeating + repeating * 0.1**nonRepeatingLength * ratios[repeatingLength]\n\n return abs(valueOf(s) - valueOf(t)) < 1e-9\n", | |
| "title": "972. Equal Rational Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 921 | |
| }, | |
| { | |
| "code": "class Solution:\n def kClosest(self, points: list[list[int]], k: int) -> list[list[int]]:\n maxHeap = []\n\n for x, y in points:\n heapq.heappush(maxHeap, (- x * x - y * y, [x, y]))\n if len(maxHeap) > k:\n heapq.heappop(maxHeap)\n\n return [pair[1] for pair in maxHeap]\n", | |
| "title": "973. K Closest Points to Origin_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 922 | |
| }, | |
| { | |
| "code": "class Solution:\n def kClosest(self, points: list[list[int]], k: int) -> list[list[int]]:\n def squareDist(p: list[int]) -> int:\n return p[0] * p[0] + p[1] * p[1]\n\n def quickSelect(l: int, r: int, k: int) -> None:\n pivot = points[r]\n\n nextSwapped = l\n for i in range(l, r):\n if squareDist(points[i]) <= squareDist(pivot):\n points[nextSwapped], points[i] = points[i], points[nextSwapped]\n nextSwapped += 1\n points[nextSwapped], points[r] = points[r], points[nextSwapped]\n\n count = nextSwapped - l + 1 the number of points <= pivot\n if count == k:\n return\n if count > k:\n quickSelect(l, nextSwapped - 1, k)\n else:\n quickSelect(nextSwapped + 1, r, k - count)\n\n quickSelect(0, len(points) - 1, k)\n return points[0:k]\n", | |
| "title": "973. K Closest Points to Origin", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 923 | |
| }, | |
| { | |
| "code": "class Solution:\n def subarraysDivByK(self, nums: list[int], k: int) -> int:\n ans = 0\n prefix = 0\n count = [0] * k\n count[0] = 1\n\n for num in nums:\n prefix = (prefix + num % k + k) % k\n ans += count[prefix]\n count[prefix] += 1\n\n return ans\n", | |
| "title": "974. Subarray Sums Divisible by K", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 924 | |
| }, | |
| { | |
| "code": "class Solution:\n def largestPerimeter(self, nums: list[int]) -> int:\n nums = sorted(nums)\n\n for i in range(len(nums) - 1, 1, -1):\n if nums[i - 2] + nums[i - 1] > nums[i]:\n return nums[i - 2] + nums[i - 1] + nums[i]\n\n return 0\n", | |
| "title": "976. Largest Perimeter Triangle", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 925 | |
| }, | |
| { | |
| "code": "class Solution:\n def sortedSquares(self, nums: list[int]) -> list[int]:\n n = len(nums)\n l = 0\n r = n - 1\n ans = [0] * n\n\n while n:\n n -= 1\n if abs(nums[l]) > abs(nums[r]):\n ans[n] = nums[l] * nums[l]\n l += 1\n else:\n ans[n] = nums[r] * nums[r]\n r -= 1\n\n return ans\n", | |
| "title": "977. Squares of a Sorted Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 926 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxTurbulenceSize(self, arr: list[int]) -> int:\n ans = 1\n increasing = 1\n decreasing = 1\n\n for i in range(1, len(arr)):\n if arr[i] > arr[i - 1]:\n increasing = decreasing + 1\n decreasing = 1\n elif arr[i] < arr[i - 1]:\n decreasing = increasing + 1\n increasing = 1\n else:\n increasing = 1\n decreasing = 1\n ans = max(ans, max(increasing, decreasing))\n\n return ans\n", | |
| "title": "978. Longest Turbulent Subarray", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 927 | |
| }, | |
| { | |
| "code": "class TimeMap:\n def __init__(self):\n self.values = collections.defaultdict(list)\n self.timestamps = collections.defaultdict(list)\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.values[key].append(value)\n self.timestamps[key].append(timestamp)\n\n def get(self, key: str, timestamp: int) -> str:\n if key not in self.timestamps:\n return ''\n i = bisect.bisect(self.timestamps[key], timestamp)\n return self.values[key][i - 1] if i > 0 else ''\n", | |
| "title": "981. Time Based Key-Value Store", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 928 | |
| }, | |
| { | |
| "code": "class Solution:\n def countTriplets(self, nums: list[int]) -> int:\n MAX = 1 << 16\n ans = 0\n count = [0] * MAX # {nums[i] & nums[j]: times}\n\n for a in nums:\n for b in nums:\n count[a & b] += 1\n\n for num in nums:\n for i in range(MAX):\n if (num & i) == 0:\n ans += count[i]\n\n return ans\n", | |
| "title": "982. Triples with Bitwise AND Equal To Zero", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 929 | |
| }, | |
| { | |
| "code": "class Solution:\n def mincostTickets(self, days: list[int], costs: list[int]) -> int:\n ans = 0\n last7 = collections.deque()\n last30 = collections.deque()\n\n for day in days:\n while last7 and last7[0][0] + 7 <= day:\n last7.popleft()\n while last30 and last30[0][0] + 30 <= day:\n last30.popleft()\n last7.append([day, ans + costs[1]])\n last30.append([day, ans + costs[2]])\n ans = min(ans + costs[0], last7[0][1], last30[0][1])\n\n return ans\n", | |
| "title": "983. Minimum Cost For Tickets", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 930 | |
| }, | |
| { | |
| "code": "class Solution:\n def sumEvenAfterQueries(\n self,\n nums: list[int],\n queries: list[list[int]],\n ) -> list[int]:\n ans = []\n summ = sum(a for a in nums if a % 2 == 0)\n\n for val, index in queries:\n if nums[index] % 2 == 0:\n summ -= nums[index]\n nums[index] += val\n if nums[index] % 2 == 0:\n summ += nums[index]\n ans.append(summ)\n\n return ans\n", | |
| "title": "985. Sum of Even Numbers After Queries", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 931 | |
| }, | |
| { | |
| "code": "class Solution:\n def intervalIntersection(self, firstList: list[list[int]],\n secondList: list[list[int]]) -> list[list[int]]:\n ans = []\n i = 0\n j = 0\n\n while i < len(firstList) and j < len(secondList):\n # lo := the start of the intersection\n # hi := the end of the intersection\n lo = max(firstlist[i][0], secondlist[j][0])\n hi = min(firstlist[i][1], secondlist[j][1])\n if lo <= hi:\n ans.append([lo, hi])\n if firstlist[i][1] < secondlist[j][1]:\n i += 1\n else:\n j += 1\n\n return ans\n", | |
| "title": "986. Interval List Intersections", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 932 | |
| }, | |
| { | |
| "code": "class Solution:\n def verticalTraversal(self, root: TreeNode | None) -> list[list[int]]:\n ans = []\n xToNodes = collections.defaultdict(list)\n\n def dfs(node: TreeNode | None, x: int, y: int) -> None:\n if not node:\n return\n xToNodes[x].append((-y, node.val))\n dfs(node.left, x - 1, y - 1)\n dfs(node.right, x + 1, y - 1)\n\n dfs(root, 0, 0)\n\n for _, nodes in sorted(xToNodes.items(), key=lambda x: x[0]):\n ans.append([val for _, val in sorted(nodes)])\n\n return ans\n", | |
| "title": "987. Vertical Order Traversal of a Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 933 | |
| }, | |
| { | |
| "code": "class Solution:\n def addToArrayForm(self, num: list[int], k: int) -> list[int]:\n for i in reversed(range(len(num))):\n k, num[i] = divmod(num[i] + k, 10)\n\n while k > 0:\n num = [k % 10] + num\n k //= 10\n\n return num\n", | |
| "title": "989. Add to Array-Form of Integer", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 934 | |
| }, | |
| { | |
| "code": "class UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n\n def union(self, u: int, v: int) -> None:\n self.id[self.find(u)] = self.find(v)\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def equationsPossible(self, equations: list[str]) -> bool:\n uf = UnionFind(26)\n\n for x, op, _, y in equations:\n if op == '=':\n uf.union(ord(x) - ord('a'),\n ord(y) - ord('a'))\n\n return all(\n uf.find(ord(x) - ord('a')) !=\n uf.find(ord(y) - ord('a'))\n for x, op, _, y in equations\n if op == '!')\n", | |
| "title": "990. Satisfiability of Equality Equations", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 935 | |
| }, | |
| { | |
| "code": "class Solution:\n def brokenCalc(self, startValue: int, target: int) -> int:\n ops = 0\n\n while startValue < target:\n if target % 2 == 0:\n target //= 2\n else:\n target += 1\n ops += 1\n\n return ops + startValue - target\n", | |
| "title": "991. Broken Calculator", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 936 | |
| }, | |
| { | |
| "code": "class Solution:\n def subarraysWithKDistinct(self, nums: list[int], k: int) -> int:\n def subarraysWithAtMostKDistinct(k: int) -> int:\n res = 0\n count = collections.Counter()\n\n l = 0\n for r, num in enumerate(nums):\n count[num] += 1\n if count[num] == 1:\n k -= 1\n while k < 0:\n count[nums[l]] -= 1\n if count[nums[l]] == 0:\n k += 1\n l += 1\n res += r - l + 1 # nums[l..r], nums[l + 1..r], ..., nums[r]\n\n return res\n\n return subarraysWithAtMostKDistinct(k) - subarraysWithAtMostKDistinct(k - 1)\n", | |
| "title": "992. Subarrays with K Different Integers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 937 | |
| }, | |
| { | |
| "code": "class Solution:\n def minKBitFlips(self, nums: list[int], k: int) -> int:\n ans = 0\n flippedTime = 0\n\n for i, num in enumerate(nums):\n if i >= k and nums[i - k] == 2:\n flippedTime -= 1\n if flippedTime % 2 == num:\n if i + k > len(nums):\n return -1\n ans += 1\n flippedTime += 1\n nums[i] = 2\n\n return ans\n", | |
| "title": "995. Minimum Number of K Consecutive Bit Flips", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 938 | |
| }, | |
| { | |
| "code": "class Solution:\n def numSquarefulPerms(self, nums: list[int]) -> int:\n ans = 0\n used = [False] * len(nums)\n\n def isSquare(num: int) -> bool:\n root = math.isqrt(num)\n return root * root == num\n\n def dfs(path: list[int]) -> None:\n nonlocal ans\n if len(path) > 1 and not isSquare(path[-1] + path[-2]):\n return\n if len(path) == len(nums):\n ans += 1\n return\n\n for i, a in enumerate(nums):\n if used[i]:\n continue\n if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:\n continue\n used[i] = True\n dfs(path + [a])\n used[i] = False\n\n nums.sort()\n dfs([])\n return ans\n", | |
| "title": "996. Number of Squareful Arrays", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 939 | |
| }, | |
| { | |
| "code": "class Solution:\n def findJudge(self, n: int, trust: list[list[int]]) -> int:\n count = [0] * (n + 1)\n\n for a, b in trust:\n count[a] -= 1\n count[b] += 1\n\n for i in range(1, n + 1):\n if count[i] == n - 1:\n return i\n\n return -1\n", | |
| "title": "997. Find the Town Judge", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 940 | |
| }, | |
| { | |
| "code": "class Solution:\n def insertIntoMaxTree(\n self,\n root: TreeNode | None,\n val: int,\n ) -> TreeNode | None:\n if root.val < val:\n return TreeNode(val, root, None)\n curr = root\n while curr.right and curr.right.val > val:\n curr = curr.right\n inserted = TreeNode(val, curr.right, None)\n curr.right = inserted\n return root\n", | |
| "title": "998. Maximum Binary Tree II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 941 | |
| }, | |
| { | |
| "code": "class Solution:\n def numRookCaptures(self, board: list[list[str]]) -> int:\n ans = 0\n\n for i in range(8):\n for j in range(8):\n if board[i][j] == 'R':\n i0 = i\n j0 = j\n\n for d in [[1, 0], [0, 1], [-1, 0], [0, -1]]:\n i = i0 + d[0]\n j = j0 + d[1]\n while 0 <= i < 8 and 0 <= j < 8:\n if board[i][j] == 'p':\n ans += 1\n if board[i][j] != '.':\n break\n i += d[0]\n j += d[1]\n\n return ans\n", | |
| "title": "999. Available Captures for Rook", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 942 | |
| }, | |
| { | |
| "code": "class Solution:\n def gridIllumination(\n self,\n n: int,\n lamps: list[list[int]],\n queries: list[list[int]],\n ) -> list[int]:\n ans = []\n rows = collections.Counter()\n cols = collections.Counter()\n diag1 = collections.Counter()\n diag2 = collections.Counter()\n lampsSet = set()\n\n for i, j in lamps:\n if (i, j) not in lampsSet:\n lampsSet.add((i, j))\n rows[i] += 1\n cols[j] += 1\n diag1[i + j] += 1\n diag2[i - j] += 1\n\n for i, j in queries:\n if rows[i] or cols[j] or diag1[i + j] or diag2[i - j]:\n ans.append(1)\n for y in range(max(0, i - 1), min(n, i + 2)):\n for x in range(max(0, j - 1), min(n, j + 2)):\n if (y, x) in lampsSet:\n lampsSet.remove((y, x))\n rows[y] -= 1\n cols[x] -= 1\n diag1[y + x] -= 1\n diag2[y - x] -= 1\n else:\n ans.append(0)\n\n return ans\n", | |
| "title": "1001. Grid Illumination", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 943 | |
| }, | |
| { | |
| "code": "class Solution:\n def commonChars(self, words: list[str]) -> list[str]:\n return functools.reduce(lambda a, b: a & b,\n map(collections.Counter, words)).elements()\n", | |
| "title": "1002. Find Common Characters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 944 | |
| }, | |
| { | |
| "code": "class Solution:\n def isValid(self, s: str) -> bool:\n stack = []\n\n for c in s:\n if c == 'c':\n if len(stack) < 2 or stack[-2] != 'a' or stack[-1] != 'b':\n return False\n stack.pop()\n stack.pop()\n else:\n stack.append(c)\n\n return not stack\n", | |
| "title": "1003. Check If Word Is Valid After Substitutions", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 945 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestOnes(self, nums: list[int], k: int) -> int:\n ans = 0\n\n l = 0\n for r, num in enumerate(nums):\n if num == 0:\n k -= 1\n while k < 0:\n if nums[l] == 0:\n k += 1\n l += 1\n ans = max(ans, r - l + 1)\n\n return ans\n", | |
| "title": "1004. Max Consecutive Ones III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 946 | |
| }, | |
| { | |
| "code": "class Solution:\n def largestSumAfterKNegations(self, nums: list[int], k: int) -> int:\n nums.sort()\n\n for i, num in enumerate(nums):\n if num > 0 or k == 0:\n break\n nums[i] = -num\n k -= 1\n\n return sum(nums) - (k % 2) * min(nums) * 2\n", | |
| "title": "1005. Maximize Sum Of Array After K Negations", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 947 | |
| }, | |
| { | |
| "code": "class Solution:\n def clumsy(self, n: int) -> int:\n if n == 1:\n return 1\n if n == 2:\n return 2\n if n == 3:\n return 6\n if n == 4:\n return 7\n if n % 4 == 1:\n return n + 2\n if n % 4 == 2:\n return n + 2\n if n % 4 == 3:\n return n - 1\n return n + 1\n", | |
| "title": "1006. Clumsy Factorial", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 948 | |
| }, | |
| { | |
| "code": "class Solution:\n def minDominoRotations(self, tops: list[int], bottoms: list[int]) -> int:\n for num in range(1, 7):\n if all(num in pair for pair in zip(tops, bottoms)):\n return len(tops) - max(tops.count(num), bottoms.count(num))\n return -1\n", | |
| "title": "1007. Minimum Domino Rotations For Equal Row", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 949 | |
| }, | |
| { | |
| "code": "class Solution:\n def bstFromPreorder(self, preorder: list[int]) -> TreeNode | None:\n root = TreeNode(preorder[0])\n stack = [root]\n\n for i in range(1, len(preorder)):\n parent = stack[-1]\n child = TreeNode(preorder[i])\n # Adjust the parent.\n while stack and stack[-1].val < child.val:\n parent = stack.pop()\n # Create parent-child link according to BST property.\n if parent.val > child.val:\n parent.left = child\n else:\n parent.right = child\n stack.append(child)\n\n return root\n", | |
| "title": "1008. Construct Binary Search Tree from Preorder Traversal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 950 | |
| }, | |
| { | |
| "code": "class Solution:\n def bitwiseComplement(self, n: int) -> int:\n mask = 1\n while mask < n:\n mask = (mask << 1) + 1\n return mask ^ n\n", | |
| "title": "1009. Complement of Base 10 Integer", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 951 | |
| }, | |
| { | |
| "code": "class Solution:\n def numPairsDivisibleBy60(self, time: list[int]) -> int:\n ans = 0\n count = [0] * 60\n\n for t in time:\n t %= 60\n ans += count[(60 - t) % 60]\n count[t] += 1\n\n return ans\n", | |
| "title": "1010. Pairs of Songs With Total Durations Divisible by 60", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 952 | |
| }, | |
| { | |
| "code": "class Solution:\n def shipWithinDays(self, weights: list[int], days: int) -> int:\n def shipDays(shipCapacity: int) -> int:\n shipDays = 1\n capacity = 0\n for weight in weights:\n if capacity + weight > shipCapacity:\n shipDays += 1\n capacity = weight\n else:\n capacity += weight\n return shipDays\n\n l = max(weights)\n r = sum(weights)\n return bisect.bisect_left(range(l, r), True,\n key=lambda m: shipDays(m) <= days) + l\n", | |
| "title": "1011. Capacity To Ship Packages Within D Days", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 953 | |
| }, | |
| { | |
| "code": "class Solution:\n def numDupDigitsAtMostN(self, n: int) -> int:\n return n - self._countSpecialNumbers(n)\n\n # Same as 2376. Count Special Integers\n def _countSpecialNumbers(self, n: int) -> int:\n s = str(n)\n\n @functools.lru_cache(None)\n def dp(i: int, used: int, tight: bool) -> int:\n \"\"\"\n Returns the number of special integers, considering the i-th digit, where\n `used` is the bitmask of the used digits, and `tight` indicates if the\n current digit is tightly bound.\n \"\"\"\n if i == len(s):\n return 1\n\n res = 0\n maxDigit = int(s[i]) if tight else 9\n\n for d in range(maxDigit + 1):\n # `d` is used.\n if used >> d & 1:\n continue\n # Use `d` now.\n nextTight = tight and (d == maxDigit)\n if used == 0 and d == 0: # Don't count leading 0s as used.\n res += dp(i + 1, used, nextTight)\n else:\n res += dp(i + 1, used | 1 << d, nextTight)\n\n return res\n\n return dp(0, 0, True) - 1 # - 0\n", | |
| "title": "1012. Numbers With Repeated Digits", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 954 | |
| }, | |
| { | |
| "code": "class Solution:\n def canThreePartsEqualSum(self, arr: list[int]) -> bool:\n summ = sum(arr)\n if summ % 3 != 0:\n return False\n\n average = summ // 3\n partCount = 0\n partSum = 0\n\n for a in arr:\n partSum += a\n if partSum == average:\n partCount += 1\n partSum = 0\n\n # edge case: arr = [0, 0, 0, 0] . partCount = 4.\n return partCount >= 3\n", | |
| "title": "1013. Partition Array Into Three Parts With Equal Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 955 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxScoreSightseeingPair(self, values: list[int]) -> int:\n ans = 0\n bestPrev = 0\n\n for value in values:\n ans = max(ans, value + bestPrev)\n bestPrev = max(bestPrev, value) - 1\n\n return ans\n", | |
| "title": "1014. Best Sightseeing Pair", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 956 | |
| }, | |
| { | |
| "code": "class Solution:\n def smallestRepunitDivByK(self, k: int) -> int:\n if k % 10 not in {1, 3, 7, 9}:\n return -1\n\n seen = set()\n n = 0\n\n for length in range(1, k + 1):\n n = (n * 10 + 1) % k\n if n == 0:\n return length\n if n in seen:\n return -1\n seen.add(n)\n\n return -1\n", | |
| "title": "1015. Smallest Integer Divisible by K", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 957 | |
| }, | |
| { | |
| "code": "class Solution:\n def queryString(self, s: str, n: int) -> bool:\n if n > 1511:\n return False\n\n for i in range(n, n // 2, -1):\n if format(i, 'b') not in s:\n return False\n\n return True\n", | |
| "title": "1016. Binary String With Substrings Representing 1 To N", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 958 | |
| }, | |
| { | |
| "code": "class Solution:\n def baseNeg2(self, n: int) -> str:\n ans = []\n\n while n != 0:\n ans.append(str(n % 2))\n n = -(n >> 1)\n\n return ''.join(reversed(ans)) if ans else '0'\n", | |
| "title": "1017. Convert to Base -2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 959 | |
| }, | |
| { | |
| "code": "class Solution:\n def prefixesDivBy5(self, nums: list[int]) -> list[bool]:\n ans = []\n curr = 0\n\n for num in nums:\n curr = (curr * 2 + num) % 5\n ans.append(curr % 5 == 0)\n\n return ans\n", | |
| "title": "1018. Binary Prefix Divisible By 5", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 960 | |
| }, | |
| { | |
| "code": "class Solution:\n def nextLargerNodes(self, head: ListNode) -> list[int]:\n ans = []\n stack = []\n\n while head:\n while stack and head.val > ans[stack[-1]]:\n index = stack.pop()\n ans[index] = head.val\n stack.append(len(ans))\n ans.append(head.val)\n head = head.next\n\n for i in stack:\n ans[i] = 0\n\n return ans\n", | |
| "title": "1019. Next Greater Node In Linked List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 961 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeOuterParentheses(self, s: str) -> str:\n ans = []\n opened = 0\n\n for c in s:\n if c == '(':\n opened += 1\n if opened > 1:\n ans.append(c)\n else: # c == ')'\n opened -= 1\n if opened > 0:\n ans.append(c)\n\n return ''.join(ans)\n", | |
| "title": "1021. Remove Outermost Parentheses", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 962 | |
| }, | |
| { | |
| "code": "class Solution:\n def sumRootToLeaf(self, root: TreeNode | None) -> int:\n ans = 0\n\n def dfs(root: TreeNode | None, val: int) -> None:\n nonlocal ans\n if not root:\n return\n val = val * 2 + root.val\n if not root.left and not root.right:\n ans += val\n dfs(root.left, val)\n dfs(root.right, val)\n\n dfs(root, 0)\n return ans\n", | |
| "title": "1022. Sum of Root To Leaf Binary Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 963 | |
| }, | |
| { | |
| "code": "class Solution:\n def camelMatch(self, queries: list[str], pattern: str) -> list[bool]:\n def isMatch(query: str) -> bool:\n j = 0\n for c in query:\n if j < len(pattern) and c == pattern[j]:\n j += 1\n elif c.isupper():\n return False\n return j == len(pattern)\n\n return [isMatch(query) for query in queries]\n", | |
| "title": "1023. Camelcase Matching", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 964 | |
| }, | |
| { | |
| "code": "class Solution:\n def videoStitching(self, clips: list[list[int]], time: int) -> int:\n ans = 0\n end = 0\n farthest = 0\n\n clips.sort()\n\n i = 0\n while farthest < time:\n while i < len(clips) and clips[i][0] <= end:\n farthest = max(farthest, clips[i][1])\n i += 1\n if end == farthest:\n return -1\n ans += 1\n end = farthest\n\n return ans\n", | |
| "title": "1024. Video Stitching", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 965 | |
| }, | |
| { | |
| "code": "class Solution:\n def divisorGame(self, n: int) -> bool:\n return n % 2 == 0\n", | |
| "title": "1025. Divisor Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 966 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestArithSeqLength(self, nums: list[int]) -> int:\n n = len(nums)\n ans = 0\n # dp[i][k] := the length of the longest arithmetic subsequence of nums[0..i]\n # with k = diff + 500\n dp = [[0] * 1001 for _ in range(n)]\n\n for i in range(n):\n for j in range(i):\n k = nums[i] - nums[j] + 500\n dp[i][k] = max(2, dp[j][k] + 1)\n ans = max(ans, dp[i][k])\n\n return ans\n", | |
| "title": "1027. Longest Arithmetic Subsequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 967 | |
| }, | |
| { | |
| "code": "class Solution:\n def recoverFromPreorder(self, traversal: str) -> TreeNode | None:\n i = 0\n\n def recoverFromPreorder(depth: int) -> TreeNode | None:\n nonlocal i\n nDashes = 0\n while i + nDashes < len(traversal) and traversal[i + nDashes] == '-':\n nDashes += 1\n if nDashes != depth:\n return None\n\n i += depth\n start = i\n while i < len(traversal) and traversal[i].isdigit():\n i += 1\n\n return TreeNode(int(traversal[start:i]),\n recoverFromPreorder(depth + 1),\n recoverFromPreorder(depth + 1))\n\n return recoverFromPreorder(0)\n", | |
| "title": "1028. Recover a Tree From Preorder Traversal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 968 | |
| }, | |
| { | |
| "code": "class Solution:\n def twoCitySchedCost(self, costs: list[list[int]]) -> int:\n n = len(costs) // 2\n\n # How much money can we save if we fly a person to A instead of B?\n # To save money, we should\n # 1. Fly the person with the maximum saving to A.\n # 2. Fly the person with the minimum saving to B.\n\n # Sort `costs` in ascending order by the money saved if we fly a person to\n # B instead of A.\n costs.sort(key=lambda x: x[0] - x[1])\n return sum(costs[i][0] + costs[i + n][1] for i in range(n))\n", | |
| "title": "1029. Two City Scheduling", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 969 | |
| }, | |
| { | |
| "code": "class Solution:\n def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> list[list[int]]:\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n ans = []\n q = collections.deque([(rCenter, cCenter)])\n seen = {(rCenter, cCenter)}\n\n while q:\n i, j = q.popleft()\n ans.append([i, j])\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x == rows or y < 0 or y == cols:\n continue\n if (x, y) in seen:\n continue\n seen.add((x, y))\n q.append((x, y))\n\n return ans\n", | |
| "title": "1030. Matrix Cells in Distance Order", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 970 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxSumTwoNoOverlap(\n self,\n nums: list[int],\n firstLen: int,\n secondLen: int,\n ) -> int:\n def helper(l: int, r: int) -> int:\n n = len(nums)\n left = [0] * n\n summ = 0\n\n for i in range(n):\n summ += nums[i]\n if i >= l:\n summ -= nums[i - l]\n if i >= l - 1:\n left[i] = max(left[i - 1], summ) if i > 0 else summ\n\n right = [0] * n\n summ = 0\n\n for i in reversed(range(n)):\n summ += nums[i]\n if i <= n - r - 1:\n summ -= nums[i + r]\n if i <= n - r:\n right[i] = max(right[i + 1], summ) if i < n - 1 else summ\n\n return max(left[i] + right[i + 1] for i in range(n - 1))\n\n return max(helper(firstLen, secondLen), helper(secondLen, firstLen))\n", | |
| "title": "1031. Maximum Sum of Two Non-Overlapping Subarrays", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 971 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: dict[str, TrieNode] = {}\n self.isWord = False\n\n\nclass StreamChecker:\n def __init__(self, words: list[str]):\n self.root = TrieNode()\n self.letters = []\n for word in words:\n self._insert(word)\n\n def query(self, letter: str) -> bool:\n self.letters.append(letter)\n node = self.root\n for c in reversed(self.letters):\n if c not in node.children:\n return False\n node = node.children[c]\n if node.isWord:\n return True\n return False\n\n def _insert(self, word: str) -> None:\n node = self.root\n for c in reversed(word):\n node = node.children.setdefault(c, TrieNode())\n node.isWord = True\n", | |
| "title": "1032. Stream of Characters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 972 | |
| }, | |
| { | |
| "code": "class Solution:\n def numMovesStones(self, a: int, b: int, c: int) -> list[int]:\n nums = sorted([a, b, c])\n\n if nums[2] - nums[0] == 2:\n return [0, 0]\n return [1 if min(nums[1] - nums[0], nums[2] - nums[1]) <= 2 else 2,\n nums[2] - nums[0] - 2]\n", | |
| "title": "1033. Moving Stones Until Consecutive", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 973 | |
| }, | |
| { | |
| "code": "class Solution:\n def colorBorder(\n self,\n grid: list[list[int]],\n r0: int,\n c0: int,\n color: int\n ) -> list[list[int]]:\n def dfs(i: int, j: int, startColor: int) -> None:\n if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]):\n return\n if grid[i][j] != startColor:\n return\n\n grid[i][j] = -startColor\n dfs(i + 1, j, startColor)\n dfs(i - 1, j, startColor)\n dfs(i, j + 1, startColor)\n dfs(i, j - 1, startColor)\n\n # If this cell is already on the boarder, it must be painted later.\n if i == 0 or i == len(grid) - 1 or j == 0 or j == len(grid[0]) - 1:\n return\n\n if (abs(grid[i + 1][j]) == startColor and\n abs(grid[i - 1][j]) == startColor and\n abs(grid[i][j + 1]) == startColor and\n abs(grid[i][j - 1]) == startColor):\n grid[i][j] = startColor\n\n dfs(r0, c0, grid[r0][c0])\n\n for i, row in enumerate(grid):\n for j, num in enumerate(row):\n if num < 0:\n grid[i][j] = color\n\n return grid\n", | |
| "title": "1034. Coloring A Border", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 974 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n m = len(nums1)\n n = len(nums2)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n dp[i][j] = (dp[i - 1][j - 1] + 1\n if nums1[i - 1] == nums2[j - 1]\n else max(dp[i - 1][j], dp[i][j - 1]))\n\n return dp[m][n]\n", | |
| "title": "1035. Uncrossed Lines", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 975 | |
| }, | |
| { | |
| "code": "class Solution:\n def isEscapePossible(\n self,\n blocked: list[list[int]],\n source: list[int],\n target: list[int]\n ) -> bool:\n def dfs(i: int, j: int, target: list[int], seen: set) -> bool:\n if i < 0 or i >= 10**6 or j < 0 or j >= 10**6:\n return False\n if (i, j) in blocked or (i, j) in seen:\n return False\n seen.add((i, j))\n return (len(seen) > (1 + 199) * 199 // 2 or [i, j] == target or\n dfs(i + 1, j, target, seen) or\n dfs(i - 1, j, target, seen) or\n dfs(i, j + 1, target, seen) or\n dfs(i, j - 1, target, seen))\n\n blocked = set(tuple(b) for b in blocked)\n return (dfs(source[0], source[1], target, set()) and\n dfs(target[0], target[1], source, set()))\n", | |
| "title": "1036. Escape a Large Maze", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 976 | |
| }, | |
| { | |
| "code": "class Solution:\n def isBoomerang(self, points: list[list[int]]) -> bool:\n return ((points[1][0] - points[0][0]) * (points[2][1] - points[1][1]) !=\n (points[1][1] - points[0][1]) * (points[2][0] - points[1][0]))\n", | |
| "title": "1037. Valid Boomerang", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 977 | |
| }, | |
| { | |
| "code": "class Solution:\n def minScoreTriangulation(self, values: list[int]) -> int:\n n = len(values)\n dp = [[0] * n for _ in range(n)]\n\n for j in range(2, n):\n for i in range(j - 2, -1, -1):\n dp[i][j] = math.inf\n for k in range(i + 1, j):\n dp[i][j] = min(dp[i][j], dp[i][k] + values[i]\n * values[k] * values[j] + dp[k][j])\n\n return dp[0][n - 1]\n", | |
| "title": "1039. Minimum Score Triangulation of Polygon", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 978 | |
| }, | |
| { | |
| "code": "class Solution:\n def numMovesStonesII(self, stones: list[int]) -> list[int]:\n n = len(stones)\n minMoves = n\n\n stones.sort()\n\n l = 0\n for r, stone in enumerate(stones):\n while stone - stones[l] + 1 > n:\n l += 1\n alreadyStored = r - l + 1\n if alreadyStored == n - 1 and stone - stones[l] + 1 == n - 1:\n minMoves = 2\n else:\n minMoves = min(minMoves, n - alreadyStored)\n\n return [minMoves, max(stones[n - 1] - stones[1] - n + 2, stones[n - 2] - stones[0] - n + 2)]\n", | |
| "title": "1040. Moving Stones Until Consecutive II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 979 | |
| }, | |
| { | |
| "code": "class Solution:\n def isRobotBounded(self, instructions: str) -> bool:\n x = 0\n y = 0\n d = 0\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n\n for instruction in instructions:\n if instruction == 'G':\n x += directions[d][0]\n y += directions[d][1]\n elif instruction == 'L':\n d = (d + 3) % 4\n else:\n d = (d + 1) % 4\n\n return (x, y) == (0, 0) or d > 0\n", | |
| "title": "1041. Robot Bounded In Circle", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 980 | |
| }, | |
| { | |
| "code": "class Solution:\n def gardenNoAdj(self, n: int, paths: list[list[int]]) -> list[int]:\n ans = [0] * n # ans[i] := 1, 2, 3, or 4\n graph = [[] for _ in range(n)]\n\n for x, y in paths:\n u = x - 1\n v = y - 1\n graph[u].append(v)\n graph[v].append(u)\n\n for u in range(n):\n used = functools.reduce(operator.or_, (1 << ans[v] for v in graph[u]), 0)\n ans[u] = next(type_\n for type_ in range(1, 5)\n if not (used >> type_ & 1))\n\n return ans\n", | |
| "title": "1042. Flower Planting With No Adjacent", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 981 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxSumAfterPartitioning(self, arr: list[int], k: int) -> int:\n n = len(arr)\n dp = [0] * (n + 1)\n\n for i in range(1, n + 1):\n mx = -math.inf\n for j in range(1, min(i, k) + 1):\n mx = max(mx, arr[i - j])\n dp[i] = max(dp[i], dp[i - j] + mx * j)\n\n return dp[n]\n", | |
| "title": "1043. Partition Array for Maximum Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 982 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestDupSubstring(self, s: str) -> str:\n BASE = 26\n HASH = 1_000_000_007\n bestStart = -1\n l = 1\n r = len(s)\n\n def val(c: str) -> int:\n return ord(c) - ord('a')\n\n # k := the length of the substring to be hashed\n def getStart(k: int) -> int | None:\n maxPow = pow(BASE, k - 1, HASH)\n hashToStart = collections.defaultdict(list)\n h = 0\n\n # Compute the hash value of s[:k].\n for i in range(k):\n h = (h * BASE + val(s[i])) % HASH\n hashToStart[h].append(0)\n\n # Compute the rolling hash by Rabin Karp.\n for i in range(k, len(s)):\n startIndex = i - k + 1\n h = (h - maxPow * val(s[i - k])) % HASH\n h = (h * BASE + val(s[i])) % HASH\n if h in hashToStart:\n currSub = s[startIndex:startIndex + k]\n for start in hashToStart[h]:\n if s[start:start + k] == currSub:\n return startIndex\n hashToStart[h].append(startIndex)\n\n while l < r:\n m = (l + r) // 2\n start: int | None = getStart(m)\n if start:\n bestStart = start\n l = m + 1\n else:\n r = m\n\n if bestStart == -1:\n return ''\n if getStart(l):\n return s[bestStart:bestStart + l]\n return s[bestStart:bestStart + l - 1]\n", | |
| "title": "1044. Longest Duplicate Substring", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 983 | |
| }, | |
| { | |
| "code": "SELECT customer_id\nFROM Customer\nGROUP BY 1\nHAVING COUNT(DISTINCT product_key) = (\n SELECT COUNT(*) FROM Product\n );\n", | |
| "title": "1045. Customers Who Bought All Products", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 984 | |
| }, | |
| { | |
| "code": "class Solution:\n def lastStoneWeight(self, stones: list[int]) -> int:\n pq = [-stone for stone in stones]\n heapq.heapify(pq)\n\n while len(pq) >= 2:\n n1 = -heapq.heappop(pq)\n n2 = -heapq.heappop(pq)\n if n1 != n2:\n heapq.heappush(pq, -(n1 - n2))\n\n return 0 if not pq else -pq[0]\n", | |
| "title": "1046. Last Stone Weight", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 985 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestStrChain(self, words: list[str]) -> int:\n dp = {}\n\n for word in sorted(words, key=len):\n dp[word] = max(dp.get(word[:i] + word[i + 1:], 0) +\n 1 for i in range(len(word)))\n\n return max(dp.values())\n", | |
| "title": "1048. Longest String Chain", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 986 | |
| }, | |
| { | |
| "code": "class Solution:\n def lastStoneWeightII(self, stones: list[int]) -> int:\n summ = sum(stones)\n s = 0\n dp = [True] + [False] * summ\n\n for stone in stones:\n for w in range(summ // 2 + 1)[::-1]:\n if w >= stone:\n dp[w] = dp[w] or dp[w - stone]\n if dp[w]:\n s = max(s, w)\n\n return summ - 2 * s\n", | |
| "title": "1049. Last Stone Weight II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 987 | |
| }, | |
| { | |
| "code": "SELECT actor_id, director_id\nFROM ActorDirector\nGROUP BY 1, 2\nHAVING COUNT(*) >= 3;\n", | |
| "title": "1050. Actors and Directors Who Cooperated At Least Three Times", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 988 | |
| }, | |
| { | |
| "code": "class Solution:\n def heightChecker(self, heights: list[int]) -> int:\n ans = 0\n currentHeight = 1\n count = [0] * 101\n\n for height in heights:\n count[height] += 1\n\n for height in heights:\n while count[currentHeight] == 0:\n currentHeight += 1\n if height != currentHeight:\n ans += 1\n count[currentHeight] -= 1\n\n return ans\n", | |
| "title": "1051. Height Checker", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 989 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxSatisfied(\n self,\n customers: list[int],\n grumpy: list[int],\n X: int,\n ) -> int:\n satisfied = sum(c for i, c in enumerate(customers) if grumpy[i] == 0)\n madeSatisfied = 0\n windowSatisfied = 0\n\n for i, customer in enumerate(customers):\n if grumpy[i] == 1:\n windowSatisfied += customer\n if i >= X and grumpy[i - X] == 1:\n windowSatisfied -= customers[i - X]\n madeSatisfied = max(madeSatisfied, windowSatisfied)\n\n return satisfied + madeSatisfied\n", | |
| "title": "1052. Grumpy Bookstore Owner", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 990 | |
| }, | |
| { | |
| "code": "class Solution:\n def prevPermOpt1(self, arr: list[int]) -> list[int]:\n n = len(arr)\n l = n - 2\n r = n - 1\n\n while l >= 0 and arr[l] <= arr[l + 1]:\n l -= 1\n if l < 0:\n return arr\n while arr[r] >= arr[l] or arr[r] == arr[r - 1]:\n r -= 1\n arr[l], arr[r] = arr[r], arr[l]\n\n return arr\n", | |
| "title": "1053. Previous Permutation With One Swap", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 991 | |
| }, | |
| { | |
| "code": "class Solution:\n def rearrangeBarcodes(self, barcodes: list[int]) -> list[int]:\n ans = [0] * len(barcodes)\n count = collections.Counter(barcodes)\n i = 0 # ans' index\n maxNum = max(count, key=count.get)\n\n def fillAns(num: int) -> None:\n nonlocal i\n while count[num]:\n ans[i] = num\n i = i + 2 if i + 2 < len(barcodes) else 1\n count[num] -= 1\n\n fillAns(maxNum)\n for num in count.keys():\n fillAns(num)\n\n return ans\n", | |
| "title": "1054. Distant Barcodes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 992 | |
| }, | |
| { | |
| "code": "class Solution:\n def confusingNumber(self, n: int) -> bool:\n s = str(n)\n rotated = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}\n rotatedNum = []\n\n for c in s[::-1]:\n if c not in rotated:\n return False\n rotatedNum.append(rotated[c])\n\n return ''.join(rotatedNum) != s\n", | |
| "title": "1056. Confusing Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 993 | |
| }, | |
| { | |
| "code": "class Solution:\n def assignBikes(\n self,\n workers: list[list[int]],\n bikes: list[list[int]],\n ) -> list[int]:\n ans = [-1] * len(workers)\n usedBikes = [False] * len(bikes)\n # buckets[k] := (i, j), where k = dist(workers[i], bikes[j])\n buckets = [[] for _ in range(2001)]\n\n def dist(p1: list[int], p2: list[int]) -> int:\n return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])\n\n for i, worker in enumerate(workers):\n for j, bike in enumerate(bikes):\n buckets[dist(worker, bike)].append((i, j))\n\n for k in range(2001):\n for i, j in buckets[k]:\n if ans[i] == -1 and not usedBikes[j]:\n ans[i] = j\n usedBikes[j] = True\n\n return ans\n", | |
| "title": "1057. Campus Bikes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 994 | |
| }, | |
| { | |
| "code": "class Solution:\n def minimizeError(self, prices: list[str], target: int) -> str:\n # A[i] := (costCeil - costFloor, costCeil, costFloor)\n # The lower the costCeil - costFloor is, the cheaper to ceil it.\n A = []\n sumFloored = 0\n sumCeiled = 0\n\n for price in map(float, prices):\n floored = math.floor(price)\n ceiled = math.ceil(price)\n sumFloored += floored\n sumCeiled += ceiled\n costFloor = price - floored\n costCeil = ceiled - price\n A.append((costCeil - costFloor, costCeil, costFloor))\n\n if not sumFloored <= target <= sumCeiled:\n return '-1'\n\n A.sort()\n nCeiled = target - sumFloored\n return '{:.3f}'.format(sum(a[1] for a in A[:nCeiled]) +\n sum(a[2] for a in A[nCeiled:]))\n", | |
| "title": "1058. Minimize Rounding Error to Meet Target", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 995 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestRepeatingSubstring(self, s: str) -> int:\n n = len(s)\n ans = 0\n # dp[i][j] := the number of repeating characters of s[0..i) and s[0..j)\n dp = [[0] * (n + 1) for _ in range(n + 1)]\n\n for i in range(1, n + 1):\n for j in range(i + 1, n + 1):\n if s[i - 1] == s[j - 1]:\n dp[i][j] = 1 + dp[i - 1][j - 1]\n ans = max(ans, dp[i][j])\n\n return ans\n", | |
| "title": "1062. Longest Repeating Substring", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 996 | |
| }, | |
| { | |
| "code": "class Solution:\n def validSubarrays(self, nums: list[int]) -> int:\n # For each `num` in `nums`, each element x in the stack can be the leftmost\n # element s.t. [x, num] forms a valid subarray, so the size of the stack is\n # the number of valid subarrays ending in the current number.\n #\n # e.g. nums = [1, 3, 2]\n # num = 1, stack = [1] -> valid subarray is [1]\n # num = 3, stack = [1, 3] -> valid subarrays are [1, 3], [3]\n # num = 2, stack = [1, 2] -> valid subarrays are [1, 3, 2], [2]\n ans = 0\n stack = []\n\n for num in nums:\n while stack and stack[-1] > num:\n stack.pop()\n stack.append(num)\n ans += len(stack)\n\n return ans\n", | |
| "title": "1063. Number of Valid Subarrays", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 997 | |
| }, | |
| { | |
| "code": "class Solution:\n def fixedPoint(self, arr: list[int]) -> int:\n l = 0\n r = len(arr) - 1\n\n # Since arr[i] is strictly increasing, arr[i] - i will also be increasing.\n # Therefore, binary search `arr` for the first arr[i] - i = 0.\n while l < r:\n m = (l + r) // 2\n if arr[m] - m >= 0:\n r = m\n else:\n l = m + 1\n\n return l if arr[l] == l else -1\n", | |
| "title": "1064. Fixed Point", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 998 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: dict[str, TrieNode] = {}\n self.isWord = False\n\n\nclass Solution:\n def indexPairs(self, text: str, words: list[str]) -> list[list[int]]:\n ans = []\n root = TrieNode()\n\n for word in words:\n node: TrieNode = root\n for c in word:\n node = node.children.setdefault(c, TrieNode())\n node.isWord = True\n\n # Scan each text[i..j].\n for i in range(len(text)):\n node: TrieNode = root\n for j in range(i, len(text)):\n c = text[j]\n if c not in node.children:\n break\n node = node.children[c]\n if node.isWord:\n ans.append([i, j])\n\n return ans\n", | |
| "title": "1065. Index Pairs of a String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 999 | |
| }, | |
| { | |
| "code": "class Solution:\n def assignBikes(\n self,\n workers: list[list[int]],\n bikes: list[list[int]],\n ) -> int:\n def dist(p1: list[int], p2: list[int]) -> int:\n return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])\n\n @functools.lru_cache(None)\n def dp(workerIndex: int, used: int) -> int:\n \"\"\"\n Returns the minimum Manhattan distances to assign bikes to\n workers[workerIndex..n), where `used` is the bitmask of the used bikes.\n \"\"\"\n if workerIndex == len(workers):\n return 0\n return min(\n (dist(workers[workerIndex],\n bike) + dp(workerIndex + 1, used | 1 << i) for i,\n bike in enumerate(bikes) if not used >> i & 1),\n default=math.inf)\n\n return dp(0, 0)\n", | |
| "title": "1066. Campus Bikes II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1000 | |
| }, | |
| { | |
| "code": "SELECT\n Product.product_name,\n Sales.year,\n Sales.price\nFROM Sales\nINNER JOIN Product\n USING (product_id);\n", | |
| "title": "1068. Product Sales Analysis I", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1001 | |
| }, | |
| { | |
| "code": "SELECT product_id, SUM(quantity) AS total_quantity\nFROM Sales\nGROUP BY 1;\n", | |
| "title": "1069. Product Sales Analysis II", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1002 | |
| }, | |
| { | |
| "code": "WITH\n ProductToYear AS (\n SELECT product_id, MIN(year) AS year\n FROM Sales\n GROUP BY 1\n )\nSELECT\n Sales.product_id,\n ProductToYear.year AS first_year,\n Sales.quantity,\n Sales.price\nFROM Sales\nINNER JOIN ProductToYear\n USING (product_id, year);\n", | |
| "title": "1070. Product Sales Analysis III", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1003 | |
| }, | |
| { | |
| "code": "class Solution:\n def gcdOfStrings(self, str1: str, str2: str) -> str:\n if str1 + str2 != str2 + str1:\n return ''\n g = math.gcd(len(str1), len(str2))\n return str1[:g]\n", | |
| "title": "1071. Greatest Common Divisor of Strings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1004 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxEqualRowsAfterFlips(self, matrix: list[list[int]]) -> int:\n patterns = [tuple(a ^ row[0] for a in row) for row in matrix]\n return max(Counter(patterns).values())\n", | |
| "title": "1072. Flip Columns For Maximum Number of Equal Rows", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1005 | |
| }, | |
| { | |
| "code": "class Solution:\n def addNegabinary(self, arr1: list[int], arr2: list[int]) -> list[int]:\n ans = []\n carry = 0\n\n while carry != 0 or arr1 or arr2:\n if arr1:\n carry += arr1.pop()\n if arr2:\n carry += arr2.pop()\n ans.append(carry & 1)\n carry = -(carry >> 1)\n\n while len(ans) > 1 and ans[-1] == 0:\n ans.pop()\n\n return ans[::-1]\n", | |
| "title": "1073. Adding Two Negabinary Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1006 | |
| }, | |
| { | |
| "code": "class Solution:\n def numSubmatrixSumTarget(self, matrix: list[list[int]], target: int) -> int:\n m = len(matrix)\n n = len(matrix[0])\n ans = 0\n\n # Transfer each row in the matrix to the prefix sum.\n for row in matrix:\n for i in range(1, n):\n row[i] += row[i - 1]\n\n for baseCol in range(n):\n for j in range(baseCol, n):\n prefixCount = collections.Counter({0: 1})\n summ = 0\n for i in range(m):\n if baseCol > 0:\n summ -= matrix[i][baseCol - 1]\n summ += matrix[i][j]\n ans += prefixCount[summ - target]\n prefixCount[summ] += 1\n\n return ans\n", | |
| "title": "1074. Number of Submatrices That Sum to Target", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1007 | |
| }, | |
| { | |
| "code": "SELECT\n Project.project_id,\n ROUND(AVG(Employee.experience_years), 2) AS average_years\nFROM Project\nINNER JOIN Employee\n USING (employee_id)\nGROUP BY 1;\n", | |
| "title": "1075. Project Employees I", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1008 | |
| }, | |
| { | |
| "code": "WITH\n RankedProjects AS (\n SELECT project_id, RANK() OVER(ORDER BY COUNT(*) DESC) AS `rank`\n FROM Project\n GROUP BY 1\n )\nSELECT project_id\nFROM RankedProjects\nWHERE `rank` = 1;\n", | |
| "title": "1076. Project Employees II", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1009 | |
| }, | |
| { | |
| "code": "WITH\n RankedProjectToEmployee AS (\n SELECT\n Project.project_id,\n Project.employee_id,\n RANK() OVER(\n PARTITION BY Project.project_id\n ORDER BY Employee.experience_years DESC\n ) AS `rank`\n FROM Project\n INNER JOIN Employee\n USING (employee_id)\n )\nSELECT project_id, employee_id\nFROM RankedProjectToEmployee\nWHERE `rank` = 1;\n", | |
| "title": "1077. Project Employees III", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1010 | |
| }, | |
| { | |
| "code": "class Solution:\n def findOcurrences(self, text: str, first: str, second: str) -> list[str]:\n words = text.split()\n return [c for a, b, c in zip(words, words[1:], words[2:]) if a == first and b == second]\n", | |
| "title": "1078. Occurrences After Bigram", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1011 | |
| }, | |
| { | |
| "code": "class Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n count = collections.Counter(tiles)\n\n def dfs(count: dict[int, int]) -> int:\n possibleSequences = 0\n\n for k, v in count.items():\n if v == 0:\n continue\n # Put c in the current position. We only care about the number of possible\n # sequences of letters but don't care about the actual combination.\n count[k] -= 1\n possibleSequences += 1 + dfs(count)\n count[k] += 1\n\n return possibleSequences\n\n return dfs(count)\n", | |
| "title": "1079. Letter Tile Possibilities", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1012 | |
| }, | |
| { | |
| "code": "class Solution:\n def sufficientSubset(\n self,\n root: TreeNode | None,\n limit: int\n ) -> TreeNode | None:\n if not root:\n return None\n if not root.left and not root.right:\n return None if root.val < limit else root\n root.left = self.sufficientSubset(root.left, limit - root.val)\n root.right = self.sufficientSubset(root.right, limit - root.val)\n return None if not root.left and not root.right else root\n", | |
| "title": "1080. Insufficient Nodes in Root to Leaf Paths", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1013 | |
| }, | |
| { | |
| "code": "class Solution:\n def smallestSubsequence(self, text: str) -> str:\n ans = []\n count = collections.Counter(text)\n used = [False] * 26\n\n for c in text:\n count[c] -= 1\n if used[ord(c) - ord('a')]:\n continue\n while ans and ans[-1] > c and count[ans[-1]] > 0:\n used[ord(ans[-1]) - ord('a')] = False\n ans.pop()\n ans.append(c)\n used[ord(ans[-1]) - ord('a')] = True\n\n return ''.join(ans)\n", | |
| "title": "1081. Smallest Subsequence of Distinct Characters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1014 | |
| }, | |
| { | |
| "code": "WITH\n SellerToPrice AS (\n SELECT seller_id, SUM(price) AS price\n FROM Sales\n GROUP BY 1\n )\nSELECT seller_id\nFROM SellerToPrice\nWHERE price = (\n SELECT MAX(price)\n FROM SellerToPrice\n );\n", | |
| "title": "1082. Sales Analysis I", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1015 | |
| }, | |
| { | |
| "code": "SELECT Sales.buyer_id\nFROM Sales\nINNER JOIN Product\n USING (product_id)\nGROUP BY 1\nHAVING\n SUM(Product.product_name = 'S8') > 0\n AND SUM(Product.product_name = 'iPhone') = 0;\n", | |
| "title": "1083. Sales Analysis II", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1016 | |
| }, | |
| { | |
| "code": "SELECT\n Product.product_id,\n Product.product_name\nFROM Product\nINNER JOIN Sales\n USING (product_id)\nGROUP BY 1, 2\nHAVING SUM(\n Sales.sale_date < '2019-01-01'\n OR Sales.sale_date > '2019-03-31'\n ) = 0;\n", | |
| "title": "1084. Sales Analysis III", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1017 | |
| }, | |
| { | |
| "code": "class Solution:\n def sumOfDigits(self, nums: list[int]) -> int:\n return sum(int(d) for d in str(min(nums))) & 1 ^ 1\n", | |
| "title": "1085. Sum of Digits in the Minimum Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1018 | |
| }, | |
| { | |
| "code": "class Solution:\n def highFive(self, items: list[list[int]]) -> list[list[int]]:\n idToScores = collections.defaultdict(list)\n\n for id, score in items:\n heapq.heappush(idToScores[id], score)\n if len(idToScores[id]) > 5:\n heapq.heappop(idToScores[id])\n\n return [[id, sum(scores) // 5] for id, scores in sorted(idToScores.items())]\n", | |
| "title": "1086. High Five", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1019 | |
| }, | |
| { | |
| "code": "class Solution:\n def expand(self, s: str) -> list[str]:\n ans = []\n\n def dfs(i: int, path: list[str]) -> None:\n if i == len(s):\n ans.append(''.join(path))\n return\n if s[i] == '{':\n nextRightBraceIndex = s.find('}', i)\n for c in s[i + 1:nextRightBraceIndex].split(','):\n path.append(c)\n dfs(nextRightBraceIndex + 1, path)\n path.pop()\n else: # s[i] != '{'\n path.append(s[i])\n dfs(i + 1, path)\n path.pop()\n\n dfs(0, [])\n return sorted(ans)\n", | |
| "title": "1087. Brace Expansion", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1020 | |
| }, | |
| { | |
| "code": "class Solution:\n def confusingNumberII(self, n: int) -> int:\n digitToRotated = [(0, 0), (1, 1), (6, 9), (8, 8), (9, 6)]\n\n def dfs(num: int, rotatedNum: int, unit: int) -> int:\n ans = 0 if num == rotatedNum else 1\n # Add one more digit\n for digit, rotated in digitToRotated:\n if digit == 0 and num == 0:\n continue\n nextNum = num * 10 + digit\n if nextNum > n:\n break\n ans += dfs(nextNum, rotated * unit + rotatedNum, unit * 10)\n return ans\n\n return dfs(0, 0, 1)\n", | |
| "title": "1088. Confusing Number II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1021 | |
| }, | |
| { | |
| "code": "class Solution:\n def duplicateZeros(self, arr: list[int]) -> None:\n zeros = arr.count(0)\n i = len(arr) - 1\n j = len(arr) + zeros - 1\n\n while i < j:\n if j < len(arr):\n arr[j] = arr[i]\n if arr[i] == 0:\n j -= 1\n if j < len(arr):\n arr[j] = arr[i]\n i -= 1\n j -= 1\n", | |
| "title": "1089. Duplicate Zeros", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1022 | |
| }, | |
| { | |
| "code": "class Solution:\n def sampleStats(self, count: list[int]) -> list[float]:\n minimum = next((i for i, num in enumerate(count) if num), None)\n maximum = next((i for i, num in reversed(\n list(enumerate(count))) if num), None)\n n = sum(count)\n mean = sum(i * c / n for i, c in enumerate(count))\n mode = count.index(max(count))\n\n numCount = 0\n leftMedian = 0\n for i, c in enumerate(count):\n numCount += c\n if numCount >= n / 2:\n leftMedian = i\n break\n\n numCount = 0\n rightMedian = 0\n for i, c in reversed(list(enumerate(count))):\n numCount += c\n if numCount >= n / 2:\n rightMedian = i\n break\n\n return [minimum, maximum, mean, (leftMedian + rightMedian) / 2, mode]\n", | |
| "title": "1093. Statistics from a Large Sample", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1023 | |
| }, | |
| { | |
| "code": "# \"\"\"\n# This is MountainArray's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n# Class MountainArray:\n# def get(self, index: int) -> int:\n# def length(self) -> int:\n\nclass Solution:\n def findInMountainArray(\n self,\n target: int,\n mountain_arr: 'MountainArray',\n ) -> int:\n n = mountain_arr.length()\n peakIndex = self.peakIndexInMountainArray(mountain_arr, 0, n - 1)\n\n leftIndex = self.searchLeft(mountain_arr, target, 0, peakIndex)\n if mountain_arr.get(leftIndex) == target:\n return leftIndex\n\n rightIndex = self.searchRight(mountain_arr, target, peakIndex + 1, n - 1)\n if mountain_arr.get(rightIndex) == target:\n return rightIndex\n\n return -1\n\n # 852. Peak Index in a Mountain Array\n def peakIndexInMountainArray(self, A: 'MountainArray', l: int, r: int) -> int:\n while l < r:\n m = (l + r) // 2\n if A.get(m) < A.get(m + 1):\n l = m + 1\n else:\n r = m\n return l\n\n def searchLeft(self, A: 'MountainArray', target: int, l: int, r: int) -> int:\n while l < r:\n m = (l + r) // 2\n if A.get(m) < target:\n l = m + 1\n else:\n r = m\n return l\n\n def searchRight(self, A: 'MountainArray', target: int, l: int, r: int) -> int:\n while l < r:\n m = (l + r) // 2\n if A.get(m) > target:\n l = m + 1\n else:\n r = m\n return l\n", | |
| "title": "1095. Find in Mountain Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1024 | |
| }, | |
| { | |
| "code": "class Solution:\n def braceExpansionII(self, expression: str) -> list[str]:\n def merge(groups: list[list[str]], group: list[str]) -> None:\n if not groups[-1]:\n groups[-1] = group\n return\n\n groups[-1] = [word1 + word2 for word1 in groups[-1]\n for word2 in group]\n\n def dfs(s: int, e: int) -> list[str]:\n groups = [[]]\n layer = 0\n\n for i in range(s, e + 1):\n c = expression[i]\n if c == '{':\n layer += 1\n if layer == 1:\n left = i + 1\n elif c == '}':\n layer -= 1\n if layer == 0:\n group = dfs(left, i - 1)\n merge(groups, group)\n elif c == ',' and layer == 0:\n groups.append([])\n elif layer == 0:\n merge(groups, [c])\n\n return sorted(list({word for group in groups for word in group}))\n\n return dfs(0, len(expression) - 1)\n", | |
| "title": "1096. Brace Expansion II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1025 | |
| }, | |
| { | |
| "code": "WITH\n PlayerToInstallDate AS (\n SELECT player_id, MIN(event_date) AS install_dt\n FROM Activity\n GROUP BY 1\n )\nSELECT PlayerToInstallDate.install_dt,\n COUNT(*) AS installs,\n ROUND(\n SUM(IF(Activity.event_date, 1, 0)) / COUNT(PlayerToInstallDate.install_dt),\n 2\n ) AS Day1_retention\nFROM PlayerToInstallDate\nLEFT JOIN Activity\n ON (\n PlayerToInstallDate.player_id = Activity.player_id\n AND DATEDIFF(Activity.event_date, PlayerToInstallDate.install_dt) = 1)\nGROUP BY 1;\n", | |
| "title": "1097. Game Play Analysis V", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1026 | |
| }, | |
| { | |
| "code": "SELECT\n Books.book_id,\n ANY_VALUE(Books.name) AS name\nFROM Books\nLEFT JOIN Orders\n ON (\n Books.book_id = Orders.book_id\n AND Orders.dispatch_date BETWEEN '2018-06-23' AND '2019-06-23')\nWHERE DATEDIFF('2019-06-23', Books.available_from) > 30\nGROUP BY 1\nHAVING IFNULL(SUM(Orders.quantity), 0) < 10;\n", | |
| "title": "1098. Unpopular Books", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1027 | |
| }, | |
| { | |
| "code": "class Solution:\n def twoSumLessThanK(self, nums: list[int], k: int) -> int:\n if len(nums) < 2:\n return -1\n\n ans = -1 # Note the constrathat nums[i] > 0.\n l = 0\n r = len(nums) - 1\n\n nums.sort()\n\n while l < r:\n if nums[l] + nums[r] < k:\n ans = max(ans, nums[l] + nums[r])\n l += 1\n else:\n r -= 1\n\n return ans\n", | |
| "title": "1099. Two Sum Less Than K", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1028 | |
| }, | |
| { | |
| "code": "class Solution:\n def numKLenSubstrNoRepeats(self, s: str, k: int) -> int:\n ans = 0\n unique = 0\n count = collections.Counter()\n\n for i, c in enumerate(s):\n count[c] += 1\n if count[c] == 1:\n unique += 1\n if i >= k:\n count[s[i - k]] -= 1\n if count[s[i - k]] == 0:\n unique -= 1\n if unique == k:\n ans += 1\n\n return ans\n", | |
| "title": "1100. Find K-Length Substrings With No Repeated Characters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1029 | |
| }, | |
| { | |
| "code": "class UnionFind:\n def __init__(self, n: int):\n self.count = n\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n self.count -= 1\n\n def getCount(self) -> int:\n return self.count\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def earliestAcq(self, logs: list[list[int]], n: int) -> int:\n uf = UnionFind(n)\n\n # Sort `logs` by timestamp.\n logs.sort(key=lambda x: x[0])\n\n for timestamp, x, y in logs:\n uf.unionByRank(x, y)\n if uf.getCount() == 1:\n return timestamp\n\n return -1\n", | |
| "title": "1101. The Earliest Moment When Everyone Become Friends", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1030 | |
| }, | |
| { | |
| "code": "class Solution:\n def distributeCandies(self, candies: int, n: int) -> list[int]:\n ans = [0] * n\n rows = int((-n + (n**2 + 8 * n**2 * candies)**0.5) / (2 * n**2))\n accumN = rows * (rows - 1) * n // 2\n\n for i in range(n):\n ans[i] = accumN + rows * (i + 1)\n\n givenCandies = (n**2 * rows**2 + n * rows) // 2\n candies -= givenCandies\n lastGiven = rows * n\n i = 0\n\n while candies > 0:\n lastGiven += 1\n actualGiven = min(lastGiven, candies)\n candies -= actualGiven\n ans[i] += actualGiven\n i += 1\n\n return ans\n", | |
| "title": "1103. Distribute Candies to People", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1031 | |
| }, | |
| { | |
| "code": "class Solution:\n def pathInZigZagTree(self, label: int) -> list[int]:\n def boundarySum(level: int):\n return 2**level + 2**(level + 1) - 1\n\n ans = []\n\n for l in range(21):\n if 2**l > label:\n level = l - 1\n break\n\n if level % 2 == 1:\n label = boundarySum(level) - label\n\n for l in reversed(range(level + 1)):\n ans.append(label if l % 2 == 0 else boundarySum(l) - label)\n label //= 2\n\n return ans[::-1]\n", | |
| "title": "1104. Path In Zigzag Labelled Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1032 | |
| }, | |
| { | |
| "code": "class Solution:\n def minHeightShelves(self, books: list[list[int]], shelfWidth: int) -> int:\n # dp[i] := the minimum height to place the first i books\n dp = [0] + [math.inf] * len(books)\n\n for i in range(len(books)):\n sumThickness = 0\n maxHeight = 0\n # Place books[j..i] on a new shelf.\n for j in range(i, -1, -1):\n thickness, height = books[j]\n sumThickness += thickness\n if sumThickness > shelfWidth:\n break\n maxHeight = max(maxHeight, height)\n dp[i + 1] = min(dp[i + 1], dp[j] + maxHeight)\n\n return dp[-1]\n", | |
| "title": "1105. Filling Bookcase Shelves", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1033 | |
| }, | |
| { | |
| "code": "class Solution:\n def parseBoolExpr(self, expression: str) -> bool:\n def dfs(s: int, e: int) -> list[str]:\n if s == e:\n return True if expression[s] == 't' else False\n\n exps = []\n layer = 0\n\n for i in range(s, e + 1):\n c = expression[i]\n if layer == 0 and c in '!&|':\n op = c\n elif c == '(':\n layer += 1\n if layer == 1:\n left = i + 1\n elif c == ')':\n layer -= 1\n if layer == 0:\n exps.append(dfs(left, i - 1))\n elif c == ',' and layer == 1:\n exps.append(dfs(left, i - 1))\n left = i + 1\n\n if op == '|':\n return functools.reduce(operator.or_, exps)\n if op == '&':\n return functools.reduce(operator.and_, exps)\n if op == '!':\n return not exps[0]\n\n return dfs(0, len(expression) - 1)\n", | |
| "title": "1106. Parsing A Boolean Expression", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1034 | |
| }, | |
| { | |
| "code": "WITH\n UserToLoginDate AS (\n SELECT\n user_id,\n MIN(activity_date) AS login_date\n FROM Traffic\n WHERE activity = 'login'\n GROUP BY 1\n )\nSELECT\n login_date,\n COUNT(*) AS user_count\nFROM UserToLoginDate\nWHERE DATEDIFF('2019-06-30', login_date) <= 90\nGROUP BY 1;\n", | |
| "title": "1107. New Users Daily Count", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1035 | |
| }, | |
| { | |
| "code": "class Solution:\n def defangIPaddr(self, address: str) -> str:\n return address.replace('.', '[.]')\n", | |
| "title": "1108. Defanging an IP Address", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1036 | |
| }, | |
| { | |
| "code": "class Solution:\n def corpFlightBookings(self, bookings: list[list[int]], n: int) -> list[int]:\n ans = [0] * n\n\n for booking in bookings:\n ans[booking[0] - 1] += booking[2]\n if booking[1] < n:\n ans[booking[1]] -= booking[2]\n\n for i in range(1, n):\n ans[i] += ans[i - 1]\n\n return ans\n", | |
| "title": "1109. Corporate Flight Bookings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1037 | |
| }, | |
| { | |
| "code": "class Solution:\n def delNodes(self, root: TreeNode, to_delete: list[int]) -> list[TreeNode]:\n ans = []\n toDeleteSet = set(to_delete)\n\n def dfs(root: TreeNode, isRoot: bool) -> TreeNode:\n if not root:\n return None\n\n deleted = root.val in toDeleteSet\n if isRoot and not deleted:\n ans.append(root)\n\n # If root is deleted, both children have the possibility to be a new root\n root.left = dfs(root.left, deleted)\n root.right = dfs(root.right, deleted)\n return None if deleted else root\n\n dfs(root, True)\n return ans\n", | |
| "title": "1110. Delete Nodes And Return Forest", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1038 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxDepthAfterSplit(self, seq: str) -> list[int]:\n ans = []\n depth = 1\n\n # Put all odd-depth parentheses in one group and even-depth parentheses in the other group.\n for c in seq:\n if c == '(':\n depth += 1\n ans.append(depth % 2)\n else:\n ans.append(depth % 2)\n depth -= 1\n\n return ans\n", | |
| "title": "1111. Maximum Nesting Depth of Two Valid Parentheses Strings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1039 | |
| }, | |
| { | |
| "code": "WITH\n RankedEnrollments AS (\n SELECT\n student_id,\n course_id,\n grade,\n RANK() OVER(\n PARTITION BY student_id\n ORDER BY grade DESC, course_id\n ) AS `rank`\n FROM Enrollments\n )\nSELECT\n student_id,\n course_id,\n grade\nFROM RankedEnrollments\nWHERE `rank` = 1;\n", | |
| "title": "1112. Highest Grade For Each Student", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1040 | |
| }, | |
| { | |
| "code": "SELECT\n extra AS report_reason,\n COUNT(DISTINCT post_id) AS report_count\nFROM Actions\nWHERE\n ACTION = 'report'\n AND DATEDIFF('2019-07-05', action_date) = 1\nGROUP BY 1;\n", | |
| "title": "1113. Reported Posts", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1041 | |
| }, | |
| { | |
| "code": "from threading import Lock\n\n\nclass Foo:\n def __init__(self):\n self.firstDone = Lock()\n self.secondDone = Lock()\n self.firstDone.acquire()\n self.secondDone.acquire()\n\n def first(self, printFirst: 'Callable[[], None]') -> None:\n printFirst()\n self.firstDone.release()\n\n def second(self, printSecond: 'Callable[[], None]') -> None:\n self.firstDone.acquire()\n printSecond()\n self.secondDone.release()\n\n def third(self, printThird: 'Callable[[], None]') -> None:\n self.secondDone.acquire()\n printThird()\n", | |
| "title": "1114. Print in Order", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1042 | |
| }, | |
| { | |
| "code": "from threading import Semaphore\n\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.fooSemaphore = Semaphore(1)\n self.barSemaphore = Semaphore(0)\n\n def foo(self, printFoo: 'Callable[[], None]') -> None:\n for _ in range(self.n):\n self.fooSemaphore.acquire()\n printFoo()\n self.barSemaphore.release()\n\n def bar(self, printBar: 'Callable[[], None]') -> None:\n for _ in range(self.n):\n self.barSemaphore.acquire()\n printBar()\n self.fooSemaphore.release()\n", | |
| "title": "1115. Print FooBar Alternately", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1043 | |
| }, | |
| { | |
| "code": "from threading import Semaphore\n\n\nclass ZeroEvenOdd:\n def __init__(self, n):\n self.n = n\n self.zeroSemaphore = Semaphore(1)\n self.evenSemaphore = Semaphore(0)\n self.oddSemaphore = Semaphore(0)\n\n # printNumber(x) outputs \"x\", where x is an integer.\n def zero(self, printNumber: 'Callable[[int], None]') -> None:\n for i in range(self.n):\n self.zeroSemaphore.acquire()\n printNumber(0)\n (self.oddSemaphore if i & 2 == 0 else self.evenSemaphore).release()\n\n def even(self, printNumber: 'Callable[[int], None]') -> None:\n for i in range(2, self.n + 1, 2):\n self.evenSemaphore.acquire()\n printNumber(i)\n self.zeroSemaphore.release()\n\n def odd(self, printNumber: 'Callable[[int], None]') -> None:\n for i in range(1, self.n + 1, 2):\n self.oddSemaphore.acquire()\n printNumber(i)\n self.zeroSemaphore.release()\n", | |
| "title": "1116. Print Zero Even Odd", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1044 | |
| }, | |
| { | |
| "code": "class Solution:\n def numberOfDays(self, year: int, month: int) -> int:\n days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\n def isLeapYear(year: int) -> bool:\n return year % 4 == 0 and year % 100 != 0 or year % 400 == 0\n return 29 if month == 2 and isLeapYear(year) else days[month]\n", | |
| "title": "1118. Number of Days in a Month", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1045 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeVowels(self, s: str) -> str:\n return re.sub('a|e|i|o|u', '', s)\n", | |
| "title": "1119. Remove Vowels from a String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1046 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass(frozen=True)\nclass T:\n summ: int\n count: int\n maxAverage: int\n\n\nclass Solution:\n def maximumAverageSubtree(self, root: TreeNode | None) -> float:\n def maximumAverage(root: TreeNode | None) -> T:\n if not root:\n return T(0, 0, 0)\n\n left = maximumAverage(root.left)\n right = maximumAverage(root.right)\n\n summ = root.val + left.summ + right.summ\n count = 1 + left.count + right.count\n maxAverage = max(summ / count, left.maxAverage, right.maxAverage)\n return T(summ, count, maxAverage)\n\n return maximumAverage(root).maxAverage\n", | |
| "title": "1120. Maximum Average Subtree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1047 | |
| }, | |
| { | |
| "code": "class Solution:\n def canDivideIntoSubsequences(self, nums: list[int], k: int) -> bool:\n # Find the number with the maxFreq, we need at least maxFreq * k elements\n # e.g. nums = [1, 2, 2, 3, 4], we have maxFreq = 2 (two 2s), so we have to\n # Split nums into two subsequences say k = 3, the minimum length of nums is 2 x\n # 3 = 6, which is impossible if len(nums) = 5\n return len(nums) >= k * max(Counter(nums).values())\n", | |
| "title": "1121. Divide Array Into Increasing Sequences", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1048 | |
| }, | |
| { | |
| "code": "class Solution:\n def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:\n ans = []\n count = [0] * 1001\n\n for a in arr1:\n count[a] += 1\n\n for a in arr2:\n while count[a] > 0:\n ans.append(a)\n count[a] -= 1\n\n for num in range(1001):\n for _ in range(count[num]):\n ans.append(num)\n\n return ans\n", | |
| "title": "1122. Relative Sort Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1049 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestWPI(self, hours: list[int]) -> int:\n ans = 0\n prefix = 0\n dict = {}\n\n for i in range(len(hours)):\n prefix += 1 if hours[i] > 8 else -1\n if prefix > 0:\n ans = i + 1\n else:\n if prefix not in dict:\n dict[prefix] = i\n if prefix - 1 in dict:\n ans = max(ans, i - dict[prefix - 1])\n\n return ans\n", | |
| "title": "1124. Longest Well-Performing Interval", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1050 | |
| }, | |
| { | |
| "code": "WITH\n AvgEvents AS (\n SELECT\n business_id,\n AVG(occurrences) OVER(PARTITION BY event_type) AS event_avg_occurrences,\n occurrences\n FROM Events\n )\nSELECT business_id\nFROM AvgEvents\nGROUP BY 1\nHAVING SUM(IF(occurrences > event_avg_occurrences, 1, 0)) > 1;\n", | |
| "title": "1126. Active Businesses", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1051 | |
| }, | |
| { | |
| "code": "WITH\n UserToAmount AS (\n SELECT\n user_id,\n spend_date,\n CASE\n WHEN COUNT(DISTINCT platform) = 2 THEN 'both'\n ELSE platform\n END AS platform,\n SUM(amount) AS amount\n FROM Spending\n GROUP BY 1, 2\n ),\n DateAndPlatforms AS (\n SELECT DISTINCT(spend_date), 'desktop' AS platform\n FROM Spending\n UNION ALL\n SELECT DISTINCT(spend_date), 'mobile' AS platform\n FROM Spending\n UNION ALL\n SELECT DISTINCT(spend_date), 'both' AS platform\n FROM Spending\n )\nSELECT\n DateAndPlatforms.spend_date,\n DateAndPlatforms.platform,\n IFNULL(SUM(UserToAmount.amount), 0) AS total_amount,\n COUNT(DISTINCT UserToAmount.user_id) AS total_users\nFROM DateAndPlatforms\nLEFT JOIN UserToAmount\n USING (spend_date, platform)\nGROUP BY 1, 2;\n", | |
| "title": "1127. User Purchase Platform", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1052 | |
| }, | |
| { | |
| "code": "class Solution:\n def numEquivDominoPairs(self, dominoes: list[list[int]]) -> int:\n ans = 0\n count = collections.Counter()\n\n for domino in dominoes:\n key = min(domino[0], domino[1]) * 10 + max(domino[0], domino[1])\n ans += count[key]\n count[key] += 1\n\n return ans\n", | |
| "title": "1128. Number of Equivalent Domino Pairs", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1053 | |
| }, | |
| { | |
| "code": "from enum import Enum\n\n\nclass Color(Enum):\n INIT = 0\n RED = 1\n BLUE = 2\n\n\nclass Solution:\n def shortestAlternatingPaths(\n self,\n n: int,\n redEdges: list[list[int]],\n blueEdges: list[list[int]],\n ) -> list[int]:\n ans = [-1] * n\n graph = [[] for _ in range(n)] # graph[u] := [(v, edgeColor)]\n q = collections.deque([(0, Color.INIT)]) # [(u, prevColor)]\n\n for u, v in redEdges:\n graph[u].append((v, Color.RED))\n\n for u, v in blueEdges:\n graph[u].append((v, Color.BLUE))\n\n step = 0\n while q:\n for _ in range(len(q)):\n u, prevColor = q.popleft()\n if ans[u] == -1:\n ans[u] = step\n for i, (v, edgeColor) in enumerate(graph[u]):\n if v == -1 or edgeColor == prevColor:\n continue\n q.append((v, edgeColor))\n graph[u][i] = (-1, edgeColor) # Mark (u, v) as used.\n step += 1\n\n return ans\n", | |
| "title": "1129. Shortest Path with Alternating Colors", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1054 | |
| }, | |
| { | |
| "code": "class Solution:\n def mctFromLeafValues(self, arr: list[int]) -> int:\n n = len(arr)\n # dp[i][j] := the minimum cost of arr[i..j]\n dp = [[0] * n for _ in range(n)]\n # maxVal[i][j] := the maximum value of arr[i..j]\n maxVal = [[0] * n for _ in range(n)]\n\n for i in range(n):\n maxVal[i][i] = arr[i]\n\n for d in range(1, n):\n for i in range(n - d):\n j = i + d\n maxVal[i][j] = max(maxVal[i][j - 1], maxVal[i + 1][j])\n\n for d in range(1, n):\n for i in range(n - d):\n j = i + d\n dp[i][j] = math.inf\n for k in range(i, j):\n dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] +\n maxVal[i][k] * maxVal[k + 1][j])\n\n return dp[0][-1]\n", | |
| "title": "1130. Minimum Cost Tree From Leaf Values_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1055 | |
| }, | |
| { | |
| "code": "class Solution:\n def mctFromLeafValues(self, arr: list[int]) -> int:\n ans = 0\n stack = [math.inf]\n\n for a in arr:\n while stack and stack[-1] <= a:\n mid = stack.pop()\n # Multiply mid with next greater element in the array,\n # On the left (stack[-1]) or on the right (current number a)\n ans += min(stack[-1], a) * mid\n stack.append(a)\n\n return ans + sum(a * b for a, b in zip(stack[1:], stack[2:]))\n", | |
| "title": "1130. Minimum Cost Tree From Leaf Values", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1056 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxAbsValExpr(self, arr1: list[int], arr2: list[int]) -> int:\n n = len(arr1)\n a = [arr1[i] + arr2[i] + i for i in range(n)]\n b = [arr1[i] + arr2[i] - i for i in range(n)]\n c = [arr1[i] - arr2[i] + i for i in range(n)]\n d = [arr1[i] - arr2[i] - i for i in range(n)]\n return max(map(lambda x: max(x) - min(x), (a, b, c, d)))\n", | |
| "title": "1131. Maximum of Absolute Value Expression", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1057 | |
| }, | |
| { | |
| "code": "WITH\n DailyPercents AS (\n SELECT (\n COUNT(DISTINCT Removals.post_id) / COUNT(DISTINCT Actions.post_id)\n ) * 100 AS percent\n FROM Actions\n LEFT JOIN Removals\n USING (post_id)\n WHERE Actions.extra = 'spam'\n GROUP BY Actions.action_date\n )\nSELECT ROUND(AVG(percent), 2) AS average_daily_percent\nFROM DailyPercents;\n", | |
| "title": "1132. Reported Posts II", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1058 | |
| }, | |
| { | |
| "code": "class Solution:\n def largestUniqueNumber(self, nums: list[int]) -> int:\n return max([num for num, freq in collections.Counter(nums).items()\n if freq == 1], default=-1)\n", | |
| "title": "1133. Largest Unique Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1059 | |
| }, | |
| { | |
| "code": "class Solution:\n def isArmstrong(self, n: int) -> bool:\n s = str(n)\n k = len(s)\n return sum(pow(int(c), k) for c in s) == n\n", | |
| "title": "1134. Armstrong Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1060 | |
| }, | |
| { | |
| "code": "class UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self.find(u)\n j = self.find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def minimumCost(self, n: int, connections: list[list[int]]) -> int:\n ans = 0\n uf = UnionFind(n + 1)\n\n # Sort by cost.\n connections.sort(key=lambda x: x[2])\n\n for u, v, cost in connections:\n if uf.find(u) == uf.find(v):\n continue\n uf.unionByRank(u, v)\n ans += cost\n\n root = uf.find(1)\n if any(uf.find(i) != root for i in range(1, n + 1)):\n return -1\n\n return ans\n", | |
| "title": "1135. Connecting Cities With Minimum Cost", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1061 | |
| }, | |
| { | |
| "code": "class Solution:\n def minimumSemesters(self, n: int, relations: list[list[int]]) -> int:\n graph = [[] for _ in range(n)]\n inDegrees = [0] * n\n\n # Build the graph.\n for u, v in relations:\n graph[u - 1].append(v - 1)\n inDegrees[v - 1] += 1\n\n # Perform topological sorting.\n q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0])\n\n step = 0\n while q:\n for _ in range(len(q)):\n u = q.popleft()\n n -= 1\n for v in graph[u]:\n inDegrees[v] -= 1\n if inDegrees[v] == 0:\n q.append(v)\n step += 1\n\n return step if n == 0 else -1\n", | |
| "title": "1136. Parallel Courses", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1062 | |
| }, | |
| { | |
| "code": "class Solution:\n def tribonacci(self, n: int) -> int:\n dp = [0, 1, 1]\n\n for i in range(3, n + 1):\n dp[i % 3] = sum(dp)\n\n return dp[n % 3]\n", | |
| "title": "1137. N-th Tribonacci Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1063 | |
| }, | |
| { | |
| "code": "class Solution:\n def largest1BorderedSquare(self, grid: list[list[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n\n # leftOnes[i][j] := consecutive 1s in the left of grid[i][j]\n leftOnes = [[0] * n for _ in range(m)]\n # topOnes[i][j] := consecutive 1s in the top of grid[i][j]\n topOnes = [[0] * n for _ in range(m)]\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n leftOnes[i][j] = 1 if j == 0 else 1 + leftOnes[i][j - 1]\n topOnes[i][j] = 1 if i == 0 else 1 + topOnes[i - 1][j]\n\n for sz in range(min(m, n), 0, -1):\n for i in range(m - sz + 1):\n for j in range(n - sz + 1):\n x = i + sz - 1\n y = j + sz - 1\n # If grid[i..x][j..y] has all 1s on its border.\n if min(\n leftOnes[i][y],\n leftOnes[x][y],\n topOnes[x][j],\n topOnes[x][y]) >= sz:\n return sz * sz\n\n return 0\n", | |
| "title": "1139. Largest 1-Bordered Square", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1064 | |
| }, | |
| { | |
| "code": "SELECT\n activity_date AS day,\n COUNT(DISTINCT user_id) AS active_users\nFROM Activity\nWHERE activity_date BETWEEN '2019-06-28' AND '2019-07-27'\nGROUP BY 1;\n", | |
| "title": "1141. User Activity for the Past 30 Days I", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1065 | |
| }, | |
| { | |
| "code": "SELECT\n IFNULL(\n ROUND(\n COUNT(DISTINCT session_id) / COUNT(DISTINCT user_id),\n 2\n ),\n 0.00\n ) AS average_sessions_per_user\nFROM Activity\nWHERE activity_date BETWEEN '2019-06-28' AND '2019-07-27';\n", | |
| "title": "1142. User Activity for the Past 30 Days II", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1066 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n m = len(text1)\n n = len(text2)\n # dp[i][j] := the length of LCS(text1[0..i), text2[0..j))\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n for i in range(m):\n for j in range(n):\n dp[i + 1][j + 1] = (1 + dp[i][j] if text1[i] == text2[j]\n else max(dp[i][j + 1], dp[i + 1][j]))\n\n return dp[m][n]\n", | |
| "title": "1143. Longest Common Subsequence", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1067 | |
| }, | |
| { | |
| "code": "class Solution:\n def movesToMakeZigzag(self, nums: list[int]) -> int:\n decreasing = [0] * 2\n\n for i, num in enumerate(nums):\n l = nums[i - 1] if i > 0 else 1001\n r = nums[i + 1] if i + 1 < len(nums) else 1001\n decreasing[i % 2] += max(0, num - min(l, r) + 1)\n\n return min(decreasing[0], decreasing[1])\n", | |
| "title": "1144. Decrease Elements To Make Array Zigzag", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1068 | |
| }, | |
| { | |
| "code": "class SnapshotArray:\n def __init__(self, length: int):\n self.snaps = [[[0, 0]] for _ in range(length)]\n self.snap_id = 0\n\n def set(self, index: int, val: int) -> None:\n snap = self.snaps[index][-1]\n if snap[0] == self.snap_id:\n snap[1] = val\n else:\n self.snaps[index].append([self.snap_id, val])\n\n def snap(self) -> int:\n self.snap_id += 1\n return self.snap_id - 1\n\n def get(self, index: int, snap_id: int) -> int:\n i = bisect.bisect_left(self.snaps[index], [snap_id + 1]) - 1\n return self.snaps[index][i][1]\n", | |
| "title": "1146. Snapshot Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1069 | |
| }, | |
| { | |
| "code": "SELECT DISTINCT author_id AS id\nFROM Views\nWHERE author_id = viewer_id\nORDER BY 1;\n", | |
| "title": "1148. Article Views I", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1070 | |
| }, | |
| { | |
| "code": "SELECT DISTINCT viewer_id AS id\nFROM Views\nGROUP BY viewer_id, view_date\nHAVING COUNT(DISTINCT article_id) > 1\nORDER BY 1;\n", | |
| "title": "1149. Article Views II", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1071 | |
| }, | |
| { | |
| "code": "class Solution:\n def isMajorityElement(self, nums: list[int], target: int) -> bool:\n n = len(nums)\n i = bisect.bisect_left(nums, target)\n return i + n // 2 < n and nums[i + n // 2] == target\n", | |
| "title": "1150. Check If a Number Is Majority Element in a Sorted Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1072 | |
| }, | |
| { | |
| "code": "class Solution:\n def minSwaps(self, data: list[int]) -> int:\n k = data.count(1)\n ones = 0 # the number of ones in the window\n maxOnes = 0 # the maximum number of ones in the window\n\n for i, num in enumerate(data):\n if i >= k and data[i - k]:\n ones -= 1\n if num:\n ones += 1\n maxOnes = max(maxOnes, ones)\n\n return k - maxOnes\n", | |
| "title": "1151. Minimum Swaps to Group All 1's Together", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1073 | |
| }, | |
| { | |
| "code": "class Solution:\n def mostVisitedPattern(\n self,\n username: list[str],\n timestamp: list[int],\n website: list[str],\n ) -> list[str]:\n userToSites = collections.defaultdict(list)\n\n # Sort websites of each user by timestamp.\n for user, _, site in sorted(\n zip(username, timestamp, website),\n key=lambda x: x[1]):\n userToSites[user].append(site)\n\n # For each of three websites, count its frequency.\n patternCount = collections.Counter()\n\n for user, sites in userToSites.items():\n patternCount.update(Counter(set(itertools.combinations(sites, 3))))\n\n return max(sorted(patternCount), key=patternCount.get)\n", | |
| "title": "1152. Analyze User Website Visit Pattern", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1074 | |
| }, | |
| { | |
| "code": "class Solution:\n def canConvert(self, str1: str, str2: str) -> bool:\n if str1 == str2:\n return True\n\n mappings = {}\n\n for a, b in zip(str1, str2):\n if mappings.get(a, b) != b:\n return False\n mappings[a] = b\n\n # No letter in the str1 maps to > 1 letter in the str2 and there is at\n # lest one temporary letter can break any loops.\n return len(set(str2)) < 26\n", | |
| "title": "1153. String Transforms Into Another String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1075 | |
| }, | |
| { | |
| "code": "class Solution:\n def dayOfYear(self, date: str) -> int:\n def isLeapYear(year: int) -> bool:\n return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0\n\n year = int(date[:4])\n month = int(date[5:7])\n day = int(date[8:])\n days = [31, 29 if isLeapYear(\n year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\n return sum(days[:month - 1]) + day\n", | |
| "title": "1154. Day of the Year", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1076 | |
| }, | |
| { | |
| "code": "class Solution:\n def numRollsToTarget(self, n: int, k: int, target: int) -> int:\n MOD = 1_000_000_007\n dp = [1] + [0] * target\n\n for _ in range(n): # n dices\n newDp = [0] * (target + 1)\n for i in range(1, k + 1): # numbers 1, 2, ..., f\n for t in range(i, target + 1): # all the possible targets\n newDp[t] += dp[t - i]\n newDp[t] %= MOD\n dp = newDp\n\n return dp[target]\n", | |
| "title": "1155. Number of Dice Rolls With Target Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1077 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxRepOpt1(self, text: str) -> int:\n count = collections.Counter(text)\n groups = [[c, len(list(group))]\n for c, group in itertools.groupby(text)]\n ans = max(min(length + 1, count[c]) for c, length in groups)\n\n for i in range(1, len(groups) - 1):\n if groups[i - 1][0] == groups[i + 1][0] and groups[i][1] == 1:\n ans = max(\n ans,\n min(groups[i - 1][1] + groups[i + 1][1] + 1, count\n [groups[i - 1][0]]))\n\n return ans\n", | |
| "title": "1156. Swap For Longest Repeated Character Substring", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1078 | |
| }, | |
| { | |
| "code": "class MajorityChecker:\n def __init__(self, arr: list[int]):\n self.arr = arr\n self.TIMES = 20 # 2^TIMES >> |arr|\n self.numToIndices = collections.defaultdict(list)\n\n for i, a in enumerate(self.arr):\n self.numToIndices[a].append(i)\n\n def query(self, left: int, right: int, threshold: int) -> int:\n for _ in range(self.TIMES):\n randIndex = random.randint(left, right)\n num = self.arr[randIndex]\n indices = self.numToIndices[num]\n l = bisect.bisect_left(indices, left)\n r = bisect.bisect_right(indices, right)\n if r - l >= threshold:\n return num\n\n return -1\n", | |
| "title": "1157. Online Majority Element In Subarray", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1079 | |
| }, | |
| { | |
| "code": "SELECT\n Users.user_id AS buyer_id,\n Users.join_date,\n COUNT(Orders.order_id) AS orders_in_2019\nFROM Users\nLEFT JOIN Orders\n ON (Users.user_id = Orders.buyer_id AND YEAR(order_date) = '2019')\nGROUP BY 1;\n", | |
| "title": "1158. Market Analysis I", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1080 | |
| }, | |
| { | |
| "code": "WITH\n RankedOrders AS (\n SELECT\n Orders.seller_id,\n RANK() OVER(\n PARTITION BY Orders.seller_id\n ORDER BY Orders.order_date\n ) AS `rank`,\n Items.item_brand\n FROM Orders\n INNER JOIN Items\n USING (item_id)\n )\nSELECT\n user_id AS seller_id,\n CASE\n WHEN Users.favorite_brand = RankedOrders.item_brand THEN 'yes'\n ELSE 'no'\n END AS 2nd_item_fav_brand\nFROM Users\nLEFT JOIN RankedOrders\n ON (Users.user_id = RankedOrders.seller_id AND RankedOrders.`rank` = 2);\n", | |
| "title": "1159. Market Analysis II", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1081 | |
| }, | |
| { | |
| "code": "class Solution:\n def countCharacters(self, words: list[str], chars: str) -> int:\n ans = 0\n count = collections.Counter(chars)\n\n for word in words:\n tempCount = count.copy()\n for c in word:\n tempCount[c] -= 1\n if tempCount[c] < 0:\n ans -= len(word)\n break\n ans += len(word)\n\n return ans\n", | |
| "title": "1160. Find Words That Can Be Formed by Characters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1082 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxLevelSum(self, root: TreeNode | None) -> int:\n # levelSums[i] := the sum of level (i + 1) (1-indexed)\n levelSums = []\n\n def dfs(root: TreeNode | None, level: int) -> None:\n if not root:\n return\n if len(levelSums) == level:\n levelSums.append(0)\n levelSums[level] += root.val\n dfs(root.left, level + 1)\n dfs(root.right, level + 1)\n\n dfs(root, 0)\n return 1 + levelSums.index(max(levelSums))\n", | |
| "title": "1161. Maximum Level Sum of a Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1083 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxDistance(self, grid: list[list[int]]) -> int:\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(grid)\n n = len(grid[0])\n q = collections.deque()\n water = 0\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n water += 1\n else:\n q.append((i, j))\n\n if water == 0 or water == m * n:\n return -1\n\n ans = 0\n d = 0\n\n while q:\n for _ in range(len(q)):\n i, j = q.popleft()\n ans = d\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if grid[x][y] > 0:\n continue\n q.append((x, y))\n grid[x][y] = 2 # Mark as visited.\n d += 1\n\n return ans\n", | |
| "title": "1162. As Far from Land as Possible", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1084 | |
| }, | |
| { | |
| "code": "class Solution:\n def lastSubstring(self, s: str) -> str:\n i = 0\n j = 1\n k = 0 # the number of the same letters of s[i..n) and s[j..n)\n\n while j + k < len(s):\n if s[i + k] == s[j + k]:\n k += 1\n elif s[i + k] > s[j + k]:\n # Skip s[j..j + k) and advance to s[j + k + 1] to find a possible\n # lexicographically larger substring since s[i..i + k) == s[j..j + k)\n # and s[i + k] > s[j + k).\n j = j + k + 1\n k = 0\n else:\n # Skip s[i..i + k) and advance to s[i + k + 1] or s[j] to find a\n # possible lexicographically larger substring since\n # s[i..i + k) == s[j..j + k) and s[i + k] < s[j + k).\n # Note that it's unnecessary to explore s[i + k + 1..j) if\n # i + k + 1 < j since they are already explored by j.\n i = max(i + k + 1, j)\n j = i + 1\n k = 0\n\n return s[i:]\n", | |
| "title": "1163. Last Substring in Lexicographical Order", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312230, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1085 | |
| }, | |
| { | |
| "code": "WITH\n RankedProducts AS (\n SELECT\n product_id,\n new_price,\n RANK() OVER(\n PARTITION BY product_id\n ORDER BY change_date DESC\n ) AS `rank`\n FROM Products\n WHERE change_date <= '2019-08-16'\n ),\n ProductToLatestPrice AS (\n SELECT product_id, new_price\n FROM RankedProducts\n WHERE `rank` = 1\n )\nSELECT\n Products.product_id,\n IFNULL(ProductToLatestPrice.new_price, 10) AS price\nFROM Products\nLEFT JOIN ProductToLatestPrice\n USING (product_id)\nGROUP BY 1;\n", | |
| "title": "1164. Product Price at a Given Date", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1086 | |
| }, | |
| { | |
| "code": "class Solution:\n def calculateTime(self, keyboard: str, word: str) -> int:\n letterToIndex = {c: i for i, c in enumerate(keyboard)}\n return (letterToIndex[word[0]] +\n sum(abs(letterToIndex[a] - letterToIndex[b])\n for a, b in itertools.pairwise(word)))\n", | |
| "title": "1165. Single-Row Keyboard", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1087 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self, value: int = 0):\n self.children: dict[str, TrieNode] = {}\n self.value = value\n\n\nclass FileSystem:\n def __init__(self):\n self.root = TrieNode()\n\n def createPath(self, path: str, value: int) -> bool:\n node: TrieNode = self.root\n subpaths = path.split('/')\n\n for i in range(1, len(subpaths) - 1):\n if subpaths[i] not in node.children:\n return False\n node = node.children[subpaths[i]]\n\n if subpaths[-1] in node.children:\n return False\n node.children[subpaths[-1]] = TrieNode(value)\n return True\n\n def get(self, path: str) -> int:\n node: TrieNode = self.root\n for subpath in path.split('/')[1:]:\n if subpath not in node.children:\n return -1\n node = node.children[subpath]\n return node.value\n", | |
| "title": "1166. Design File System", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1088 | |
| }, | |
| { | |
| "code": "class Solution:\n def connectSticks(self, sticks: list[int]) -> int:\n ans = 0\n heapq.heapify(sticks)\n\n while len(sticks) > 1:\n x = heapq.heappop(sticks)\n y = heapq.heappop(sticks)\n ans += x + y\n heapq.heappush(sticks, x + y)\n\n return ans\n", | |
| "title": "1167. Minimum Cost to Connect Sticks", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1089 | |
| }, | |
| { | |
| "code": "class Solution:\n def minCostToSupplyWater(\n self,\n n: int,\n wells: list[int],\n pipes: list[list[int]],\n ) -> int:\n ans = 0\n graph = [[] for _ in range(n + 1)]\n minHeap = [] # (d, u)\n\n for u, v, w in pipes:\n graph[u].append((v, w))\n graph[v].append((u, w))\n\n # Connect virtual 0 with nodes 1 to n.\n for i, well in enumerate(wells):\n graph[0].append((i + 1, well))\n heapq.heappush(minHeap, (well, i + 1))\n\n mst = {0}\n\n while len(mst) < n + 1:\n d, u = heapq.heappop(minHeap)\n if u in mst:\n continue\n # Add the new vertex.\n mst.add(u)\n ans += d\n # Expand if possible.\n for v, w in graph[u]:\n if v not in mst:\n heapq.heappush(minHeap, (w, v))\n\n return ans\n", | |
| "title": "1168. Optimize Water Distribution in a Village", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1090 | |
| }, | |
| { | |
| "code": "class Solution:\n def invalidTransactions(self, transactions: list[str]) -> list[str]:\n ans = []\n nameToTrans = collections.defaultdict(list)\n\n for t in transactions:\n name, time, amount, city = t.split(',')\n time, amount = int(time), int(amount)\n nameToTrans[name].append({'time': time, 'city': city})\n\n for t in transactions:\n name, time, amount, city = t.split(',')\n time, amount = int(time), int(amount)\n if amount > 1000:\n ans.append(t)\n elif name in nameToTrans:\n for sameName in nameToTrans[name]:\n if abs(sameName['time'] - time) <= 60 and sameName['city'] != city:\n ans.append(t)\n break\n\n return ans\n", | |
| "title": "1169. Invalid Transactions", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1091 | |
| }, | |
| { | |
| "code": "class Solution:\n def numSmallerByFrequency(\n self,\n queries: list[str],\n words: list[str],\n ) -> list[int]:\n ans = []\n wordsFreq = sorted([word.count(min(word)) for word in words])\n\n for q in queries:\n count = q.count(min(q))\n index = bisect.bisect(wordsFreq, count)\n ans.append(len(words) - index)\n\n return ans\n", | |
| "title": "1170. Compare Strings by Frequency of the Smallest Character", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1092 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeZeroSumSublists(self, head: ListNode) -> ListNode:\n dummy = ListNode(0, head)\n prefix = 0\n prefixToNode = {0: dummy}\n\n while head:\n prefix += head.val\n prefixToNode[prefix] = head\n head = head.next\n\n prefix = 0\n head = dummy\n\n while head:\n prefix += head.val\n head.next = prefixToNode[prefix].next\n head = head.next\n\n return dummy.next\n", | |
| "title": "1171. Remove Zero Sum Consecutive Nodes from Linked List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1093 | |
| }, | |
| { | |
| "code": "class DinnerPlates:\n def __init__(self, capacity: int):\n self.capacity = capacity\n self.stacks = []\n self.minHeap = [0] # the minimum indices of the stacks to push\n\n def push(self, val: int) -> None:\n index = self.minHeap[0]\n # Add a new stack on demand.\n if index == len(self.stacks):\n self.stacks.append([])\n # Push the new value.\n self.stacks[index].append(val)\n # If the stack pushed is full, remove its candidacy from `minHeap`.\n if len(self.stacks[index]) == self.capacity:\n heapq.heappop(self.minHeap)\n # If `minHeap` is empty, the next available stack index is |stacks|.\n if not self.minHeap:\n heapq.heappush(self.minHeap, len(self.stacks))\n\n def pop(self) -> int:\n # Remove empty stacks from the back.\n while self.stacks and not self.stacks[-1]:\n self.stacks.pop()\n if not self.stacks:\n return -1\n return self.popAtStack(len(self.stacks) - 1)\n\n def popAtStack(self, index: int) -> int:\n if index >= len(self.stacks) or not self.stacks[index]:\n return -1\n # If the stack is going to have space, add its candiday to `minHeap`.\n if len(self.stacks[index]) == self.capacity:\n heapq.heappush(self.minHeap, index)\n return self.stacks[index].pop()\n", | |
| "title": "1172. Dinner Plate Stacks", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1094 | |
| }, | |
| { | |
| "code": "SELECT\n ROUND(\n 100 * AVG(order_date = customer_pref_delivery_date),\n 2\n ) AS immediate_percentage\nFROM Delivery;\n", | |
| "title": "1173. Immediate Food Delivery I", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1095 | |
| }, | |
| { | |
| "code": "WITH\n CustomerToIsImmediate AS(\n SELECT\n DISTINCT customer_id,\n FIRST_VALUE(order_date = customer_pref_delivery_date) OVER(\n PARTITION BY customer_id\n ORDER BY order_date\n ) is_immediate\n FROM Delivery\n )\nSELECT ROUND(AVG(is_immediate) * 100, 2) immediate_percentage\nFROM CustomerToIsImmediate;\n", | |
| "title": "1174. Immediate Food Delivery II", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1096 | |
| }, | |
| { | |
| "code": "class Solution:\n def numPrimeArrangements(self, n: int) -> int:\n MOD = 1_000_000_007\n\n def factorial(n: int) -> int:\n fact = 1\n for i in range(2, n + 1):\n fact = fact * i % MOD\n return fact\n\n count = self._countPrimes(n)\n return factorial(count) * factorial(n - count) % MOD\n\n def _countPrimes(self, n: int) -> int:\n isPrime = [False] * 2 + [True] * (n - 1)\n for i in range(2, int(n**0.5) + 1):\n if isPrime[i]:\n for j in range(i * i, n + 1, i):\n isPrime[j] = False\n return sum(isPrime)\n", | |
| "title": "1175. Prime Arrangements", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1097 | |
| }, | |
| { | |
| "code": "class Solution:\n def dietPlanPerformance(\n self,\n calories: list[int],\n k: int,\n lower: int,\n upper: int,\n ) -> int:\n ans = 0\n summ = 0\n\n for i, calorie in enumerate(calories):\n summ += calorie\n if i < k - 1:\n continue\n if i >= k:\n summ -= calories[i - k]\n if summ < lower:\n ans -= 1\n elif summ > upper:\n ans += 1\n\n return ans\n", | |
| "title": "1176. Diet Plan Performance", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1098 | |
| }, | |
| { | |
| "code": "class Solution:\n def canMakePaliQueries(self, s: str, queries: list[list[int]]) -> list[bool]:\n dp = [0] * (len(s) + 1)\n\n for i in range(1, len(s) + 1):\n dp[i] = dp[i - 1] ^ 1 << ord(s[i - 1]) - ord('a')\n\n return [\n (dp[right + 1] ^ dp[left]).bit_count() // 2 <= k\n for left, right, k in queries\n ]\n", | |
| "title": "1177. Can Make Palindrome from Substring", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1099 | |
| }, | |
| { | |
| "code": "class Solution:\n def findNumOfValidWords(\n self,\n words: list[str],\n puzzles: list[str],\n ) -> list[int]:\n ans = []\n binaryCount = collections.Counter()\n\n for word in words:\n mask = 0\n for c in word:\n mask |= 1 << ord(c) - ord('a')\n binaryCount[mask] += 1\n\n for puzzle in puzzles:\n valid = 0\n n = len(puzzle) - 1\n for i in range(1 << n):\n mask = 1 << ord(puzzle[0]) - ord('a')\n for j in range(n):\n if i >> j & 1:\n mask |= 1 << ord(puzzle[j + 1]) - ord('a')\n if mask in binaryCount:\n valid += binaryCount[mask]\n ans.append(valid)\n\n return ans\n", | |
| "title": "1178. Number of Valid Words for Each Puzzle", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1100 | |
| }, | |
| { | |
| "code": "SELECT\n id,\n SUM(IF(month = 'Jan', revenue, NULL)) AS Jan_Revenue,\n SUM(IF(month = 'Feb', revenue, NULL)) AS Feb_Revenue,\n SUM(IF(month = 'Mar', revenue, NULL)) AS Mar_Revenue,\n SUM(IF(month = 'Apr', revenue, NULL)) AS Apr_Revenue,\n SUM(IF(month = 'May', revenue, NULL)) AS May_Revenue,\n SUM(IF(month = 'Jun', revenue, NULL)) AS Jun_Revenue,\n SUM(IF(month = 'Jul', revenue, NULL)) AS Jul_Revenue,\n SUM(IF(month = 'Aug', revenue, NULL)) AS Aug_Revenue,\n SUM(IF(month = 'Sep', revenue, NULL)) AS Sep_Revenue,\n SUM(IF(month = 'Oct', revenue, NULL)) AS Oct_Revenue,\n SUM(IF(month = 'Nov', revenue, NULL)) AS Nov_Revenue,\n SUM(IF(month = 'Dec', revenue, NULL)) AS Dec_Revenue\nFROM Department\nGROUP BY 1;\n", | |
| "title": "1179. Reformat Department Table", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1101 | |
| }, | |
| { | |
| "code": "class Solution:\n def countLetters(self, s: str) -> int:\n ans = 0\n dp = 0 # the length of the running letter\n letter = '@' # the running letter\n\n for c in s:\n if c == letter:\n dp += 1\n else:\n dp = 1\n letter = c\n ans += dp # Add the number of substrings ending in the current letter.\n\n return ans\n", | |
| "title": "1180. Count Substrings with Only One Distinct Letter", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1102 | |
| }, | |
| { | |
| "code": "class Solution:\n def shortestDistanceColor(\n self,\n colors: list[int],\n queries: list[list[int]],\n ) -> list[int]:\n NUM_COLOR = 3\n n = len(colors)\n ans = []\n # left[i][c] := the closest index of color c in index i to the left\n left = [[0] * (NUM_COLOR + 1) for _ in range(n)]\n # right[i][c] := the closest index of color c in index i to the right\n right = [[0] * (NUM_COLOR + 1) for _ in range(n)]\n\n colorToLatestIndex = [0, -1, -1, -1] # 0-indexed, -1 means N//A\n for i, color in enumerate(colors):\n colorToLatestIndex[color] = i\n for c in range(1, NUM_COLOR + 1):\n left[i][c] = colorToLatestIndex[c]\n\n colorToLatestIndex = [0, -1, -1, -1] # Reset.\n for i in range(n - 1, -1, -1):\n colorToLatestIndex[colors[i]] = i\n for c in range(1, NUM_COLOR + 1):\n right[i][c] = colorToLatestIndex[c]\n\n for i, c in queries:\n leftDist = math.inf if left[i][c] == -1 else i - left[i][c]\n rightDist = math.inf if right[i][c] == -1 else right[i][c] - i\n minDist = min(leftDist, rightDist)\n ans.append(-1 if minDist == math.inf else minDist)\n\n return ans\n", | |
| "title": "1182. Shortest Distance to Target Color", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1103 | |
| }, | |
| { | |
| "code": "class Solution:\n def maximumNumberOfOnes(\n self,\n width: int,\n height: int,\n sideLength: int,\n maxOnes: int,\n ) -> int:\n subCount = []\n\n def getCount(length: int, index: int) -> int:\n return (length - index - 1) // sideLength + 1\n\n for i in range(sideLength):\n for j in range(sideLength):\n subCount.append(getCount(width, i) * getCount(height, j))\n\n return sum(sorted(subCount, reverse=True)[:maxOnes])\n", | |
| "title": "1183. Maximum Number of Ones", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1104 | |
| }, | |
| { | |
| "code": "class Solution:\n def distanceBetweenBusStops(\n self,\n distance: list[int],\n start: int, destination: int,\n ) -> int:\n clockwise = 0\n counterclockwise = 0\n\n if start > destination:\n start, destination = destination, start\n\n for i, d in enumerate(distance):\n if i >= start and i < destination:\n clockwise += d\n else:\n counterclockwise += d\n\n return min(clockwise, counterclockwise)\n", | |
| "title": "1184. Distance Between Bus Stops", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1105 | |
| }, | |
| { | |
| "code": "class Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n def isLeapYear(year: int) -> bool:\n return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0\n\n week = [\"Sunday\", \"Monday\", \"Tuesday\",\n \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n days = [31, 29 if isLeapYear(\n year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n count = 0\n\n for i in range(1971, year):\n count += 366 if i % 4 == 0 else 365\n for i in range(month - 1):\n count += days[i]\n count += day\n\n return week[(count + 4) % 7]\n", | |
| "title": "1185. Day of the Week", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1106 | |
| }, | |
| { | |
| "code": "class Solution:\n # Similar to 53. Maximum Subarray\n def maximumSum(self, arr: list[int]) -> int:\n ans = -math.inf\n zero = -math.inf # no deletion\n one = -math.inf # <= 1 deletion\n\n for a in arr:\n one = max(a, one + a, zero)\n zero = max(a, zero + a)\n ans = max(ans, one)\n\n return ans\n", | |
| "title": "1186. Maximum Subarray Sum with One Deletion", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1107 | |
| }, | |
| { | |
| "code": "class Solution:\n def makeArrayIncreasing(self, arr1: list[int], arr2: list[int]) -> int:\n # dp[i] := the minimum steps to reach i at previous round\n dp = {-1: 0}\n\n arr2.sort()\n\n for a in arr1:\n newDp = collections.defaultdict(lambda: math.inf)\n for val, steps in dp.items():\n # It's possible to use the value in the arr1.\n if a > val:\n newDp[a] = min(newDp[a], steps)\n # Also try the value in the arr2.\n i = bisect_right(arr2, val)\n if i < len(arr2):\n newDp[arr2[i]] = min(newDp[arr2[i]], steps + 1)\n if not newDp:\n return -1\n dp = newDp\n\n return min(dp.values())\n", | |
| "title": "1187. Make Array Strictly Increasing", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1108 | |
| }, | |
| { | |
| "code": "from threading import Semaphore\n\n\nclass BoundedBlockingQueue:\n def __init__(self, capacity: int):\n self.q = collections.deque()\n self.enqueueSemaphore = Semaphore(capacity)\n self.dequeueSemaphore = Semaphore(0)\n\n def enqueue(self, element: int) -> None:\n self.enqueueSemaphore.acquire()\n self.q.append(element)\n self.dequeueSemaphore.release()\n\n def dequeue(self) -> int:\n self.dequeueSemaphore.acquire()\n element = self.q.popleft()\n self.enqueueSemaphore.release()\n return element\n\n def size(self) -> int:\n return len(self.q)\n", | |
| "title": "1188. Design Bounded Blocking Queue", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1109 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n count = collections.Counter(text)\n return min(\n count['b'],\n count['a'],\n count['l'] // 2, count['o'] // 2, count['n'])\n", | |
| "title": "1189. Maximum Number of Balloons", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1110 | |
| }, | |
| { | |
| "code": "class Solution:\n def reverseParentheses(self, s: str) -> str:\n ans = []\n stack = []\n pair = {}\n\n for i, c in enumerate(s):\n if c == '(':\n stack.append(i)\n elif c == ')':\n j = stack.pop()\n pair[i] = j\n pair[j] = i\n\n i = 0\n d = 1\n while i < len(s):\n if s[i] in '()':\n i = pair[i]\n d = -d\n else:\n ans.append(s[i])\n i += d\n\n return ''.join(ans)\n", | |
| "title": "1190. Reverse Substrings Between Each Pair of Parentheses", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1111 | |
| }, | |
| { | |
| "code": "class Solution:\n def kConcatenationMaxSum(self, arr: list[int], k: int) -> int:\n MOD = 1_000_000_007\n sz = len(arr) * (1 if k == 1 else 2)\n summ = sum(arr)\n # The concatenated array will be [arr1, arr2, ..., arrk].\n # If sum(arr) > 0 and k > 2, then arr2, ..., arr(k - 1) should be included.\n # Equivalently, maxSubarraySum is from arr1 and arrk.\n if summ > 0 and k > 2:\n return (self._kadane(arr, sz) + summ * (k - 2)) % MOD\n return self._kadane(arr, sz) % MOD\n\n def _kadane(self, arr: list[int], sz: int) -> int:\n ans = 0\n summ = 0\n for i in range(sz):\n a = arr[i % len(arr)]\n summ = max(a, summ + a)\n ans = max(ans, summ)\n return ans\n", | |
| "title": "1191. K-Concatenation Maximum Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1112 | |
| }, | |
| { | |
| "code": "SELECT\n DATE_FORMAT(trans_date, '%Y-%m') AS month,\n country,\n COUNT(*) AS trans_count,\n SUM(state = 'approved') AS approved_count,\n SUM(amount) AS trans_total_amount,\n SUM(IF(state = 'approved', amount, 0)) AS approved_total_amount\nFROM Transactions\nGROUP BY 1, 2;\n", | |
| "title": "1193. Monthly Transactions I", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1113 | |
| }, | |
| { | |
| "code": "WITH\n PlayerToScore AS (\n (\n SELECT\n Players.player_id,\n Players.group_id,\n Matches.first_score AS score\n FROM Players\n LEFT JOIN Matches\n ON (Players.player_id = Matches.first_player)\n )\n UNION ALL\n (\n SELECT\n Players.player_id,\n Players.group_id,\n Matches.second_score AS score\n FROM Players\n LEFT JOIN Matches\n ON (Players.player_id = Matches.second_player)\n )\n ),\n RankedPlayers AS (\n SELECT\n player_id,\n group_id,\n RANK() OVER(\n PARTITION BY group_id\n ORDER BY SUM(score) DESC,\n player_id\n ) AS `rank`\n FROM PlayerToScore\n GROUP BY 1\n )\nSELECT group_id, player_id\nFROM RankedPlayers\nWHERE `rank` = 1;\n", | |
| "title": "1194. Tournament Winners", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1114 | |
| }, | |
| { | |
| "code": "from threading import Semaphore\n\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.fizzSemaphore = Semaphore(0)\n self.buzzSemaphore = Semaphore(0)\n self.fizzbuzzSemaphore = Semaphore(0)\n self.numberSemaphore = Semaphore(1)\n\n # printFizz() outputs \"fizz\"\n def fizz(self, printFizz: 'Callable[[], None]') -> None:\n for i in range(1, self.n + 1):\n if i % 3 == 0 and i % 15 != 0:\n self.fizzSemaphore.acquire()\n printFizz()\n self.numberSemaphore.release()\n\n # printBuzz() outputs \"buzz\"\n def buzz(self, printBuzz: 'Callable[[], None]') -> None:\n for i in range(1, self.n + 1):\n if i % 5 == 0 and i % 15 != 0:\n self.buzzSemaphore.acquire()\n printBuzz()\n self.numberSemaphore.release()\n\n # printFizzBuzz() outputs \"fizzbuzz\"\n def fizzbuzz(self, printFizzBuzz: 'Callable[[], None]') -> None:\n for i in range(1, self.n + 1):\n if i % 15 == 0:\n self.fizzbuzzSemaphore.acquire()\n printFizzBuzz()\n self.numberSemaphore.release()\n\n # printNumber(x) outputs \"x\", where x is an integer.\n def number(self, printNumber: 'Callable[[int], None]') -> None:\n for i in range(1, self.n + 1):\n self.numberSemaphore.acquire()\n if i % 15 == 0:\n self.fizzbuzzSemaphore.release()\n elif i % 3 == 0:\n self.fizzSemaphore.release()\n elif i % 5 == 0:\n self.buzzSemaphore.release()\n else:\n printNumber(i)\n self.numberSemaphore.release()\n", | |
| "title": "1195. Fizz Buzz Multithreaded", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1115 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxNumberOfApples(self, weight: list[int]) -> int:\n summ = 0\n\n for i, w in enumerate(sorted(weight)):\n summ += w\n if summ > 5000:\n return i\n\n return len(weight)\n", | |
| "title": "1196. How Many Apples Can You Put into the Basket", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1116 | |
| }, | |
| { | |
| "code": "class Solution:\n def smallestCommonElement(self, mat: list[list[int]]) -> int:\n MAX = 10000\n count = [0] * (MAX + 1)\n\n for row in mat:\n for a in row:\n count[a] += 1\n if count[a] == len(mat):\n return a\n\n return -1\n", | |
| "title": "1198. Find Smallest Common Element in All Rows", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1117 | |
| }, | |
| { | |
| "code": "class Solution:\n def minBuildTime(self, blocks: list[int], split: int) -> int:\n minHeap = blocks.copy()\n heapify(minHeap)\n\n while len(minHeap) > 1:\n heapq.heappop(minHeap) # the minimum\n x = heapq.heappop(minHeap) # the second minimum\n heapq.heappush(minHeap, x + split)\n\n return minHeap[0]\n", | |
| "title": "1199. Minimum Time to Build Blocks", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1118 | |
| }, | |
| { | |
| "code": "class Solution:\n def minimumAbsDifference(self, arr: list[int]) -> list[list[int]]:\n ans = []\n mn = math.inf\n\n arr.sort()\n\n for a, b in itertools.pairwise(arr):\n diff = b - a\n if diff < mn:\n mn = diff\n ans = []\n if diff == mn:\n ans.append([a, b])\n\n return ans\n", | |
| "title": "1200. Minimum Absolute Difference", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1119 | |
| }, | |
| { | |
| "code": "class Solution:\n def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:\n ab = a * b // math.gcd(a, b)\n ac = a * c // math.gcd(a, c)\n bc = b * c // math.gcd(b, c)\n abc = a * bc // math.gcd(a, bc)\n return bisect.bisect_left(range(2 * 10**9), n,\n key=lambda m: m // a + m // b + m // c\n - m // ab - m // ac - m // bc\n + m // abc)\n", | |
| "title": "1201. Ugly Number III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1120 | |
| }, | |
| { | |
| "code": "class UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self.find(u)\n j = self.find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def smallestStringWithSwaps(self, s: str, pairs: list[list[int]]) -> str:\n uf = UnionFind(len(s))\n indexToLetters = collections.defaultdict(list)\n\n for a, b in pairs:\n uf.unionByRank(a, b)\n\n for i, c in enumerate(s):\n indexToLetters[uf.find(i)].append(c)\n\n for key in indexToLetters.keys():\n indexToLetters[key].sort(reverse=True)\n\n return ''.join(indexToLetters[uf.find(i)].pop()\n for i in range(len(s)))\n", | |
| "title": "1202. Smallest String With Swaps", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1121 | |
| }, | |
| { | |
| "code": "WITH\n AccumulatedQueue AS (\n SELECT\n person_name,\n SUM(weight) OVER(ORDER BY turn) AS accumulated_weight\n FROM Queue\n )\nSELECT person_name\nFROM AccumulatedQueue\nWHERE accumulated_weight <= 1000\nORDER BY accumulated_weight DESC\nLIMIT 1;\n", | |
| "title": "1204. Last Person to Fit in the Bus", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1122 | |
| }, | |
| { | |
| "code": "WITH\n ApprovedTransactionsAndChargebacks AS (\n SELECT\n id,\n country,\n state,\n amount,\n DATE_FORMAT(trans_date, '%Y-%m') AS `month`\n FROM Transactions\n WHERE state = 'approved'\n UNION ALL\n SELECT\n trans_id AS id,\n country,\n 'chargeback' AS state,\n amount,\n DATE_FORMAT(Chargebacks.trans_date, '%Y-%m') AS `month`\n FROM Chargebacks\n LEFT JOIN Transactions\n ON (Chargebacks.trans_id = Transactions.id)\n )\nSELECT\n `month`,\n country,\n SUM(state = 'approved') AS approved_count,\n SUM(IF(state = 'approved', amount, 0)) AS approved_amount,\n SUM(state = 'chargeback') AS chargeback_count,\n SUM(IF(state = 'chargeback', amount, 0)) AS chargeback_amount\nFROM ApprovedTransactionsAndChargebacks\nGROUP BY 1, 2;\n", | |
| "title": "1205. Monthly Transactions II", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1123 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n val: int = -1\n next: 'Node' = None\n down: 'Node' = None\n\n\nclass Skiplist:\n def __init__(self):\n self.dummy = Node()\n\n def search(self, target: int) -> bool:\n node = self.dummy\n while node:\n while node.next and node.next.val < target:\n node = node.next\n if node.next and node.next.val == target:\n return True\n # Move to the next level\n node = node.down\n return False\n\n def add(self, num: int) -> None:\n # Collect nodes that are before the insertion point.\n nodes = []\n node = self.dummy\n while node:\n while node.next and node.next.val < num:\n node = node.next\n nodes.append(node)\n # Move to the next level\n node = node.down\n\n shouldInsert = True\n down = None\n while shouldInsert and nodes:\n node = nodes.pop()\n node.next = Node(num, node.next, down)\n down = node.next\n shouldInsert = random.getrandbits(1) == 0\n\n # Create a topmost new level dummy that points to the existing dummy.\n if shouldInsert:\n self.dummy = Node(-1, None, self.dummy)\n\n def erase(self, num: int) -> bool:\n node = self.dummy\n found = False\n while node:\n while node.next and node.next.val < num:\n node = node.next\n if node.next and node.next.val == num:\n # Delete the node\n node.next = node.next.next\n found = True\n # Move to the next level\n node = node.down\n return found\n\n # Move to the node s.t. node.next.val >= target\n def _advance(self, node: Node, target: int) -> None:\n while node.next and node.next.val < target:\n node = node.next\n", | |
| "title": "1206. Design Skiplist", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1124 | |
| }, | |
| { | |
| "code": "class Solution:\n def uniqueOccurrences(self, arr: list[int]) -> bool:\n count = collections.Counter(arr)\n occurrences = set()\n\n for value in count.values():\n if value in occurrences:\n return False\n occurrences.add(value)\n\n return True\n", | |
| "title": "1207. Unique Number of Occurrences", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1125 | |
| }, | |
| { | |
| "code": "class Solution:\n def equalSubstring(self, s: str, t: str, maxCost: int) -> int:\n j = 0\n for i in range(len(s)):\n maxCost -= abs(ord(s[i]) - ord(t[i]))\n if maxCost < 0:\n maxCost += abs(ord(s[j]) - ord(t[j]))\n j += 1\n\n return len(s) - j\n", | |
| "title": "1208. Get Equal Substrings Within Budget", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1126 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeDuplicates(self, s: str, k: int) -> str:\n stack = []\n\n for c in s:\n if not stack or stack[-1][0] != c:\n stack.append([c, 1])\n else: # stack[-1][0] == c\n stack[-1][1] += 1\n if stack[-1][1] == k:\n stack.pop()\n\n return ''.join(c * count for c, count in stack)\n", | |
| "title": "1209. Remove All Adjacent Duplicates in String II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1127 | |
| }, | |
| { | |
| "code": "from enum import IntEnum\n\n\nclass Pos(IntEnum):\n HORIZONTAL = 0\n VERTICAL = 1\n\n\nclass Solution:\n def minimumMoves(self, grid: list[list[int]]) -> int:\n n = len(grid)\n ans = 0\n # the state of (x, y, pos)\n # pos := 0 (horizontal) / 1 (vertical)\n q = collections.deque([(0, 0, Pos.HORIZONTAL)])\n seen = {(0, 0, Pos.HORIZONTAL)}\n\n def canMoveRight(x: int, y: int, pos: Pos) -> bool:\n if pos == Pos.HORIZONTAL:\n return y + 2 < n and not grid[x][y + 2]\n return y + 1 < n and not grid[x][y + 1] and not grid[x + 1][y + 1]\n\n def canMoveDown(x: int, y: int, pos: Pos) -> bool:\n if pos == Pos.VERTICAL:\n return x + 2 < n and not grid[x + 2][y]\n return x + 1 < n and not grid[x + 1][y] and not grid[x + 1][y + 1]\n\n def canRotateClockwise(x: int, y: int, pos: Pos) -> bool:\n return (pos == Pos.HORIZONTAL and x + 1 < n and\n not grid[x + 1][y + 1] and not grid[x + 1][y])\n\n def canRotateCounterclockwise(x: int, y: int, pos: Pos) -> bool:\n return (pos == Pos.VERTICAL and y + 1 < n and\n not grid[x + 1][y + 1] and not grid[x][y + 1])\n\n while q:\n for _ in range(len(q)):\n x, y, pos = q.popleft()\n if x == n - 1 and y == n - 2 and pos == Pos.HORIZONTAL:\n return ans\n if canMoveRight(x, y, pos) and (x, y + 1, pos) not in seen:\n q.append((x, y + 1, pos))\n seen.add((x, y + 1, pos))\n if canMoveDown(x, y, pos) and (x + 1, y, pos) not in seen:\n q.append((x + 1, y, pos))\n seen.add((x + 1, y, pos))\n newPos = Pos.VERTICAL if pos == Pos.HORIZONTAL else Pos.HORIZONTAL\n if ((canRotateClockwise(x, y, pos) or\n canRotateCounterclockwise(x, y, pos)) and\n (x, y, newPos) not in seen):\n q.append((x, y, newPos))\n seen.add((x, y, newPos))\n ans += 1\n\n return -1\n", | |
| "title": "1210. Minimum Moves to Reach Target with Rotations", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1128 | |
| }, | |
| { | |
| "code": "SELECT\n query_name,\n ROUND(AVG(rating / position), 2) AS quality,\n ROUND(AVG(rating < 3) * 100, 2) AS poor_query_percentage\nFROM Queries\nGROUP BY 1;\n", | |
| "title": "1211. Queries Quality and Percentage", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1129 | |
| }, | |
| { | |
| "code": "WITH\n TwoWayMatches AS (\n SELECT\n host_team AS team_id,\n host_goals AS goals,\n guest_goals AS opponent_goals\n FROM Matches\n UNION ALL\n SELECT\n guest_team,\n guest_goals,\n host_goals\n FROM Matches\n )\nSELECT\n Teams.team_id,\n Teams.team_name,\n SUM(\n CASE\n WHEN goals > opponent_goals THEN 3\n WHEN goals = opponent_goals THEN 1\n ELSE 0\n END\n ) AS num_points\nFROM Teams\nLEFT JOIN TwoWayMatches\n USING (team_id)\nGROUP BY 1\nORDER BY num_points DESC, team_id;\n", | |
| "title": "1212. Team Scores in Football Tournament", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1130 | |
| }, | |
| { | |
| "code": "class BSTIterator:\n def __init__(self, root: TreeNode | None, leftToRight: bool):\n self.stack = []\n self.leftToRight = leftToRight\n self._pushUntilNone(root)\n\n def hasNext(self) -> bool:\n return len(self.stack) > 0\n\n def next(self) -> int:\n node = self.stack.pop()\n if self.leftToRight:\n self._pushUntilNone(node.right)\n else:\n self._pushUntilNone(node.left)\n return node.val\n\n def _pushUntilNone(self, root: TreeNode | None):\n while root:\n self.stack.append(root)\n root = root.left if self.leftToRight else root.right\n\n\nclass Solution:\n def twoSumBSTs(\n self,\n root1: TreeNode | None,\n root2: TreeNode | None,\n target: int,\n ) -> bool:\n bst1 = BSTIterator(root1, True)\n bst2 = BSTIterator(root2, False)\n\n l = bst1.next()\n r = bst2.next()\n while True:\n summ = l + r\n if summ == target:\n return True\n if summ < target:\n if not bst1.hasNext():\n return False\n l = bst1.next()\n else:\n if not bst2.hasNext():\n return False\n r = bst2.next()\n", | |
| "title": "1214. Two Sum BSTs", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1131 | |
| }, | |
| { | |
| "code": "class Solution:\n def countSteppingNumbers(self, low: int, high: int) -> list[int]:\n ans = [0] if low == 0 else []\n\n def dfs(curr: int) -> None:\n if curr > high:\n return\n if curr >= low:\n ans.append(curr)\n\n lastDigit = curr % 10\n if lastDigit > 0:\n dfs(curr * 10 + lastDigit - 1)\n if lastDigit < 9:\n dfs(curr * 10 + lastDigit + 1)\n\n for i in range(1, 9 + 1):\n dfs(i)\n\n ans.sort()\n return ans\n", | |
| "title": "1215. Stepping Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1132 | |
| }, | |
| { | |
| "code": "class Solution:\n def isValidPalindrome(self, s: str, k: int) -> bool:\n return len(s) - self._longestPalindromeSubseq(s) <= k\n\n # Same as 516. Longest Palindromic Subsequence\n def _longestPalindromeSubseq(self, s: str) -> int:\n n = len(s)\n # dp[i][j] := the length of LPS(s[i..j])\n dp = [[0] * n for _ in range(n)]\n\n for i in range(n):\n dp[i][i] = 1\n\n for d in range(1, n):\n for i in range(n - d):\n j = i + d\n if s[i] == s[j]:\n dp[i][j] = 2 + dp[i + 1][j - 1]\n else:\n dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])\n\n return dp[0][n - 1]\n", | |
| "title": "1216. Valid Palindrome III", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1133 | |
| }, | |
| { | |
| "code": "class Solution:\n def minCostToMoveChips(self, position: list[int]) -> int:\n count = [0, 0]\n for p in position:\n count[p % 2] += 1\n return min(count[0], count[1])\n", | |
| "title": "1217. Play with Chips", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1134 | |
| }, | |
| { | |
| "code": "class Solution:\n def longestSubsequence(self, arr: list[int], difference: int) -> int:\n ans = 0\n lengthAt = {}\n\n for a in arr:\n lengthAt[a] = lengthAt.get(a - difference, 0) + 1\n ans = max(ans, lengthAt[a])\n\n return ans\n", | |
| "title": "1218. Longest Arithmetic Subsequence of Given Difference", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1135 | |
| }, | |
| { | |
| "code": "class Solution:\n def getMaximumGold(self, grid: list[list[int]]) -> int:\n def dfs(i: int, j: int) -> int:\n if i < 0 or j < 0 or i == len(grid) or j == len(grid[0]):\n return 0\n if grid[i][j] == 0:\n return 0\n\n gold = grid[i][j]\n grid[i][j] = 0 # Mark as visited.\n maxPath = max(dfs(i + 1, j), dfs(i - 1, j),\n dfs(i, j + 1), dfs(i, j - 1))\n grid[i][j] = gold\n return gold + maxPath\n\n return max(dfs(i, j)\n for i in range(len(grid))\n for j in range(len(grid[0])))\n", | |
| "title": "1219. Path with Maximum Gold", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1136 | |
| }, | |
| { | |
| "code": "class Solution:\n def countVowelPermutation(self, n: int) -> int:\n MOD = 1_000_000_007\n dp = {'a': 1, 'e': 1, 'i': 1, 'o': 1, 'u': 1}\n\n for _ in range(n - 1):\n newDp = {'a': dp['e'] + dp['i'] + dp['u'],\n 'e': dp['a'] + dp['i'],\n 'i': dp['e'] + dp['o'],\n 'o': dp['i'],\n 'u': dp['i'] + dp['o']}\n dp = newDp\n\n return sum(dp.values()) % MOD\n", | |
| "title": "1220. Count Vowels Permutation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1137 | |
| }, | |
| { | |
| "code": "class Solution:\n def queensAttacktheKing(self, queens: list[list[int]],\n king: list[int]) -> list[list[int]]:\n ans = []\n queens = {(i, j) for i, j in queens}\n\n for d in [\n [-1, -1],\n [-1, 0],\n [-1, 1],\n [0, -1],\n [0, 1],\n [1, -1],\n [1, 0],\n [1, 1]]:\n i = king[0] + d[0]\n j = king[1] + d[1]\n while 0 <= i < 8 and 0 <= j < 8:\n if (i, j) in queens:\n ans.append([i, j])\n break\n i += d[0]\n j += d[1]\n\n return ans\n", | |
| "title": "1222. Queens That Can Attack the King", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1138 | |
| }, | |
| { | |
| "code": "class Solution:\n def dieSimulator(self, n: int, rollMax: list[int]) -> int:\n MAX_ROLLS = 15\n MOD = 1_000_000_007\n\n dp = [[[0] * (MAX_ROLLS + 1) for j in range(6)] for i in range(n + 1)]\n\n for num in range(6):\n dp[1][num][1] = 1\n\n for i in range(2, n + 1):\n for currNum in range(6):\n for prevNum in range(6):\n for k in range(1, 15 + 1):\n if prevNum != currNum:\n dp[i][currNum][1] = (\n dp[i][currNum][1] + dp[i - 1][prevNum][k]) % MOD\n elif k < rollMax[currNum]:\n dp[i][currNum][k + 1] = dp[i - 1][currNum][k]\n\n ans = 0\n\n for num in range(6):\n for k in range(1, 15 + 1):\n ans += dp[n][num][k]\n\n return ans % MOD\n", | |
| "title": "1223. Dice Roll Simulation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1139 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxEqualFreq(self, nums: list[int]) -> int:\n ans = 0\n maxFreq = 0\n count = collections.Counter()\n freq = collections.Counter()\n\n for i, num in enumerate(nums):\n freq[count[num]] -= 1\n count[num] += 1\n freq[count[num]] += 1\n maxFreq = max(maxFreq, count[num])\n if maxFreq == 1 or maxFreq * freq[maxFreq] == i or (maxFreq - 1) * (\n freq[maxFreq - 1] + 1) == i:\n ans = i + 1\n\n return ans\n", | |
| "title": "1224. Maximum Equal Frequency", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1140 | |
| }, | |
| { | |
| "code": "WITH\n RankedDatesPerState AS (\n SELECT\n 'failed' AS state,\n fail_date AS `date`,\n RANK() OVER(ORDER BY fail_date) AS rank_per_state\n FROM Failed\n WHERE fail_date BETWEEN '2019-01-01' AND '2019-12-31'\n UNION ALL\n SELECT\n 'succeeded' AS state,\n success_date AS `date`,\n RANK() OVER(ORDER BY success_date) AS rank_per_state\n FROM Succeeded\n WHERE success_date BETWEEN '2019-01-01' AND '2019-12-31'\n ),\n RankedDates AS (\n SELECT\n state,\n `date`,\n rank_per_state,\n RANK() OVER(ORDER BY `date`) AS `rank`\n FROM RankedDatesPerState\n )\nSELECT\n state AS period_state,\n MIN(`date`) AS start_date,\n MAX(`date`) AS end_date\nFROM RankedDates\nGROUP BY state, (`rank` - rank_per_state)\nORDER BY start_date\n", | |
| "title": "1225. Report Contiguous Dates", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1141 | |
| }, | |
| { | |
| "code": "class Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n return 1 if n == 1 else 0.5\n", | |
| "title": "1227. Airplane Seat Assignment Probability", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1142 | |
| }, | |
| { | |
| "code": "class Solution:\n def missingNumber(self, arr: list[int]) -> int:\n n = len(arr)\n delta = (arr[-1] - arr[0]) // n\n l = 0\n r = n - 1\n\n while l < r:\n m = (l + r) // 2\n if arr[m] == arr[0] + m * delta:\n l = m + 1\n else:\n r = m\n\n return arr[0] + l * delta\n", | |
| "title": "1228. Missing Number In Arithmetic Progression", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1143 | |
| }, | |
| { | |
| "code": "class Solution:\n def minAvailableDuration(\n self,\n slots1: list[list[int]],\n slots2: list[list[int]],\n duration: int,\n ) -> list[int]:\n slots1.sort()\n slots2.sort()\n\n i = 0 # slots1's index\n j = 0 # slots2's index\n\n while i < len(slots1) and j < len(slots2):\n start = max(slots1[i][0], slots2[j][0])\n end = min(slots1[i][1], slots2[j][1])\n if start + duration <= end:\n return [start, start + duration]\n if slots1[i][1] < slots2[j][1]:\n i += 1\n else:\n j += 1\n\n return []\n", | |
| "title": "1229. Meeting Scheduler", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1144 | |
| }, | |
| { | |
| "code": "class Solution:\n def probabilityOfHeads(self, prob: list[float], target: int) -> float:\n # dp[j] := the probability of tossing the coins so far with j heads\n dp = [1.0] + [0] * len(prob)\n\n for p in prob:\n for j in range(target, -1, -1):\n dp[j] = (dp[j - 1] * p if j > 0 else 0) + dp[j] * (1 - p)\n\n return dp[target]\n", | |
| "title": "1230. Toss Strange Coins", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1145 | |
| }, | |
| { | |
| "code": "class Solution:\n def maximizeSweetness(self, sweetness: list[int], k: int) -> int:\n l = len(sweetness) // (k + 1)\n r = sum(sweetness) // (k + 1)\n\n def canEat(m: int) -> bool:\n \"\"\"\n Returns True if can eat m sweetness (the minimum sweetness of each piece).\n \"\"\"\n pieces = 0\n summ = 0 # the running sum\n for s in sweetness:\n summ += s\n if summ >= m:\n pieces += 1\n summ = 0\n return pieces > k\n\n while l < r:\n m = (l + r) // 2\n if canEat(m):\n l = m + 1\n else:\n r = m\n\n return l if canEat(l) else l - 1\n", | |
| "title": "1231. Divide Chocolate", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1146 | |
| }, | |
| { | |
| "code": "class Solution:\n def checkStraightLine(self, coordinates: list[list[int]]) -> bool:\n x0, y0, x1, y1 = *coordinates[0], *coordinates[1]\n dx = x1 - x0\n dy = y1 - y0\n\n return all((x - x0) * dy == (y - y0) * dx for x, y in coordinates)\n", | |
| "title": "1232. Check If It Is a Straight Line", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1147 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeSubfolders(self, folder: list[str]) -> list[str]:\n ans = []\n prev = \"\"\n\n folder.sort()\n\n for f in folder:\n if len(prev) > 0 and f.startswith(prev) and f[len(prev)] == '/':\n continue\n ans.append(f)\n prev = f\n\n return ans\n", | |
| "title": "1233. Remove Sub-Folders from the Filesystem", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1148 | |
| }, | |
| { | |
| "code": "class Solution:\n def balancedString(self, s: str) -> int:\n ans = len(s)\n count = collections.Counter(s)\n j = 0\n\n for i, c in enumerate(s):\n count[c] -= 1\n while j < len(s) and all(count[c] <= len(s) // 4 for c in 'QWER'):\n ans = min(ans, i - j + 1)\n count[s[j]] += 1\n j += 1\n\n return ans\n", | |
| "title": "1234. Replace the Substring for Balanced String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1149 | |
| }, | |
| { | |
| "code": "class Solution:\n def jobScheduling(\n self,\n startTime: list[int],\n endTime: list[int],\n profit: list[int],\n ) -> int:\n jobs = sorted([(s, e, p) for s, e, p in zip(startTime, endTime, profit)])\n\n # Will use binary search to find the first available startTime\n for i in range(len(startTime)):\n startTime[i] = jobs[i][0]\n\n @functools.lru_cache(None)\n def dp(i: int) -> int:\n \"\"\"Returns the maximum profit to schedule jobs[i..n).\"\"\"\n if i == len(startTime):\n return 0\n j = bisect.bisect_left(startTime, jobs[i][1])\n return max(jobs[i][2] + dp(j), dp(i + 1))\n\n return dp(0)\n", | |
| "title": "1235. Maximum Profit in Job Scheduling_2", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1150 | |
| }, | |
| { | |
| "code": "class Solution:\n def jobScheduling(\n self,\n startTime: list[int],\n endTime: list[int],\n profit: list[int],\n ) -> int:\n # dp[i] := the maximum profit to schedule jobs[i..n)\n dp = [0] * (len(startTime) + 1)\n jobs = sorted([(s, e, p) for s, e, p in zip(startTime, endTime, profit)])\n\n for i in range(len(startTime)):\n startTime[i] = jobs[i][0]\n\n for i in reversed(range(len(startTime))):\n j = bisect.bisect_left(startTime, jobs[i][1])\n dp[i] = max(jobs[i][2] + dp[j], dp[i + 1])\n\n return dp[0]\n", | |
| "title": "1235. Maximum Profit in Job Scheduling", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1151 | |
| }, | |
| { | |
| "code": "# \"\"\"\n# This is HtmlParser's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n# Class HtmlParser(object):\n# def getUrls(self, url: str) -> list[str]:\n\nclass Solution:\n def crawl(self, startUrl: str, htmlParser: 'HtmlParser') -> list[str]:\n q = collections.deque([startUrl])\n seen = {startUrl}\n hostname = startUrl.split('/')[2]\n\n while q:\n currUrl = q.popleft()\n for url in htmlParser.getUrls(currUrl):\n if url in seen:\n continue\n if hostname in url:\n q.append(url)\n seen.add(url)\n\n return seen\n", | |
| "title": "1236. Web Crawler", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1152 | |
| }, | |
| { | |
| "code": "class Solution:\n def findSolution(self, customfunction: 'CustomFunction', z: int) -> list[list[int]]:\n ans = []\n x = 1\n y = 1000\n\n while x <= 1000 and y >= 1:\n f = customfunction.f(x, y)\n if f < z:\n x += 1\n elif f > z:\n y -= 1\n else:\n ans.append([x, y])\n x += 1\n y -= 1\n\n return ans\n", | |
| "title": "1237. Find Positive Integer Solution for a Given Equation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1153 | |
| }, | |
| { | |
| "code": "class Solution:\n def circularPermutation(self, n: int, start: int) -> list[int]:\n return [start ^ i ^ i >> 1 for i in range(1 << n)]\n", | |
| "title": "1238. Circular Permutation in Binary Representation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1154 | |
| }, | |
| { | |
| "code": "class Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n @functools.lru_cache(None)\n def dp(heights: int) -> int:\n minHeight = min(heights)\n if minHeight == n: # All filled.\n return 0\n\n ans = m * n\n heightsList = list(heights)\n start = heightsList.index(minHeight)\n\n # Try to put square of different size that doesn't exceed the width/height.\n for sz in range(1, min(m - start + 1, n - minHeight + 1)):\n # heights[start..start + sz) must has the same height.\n if heights[start + sz - 1] != minHeight:\n break\n # Put a square of size `sz` to cover heights[start..start + sz).\n heightslist[start:start + sz] = [minHeight + sz] * sz\n ans = min(ans, dp(tuple(heightsList)))\n\n return 1 + ans\n\n return dp(tuple([0] * m))\n", | |
| "title": "1240. Tiling a Rectangle with the Fewest Squares", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1155 | |
| }, | |
| { | |
| "code": "WITH\n Posts AS (\n SELECT DISTINCT sub_id AS post_id\n FROM Submissions\n WHERE parent_id IS NULL\n )\nSELECT\n Posts.post_id,\n COUNT(DISTINCT Comments.sub_id) AS number_of_comments\nFROM Posts\nLEFT JOIN Submissions AS Comments\n ON (Posts.post_id = Comments.parent_id)\nGROUP BY 1;\n", | |
| "title": "1241. Number of Comments per Post", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1156 | |
| }, | |
| { | |
| "code": "class Solution:\n def transformArray(self, arr: list[int]) -> list[int]:\n if len(arr) < 3:\n return arr\n\n ans = []\n\n while ans != arr:\n ans = arr[:]\n for i in range(1, len(arr) - 1):\n if ans[i - 1] > ans[i] < ans[i + 1]:\n arr[i] += 1\n elif ans[i - 1] < ans[i] > ans[i + 1]:\n arr[i] -= 1\n\n return ans\n", | |
| "title": "1243. Array Transformation", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1157 | |
| }, | |
| { | |
| "code": "class Leaderboard:\n def __init__(self):\n self.idToScore = collections.Counter()\n\n def addScore(self, playerId: int, score: int) -> None:\n self.idToScore[playerId] += score\n\n def top(self, K: int) -> int:\n return sum(score for _, score in self.idToScore.most_common(K))\n\n def reset(self, playerId: int) -> None:\n del self.idToScore[playerId]\n", | |
| "title": "1244. Design A Leaderboard", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1158 | |
| }, | |
| { | |
| "code": "class Solution:\n def minimumMoves(self, arr: list[int]) -> int:\n n = len(arr)\n # dp[i][j] := the minimum number of moves to remove all numbers from arr[i..j]\n dp = [[n] * n for _ in range(n)]\n\n for i in range(n):\n dp[i][i] = 1\n\n for i in range(n - 1):\n dp[i][i + 1] = 1 if arr[i] == arr[i + 1] else 2\n\n for d in range(2, n):\n for i in range(n - d):\n j = i + d\n # Remove arr[i] and arr[j] within the move of removing\n # arr[i + 1..j - 1]\n if arr[i] == arr[j]:\n dp[i][j] = dp[i + 1][j - 1]\n # Try all the possible partitions.\n for k in range(i, j):\n dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j])\n\n return dp[0][n - 1]\n", | |
| "title": "1246. Palindrome Removal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1159 | |
| }, | |
| { | |
| "code": "class Solution:\n def minimumSwap(self, s1: str, s2: str) -> int:\n # ('xx', 'yy') = (2 'xy's) . 1 swap\n # ('yy', 'xx') = (2 'yx's) . 1 swap\n # ('xy', 'yx') = (1 'xy' and 1 'yx') . 2 swaps\n xy = 0 # the number of indices i's s.t. s1[i] = 'x' and s2[i] 'y'\n yx = 0 # the number of indices i's s.t. s1[i] = 'y' and s2[i] 'x'\n\n for a, b in zip(s1, s2):\n if a == b:\n continue\n if a == 'x':\n xy += 1\n else:\n yx += 1\n\n if (xy + yx) % 2 == 1:\n return -1\n return xy // 2 + yx // 2 + (0 if xy % 2 == 0 else 2)\n", | |
| "title": "1247. Minimum Swaps to Make Strings Equal", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1160 | |
| }, | |
| { | |
| "code": "class Solution:\n def numberOfSubarrays(self, nums: list[int], k: int) -> int:\n def numberOfSubarraysAtMost(k: int) -> int:\n ans = 0\n l = 0\n r = 0\n\n while r <= len(nums):\n if k >= 0:\n ans += r - l\n if r == len(nums):\n break\n if nums[r] & 1:\n k -= 1\n r += 1\n else:\n if nums[l] & 1:\n k += 1\n l += 1\n return ans\n\n return numberOfSubarraysAtMost(k) - numberOfSubarraysAtMost(k - 1)\n", | |
| "title": "1248. Count Number of Nice Subarrays", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1161 | |
| }, | |
| { | |
| "code": "class Solution:\n def minRemoveToMakeValid(self, s: str) -> str:\n stack = [] # unpaired '(' indices\n chars = list(s)\n\n for i, c in enumerate(chars):\n if c == '(':\n stack.append(i) # Record the unpaired '(' index.\n elif c == ')':\n if stack:\n stack.pop() # Find a pair\n else:\n chars[i] = '*' # Mark the unpaired ')' as '*'.\n\n # Mark the unpaired '(' as '*'.\n while stack:\n chars[stack.pop()] = '*'\n\n return ''.join(chars).replace('*', '')\n", | |
| "title": "1249. Minimum Remove to Make Valid Parentheses", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1162 | |
| }, | |
| { | |
| "code": "SELECT\n Prices.product_id,\n IFNULL(\n ROUND(\n SUM(Prices.price * UnitsSold.units) / SUM(UnitsSold.units),\n 2\n ),\n 0\n ) AS average_price\nFROM Prices\nLEFT JOIN UnitsSold\n ON (\n Prices.product_id = UnitsSold.product_id\n AND UnitsSold.purchase_date BETWEEN Prices.start_date AND Prices.end_date)\nGROUP BY 1;\n", | |
| "title": "1251. Average Selling Price", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1163 | |
| }, | |
| { | |
| "code": "class Solution:\n def oddCells(self, m: int, n: int, indices: list[list[int]]) -> int:\n # rows[i] and cols[i] :=\n # 1. True (flipped even times)\n # 2. False (flipped odd times)\n rows = [False] * m\n cols = [False] * n\n\n for r, c in indices:\n rows[r] ^= True\n cols[c] ^= True\n\n oddRowsCount = rows.count(True)\n oddColsCount = cols.count(True)\n evenRowsCount = m - oddRowsCount\n evenColsCount = n - oddColsCount\n return oddRowsCount * evenColsCount + oddColsCount * evenRowsCount\n", | |
| "title": "1252. Cells with Odd Values in a Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1164 | |
| }, | |
| { | |
| "code": "class Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: list[int]) -> list[list[int]]:\n if upper + lower != sum(colsum):\n return []\n if min(upper, lower) < colsum.count(2):\n return []\n\n ans = [[0] * len(colsum) for _ in range(2)]\n\n for j, c in enumerate(colsum):\n if c == 2:\n ans[0][j] = 1\n ans[1][j] = 1\n upper -= 1\n lower -= 1\n\n for j, c in enumerate(colsum):\n if c == 1 and upper > 0:\n ans[0][j] = 1\n c -= 1\n upper -= 1\n if c == 1 and lower > 0:\n ans[1][j] = 1\n lower -= 1\n\n return ans\n", | |
| "title": "1253. Reconstruct a 2-Row Binary Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1165 | |
| }, | |
| { | |
| "code": "class Solution:\n def closedIsland(self, grid: list[list[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n\n def dfs(i: int, j: int) -> None:\n if i < 0 or i == m or j < 0 or j == n:\n return\n if grid[i][j] == 1:\n return\n grid[i][j] = 1\n dfs(i + 1, j)\n dfs(i - 1, j)\n dfs(i, j + 1)\n dfs(i, j - 1)\n\n # Remove the lands connected to the edge.\n for i in range(m):\n for j in range(n):\n if i * j == 0 or i == m - 1 or j == n - 1:\n if grid[i][j] == 0:\n dfs(i, j)\n\n ans = 0\n\n # Reduce to 200. Number of Islands\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n dfs(i, j)\n ans += 1\n\n return ans\n", | |
| "title": "1254. Number of Closed Islands", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1166 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxScoreWords(\n self,\n words: list[str],\n letters: list[str],\n score: list[int],\n ) -> int:\n count = collections.Counter(letters)\n\n def useWord(i: int) -> int:\n isValid = True\n earned = 0\n for c in words[i]:\n count[c] -= 1\n if count[c] < 0:\n isValid = False\n earned += score[ord(c) - ord('a')]\n return earned if isValid else -1\n\n def unuseWord(i: int) -> None:\n for c in words[i]:\n count[c] += 1\n\n def dfs(s: int) -> int:\n \"\"\"Returns the maximum score you can get from words[s..n).\"\"\"\n ans = 0\n for i in range(s, len(words)):\n earned = useWord(i)\n if earned > 0:\n ans = max(ans, earned + dfs(i + 1))\n unuseWord(i)\n return ans\n\n return dfs(0)\n", | |
| "title": "1255. Maximum Score Words Formed by Letters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1167 | |
| }, | |
| { | |
| "code": "class Solution:\n def encode(self, num: int) -> str:\n return bin(num + 1)[3:]\n", | |
| "title": "1256. Encode Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1168 | |
| }, | |
| { | |
| "code": "from sortedcontainers import SortedSet\n\n\nclass Solution:\n def generateSentences(\n self,\n synonyms: list[list[str]],\n text: str,\n ) -> list[str]:\n ans = SortedSet()\n graph = collections.defaultdict(list)\n q = collections.deque([text])\n\n for s, t in synonyms:\n graph[s].append(t)\n graph[t].append(s)\n\n while q:\n u = q.popleft()\n ans.add(u)\n words = u.split()\n for i, word in enumerate(words):\n for synonym in graph[word]:\n # Replace words[i] with its synonym.\n words[i] = synonym\n newText = ' '.join(words)\n if newText not in ans:\n q.append(newText)\n\n return list(ans)\n", | |
| "title": "1258. Synonymous Sentences", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1169 | |
| }, | |
| { | |
| "code": "class Solution:\n def numberOfWays(self, numPeople: int) -> int:\n MOD = 1_000_000_007\n # dp[i] := the number of ways i handshakes could occure s.t. none of the\n # handshakes cross\n dp = [1] + [0] * (numPeople // 2)\n\n for i in range(1, numPeople // 2 + 1):\n for j in range(i):\n dp[i] += dp[j] * dp[i - 1 - j]\n dp[i] %= MOD\n\n return dp[numPeople // 2]\n", | |
| "title": "1259. Handshakes That Don't Cross", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1170 | |
| }, | |
| { | |
| "code": "class Solution:\n def shiftGrid(self, grid: list[list[int]], k: int) -> list[list[int]]:\n m = len(grid)\n n = len(grid[0])\n ans = [[0] * n for _ in range(m)]\n\n k %= m * n\n\n for i in range(m):\n for j in range(n):\n index = (i * n + j + k) % (m * n)\n x = index // n\n y = index % n\n ans[x][y] = grid[i][j]\n\n return ans\n", | |
| "title": "1260. Shift 2D Grid", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1171 | |
| }, | |
| { | |
| "code": "class FindElements:\n def __init__(self, root: TreeNode | None):\n self.vals = set()\n self.dfs(root, 0)\n\n def find(self, target: int) -> bool:\n return target in self.vals\n\n def dfs(self, root: TreeNode | None, val: int) -> None:\n if not root:\n return\n\n root.val = val\n self.vals.add(val)\n self.dfs(root.left, val * 2 + 1)\n self.dfs(root.right, val * 2 + 2)\n", | |
| "title": "1261. Find Elements in a Contaminated Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1172 | |
| }, | |
| { | |
| "code": "class Solution:\n def minPushBox(self, grid: list[list[str]]) -> int:\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(grid)\n n = len(grid[0])\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 'B':\n box = (i, j)\n elif grid[i][j] == 'S':\n player = (i, j)\n elif grid[i][j] == 'T':\n target = (i, j)\n\n def isInvalid(playerX: int, playerY: int) -> bool:\n return (playerX < 0 or playerX == m or playerY < 0 or playerY == n or\n grid[playerX][playerY] == '#')\n\n def canGoTo(\n playerX: int,\n playerY: int,\n fromX: int,\n fromY: int,\n boxX: int,\n boxY: int\n ) -> bool:\n \"\"\"Returns True if (playerX, playerY) can go to (fromX, fromY).\"\"\"\n q = collections.deque([(playerX, playerY)])\n seen = {(playerX, playerY)}\n\n while q:\n i, j = q.popleft()\n if i == fromX and j == fromY:\n return True\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if isInvalid(x, y):\n continue\n if (x, y) in seen:\n continue\n if x == boxX and y == boxY:\n continue\n q.append((x, y))\n seen.add((x, y))\n\n return False\n\n # (boxX, boxY, playerX, playerY)\n q = collections.deque([(box[0], box[1], player[0], player[1])])\n seen = {(box[0], box[1], player[0], player[1])}\n\n step = 0\n while q:\n for _ in range(len(q)):\n boxX, boxY, playerX, playerY = q.popleft()\n if boxX == target[0] and boxY == target[1]:\n return step\n for k, (dx, dy) in enumerate(DIRS):\n nextBoxX = boxX + dx\n nextBoxY = boxY + dy\n if isInvalid(nextBoxX, nextBoxY):\n continue\n if (nextBoxX, nextBoxY, boxX, boxY) in seen:\n continue\n fromX = boxX + DIRS[(k + 2) % 4][0]\n fromY = boxY + DIRS[(k + 2) % 4][1]\n if isInvalid(fromX, fromY):\n continue\n if canGoTo(playerX, playerY, fromX, fromY, boxX, boxY):\n q.append((nextBoxX, nextBoxY, boxX, boxY))\n seen.add((nextBoxX, nextBoxY, boxX, boxY))\n step += 1\n\n return -1\n", | |
| "title": "1263. Minimum Moves to Move a Box to Their Target Location", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1173 | |
| }, | |
| { | |
| "code": "WITH\n UserToFriends AS (\n SELECT user1_id AS user_id, user2_id AS friend_id FROM Friendship\n UNION ALL\n SELECT user2_id AS user_id, user1_id AS friend_id FROM friendship\n )\nSELECT FriendLikes.page_id AS recommended_page\nFROM UserToFriends\nLEFT JOIN Likes AS FriendLikes\n ON (UserToFriends.friend_id = FriendLikes.user_id)\nLEFT JOIN Likes AS UserLikes\n ON (\n UserToFriends.user_id = UserLikes.user_id\n AND FriendLikes.page_id = UserLikes.page_id)\nWHERE\n UserToFriends.user_id = 1\n AND UserLikes.page_id IS NULL\n AND FriendLikes.page_id IS NOT NULL\nGROUP BY 1;\n", | |
| "title": "1264. Page Recommendations", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1174 | |
| }, | |
| { | |
| "code": "class Solution:\n def minTimeToVisitAllPoints(self, points: list[list[int]]) -> int:\n ans = 0\n\n for i in range(1, len(points)):\n ans += max(abs(points[i][0] - points[i - 1][0]),\n abs(points[i][1] - points[i - 1][1]))\n\n return ans\n", | |
| "title": "1266. Minimum Time Visiting All Points", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1175 | |
| }, | |
| { | |
| "code": "class Solution:\n def countServers(self, grid: list[list[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n ans = 0\n rows = [0] * m\n cols = [0] * n\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n rows[i] += 1\n cols[j] += 1\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1 and (rows[i] > 1 or cols[j] > 1):\n ans += 1\n\n return ans\n", | |
| "title": "1267. Count Servers that Communicate", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1176 | |
| }, | |
| { | |
| "code": "class TrieNode:\n def __init__(self):\n self.children: dict[str, TrieNode] = {}\n self.word: str | None = None\n\n\nclass Solution:\n def suggestedProducts(\n self,\n products: list[str],\n searchWord: str\n ) -> list[list[str]]:\n ans = []\n root = TrieNode()\n\n def insert(word: str) -> None:\n node = root\n for c in word:\n node = node.children.setdefault(c, TrieNode())\n node.word = word\n\n def search(node: TrieNode | None) -> list[str]:\n res: list[str] = []\n dfs(node, res)\n return res\n\n def dfs(node: TrieNode | None, res: list[str]) -> None:\n if len(res) == 3:\n return\n if not node:\n return\n if node.word:\n res.append(node.word)\n for c in string.ascii_lowercase:\n if c in node.children:\n dfs(node.children[c], res)\n\n for product in products:\n insert(product)\n\n node = root\n\n for c in searchWord:\n if not node or c not in node.children:\n node = None\n ans.append([])\n continue\n node = node.children[c]\n ans.append(search(node))\n\n return ans\n", | |
| "title": "1268. Search Suggestions System", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1177 | |
| }, | |
| { | |
| "code": "class Solution:\n def numWays(self, steps: int, arrLen: int) -> int:\n MOD = 1_000_000_007\n # dp[i] := the number of ways to stay at index i\n dp = [0] * min(steps // 2 + 1, arrLen)\n dp[0] = 1\n\n for _ in range(steps):\n newDp = [0] * min(steps // 2 + 1, arrLen)\n for i, ways in enumerate(dp):\n if ways > 0:\n for dx in (-1, 0, 1):\n nextIndex = i + dx\n if 0 <= nextIndex < len(dp):\n newDp[nextIndex] += ways\n newDp[nextIndex] %= MOD\n dp = newDp\n\n return dp[0]\n", | |
| "title": "1269. Number of Ways to Stay in the Same Place After Some Steps", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1178 | |
| }, | |
| { | |
| "code": "SELECT Employee.employee_id\nFROM Employees AS Employee\nINNER JOIN Employees AS DirectManager\n ON (Employee.manager_id = DirectManager.employee_id)\nINNER JOIN Employees AS SkipManager\n ON (DirectManager.manager_id = SkipManager.employee_id)\nWHERE\n SkipManager.manager_id = 1\n AND Employee.employee_id != 1;\n", | |
| "title": "1270. All People Report to the Given Manager", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1179 | |
| }, | |
| { | |
| "code": "class Solution:\n def toHexspeak(self, num: str) -> str:\n s = hex(int(num)).upper()[2:].translate(str.maketrans('01', 'OI'))\n return 'ERROR' if any(c.isdigit() for c in s) else s\n", | |
| "title": "1271. Hexspeak", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1180 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeInterval(self, intervals: list[list[int]],\n toBeRemoved: list[int]) -> list[list[int]]:\n ans = []\n\n for a, b in intervals:\n if a >= toBeRemoved[1] or b <= toBeRemoved[0]:\n ans.append([a, b])\n else: # a < toBeRemoved[1] and b > toBeRemoved[0]\n if a < toBeRemoved[0]:\n ans.append([a, toBeRemoved[0]])\n if b > toBeRemoved[1]:\n ans.append([toBeRemoved[1], b])\n\n return ans\n", | |
| "title": "1272. Remove Interval", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1181 | |
| }, | |
| { | |
| "code": "# \"\"\"\n# This is Sea's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n# class Sea(object):\n# def hasShips(self, topRight: 'Point', bottomLeft: 'Point') -> bool:\n# pass\n#\n# class Point(object):\n# def __init__(self, x: int, y: int):\n# self.x = x\n# self.y = y\n\nclass Solution(object):\n def countShips(\n self,\n sea: 'Sea',\n topRight: 'Point',\n bottomLeft: 'Point',\n ) -> int:\n if topRight.x < bottomLeft.x or topRight.y < bottomLeft.y:\n return 0\n if not sea.hasShips(topRight, bottomLeft):\n return 0\n\n # sea.hashShips(topRight, bottomLeft) == True\n if topRight.x == bottomLeft.x and topRight.y == bottomLeft.y:\n return 1\n\n mx = (topRight.x + bottomLeft.x) // 2\n my = (topRight.y + bottomLeft.y) // 2\n ans = 0\n # the top-right\n ans += self.countShips(sea, topRight, Point(mx + 1, my + 1))\n # the bottom-right\n ans += self.countShips(sea, Point(topRight.x, my),\n Point(mx + 1, bottomLeft.y))\n # the top-left\n ans += self.countShips(sea, Point(mx, topRight.y),\n Point(bottomLeft.x, my + 1))\n # the bottom-left\n ans += self.countShips(sea, Point(mx, my), bottomLeft)\n return ans\n", | |
| "title": "1274. Number of Ships in a Rectangle", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1182 | |
| }, | |
| { | |
| "code": "class Solution:\n def tictactoe(self, moves: list[list[int]]) -> str:\n row = [[0] * 3 for _ in range(2)]\n col = [[0] * 3 for _ in range(2)]\n diag1 = [0] * 2\n diag2 = [0] * 2\n i = 0\n\n for r, c in moves:\n row[i][r] += 1\n col[i][c] += 1\n diag1[i] += r == c\n diag2[i] += r + c == 2\n if 3 in (row[i][r], col[i][c], diag1[i], diag2[i]):\n return 'A' if i == 0 else 'B'\n i ^= 1\n\n return 'Draw' if len(moves) == 9 else 'Pending'\n", | |
| "title": "1275. Find Winner on a Tic Tac Toe Game", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1183 | |
| }, | |
| { | |
| "code": "class Solution:\n def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> list[int]:\n if tomatoSlices % 2 == 1 or tomatoSlices < 2 * cheeseSlices or tomatoSlices > cheeseSlices * 4:\n return []\n\n jumboBurgers = (tomatoSlices - 2 * cheeseSlices) // 2\n\n return [jumboBurgers, cheeseSlices - jumboBurgers]\n", | |
| "title": "1276. Number of Burgers with No Waste of Ingredients", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1184 | |
| }, | |
| { | |
| "code": "class Solution:\n def countSquares(self, matrix: list[list[int]]) -> int:\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == 1 and i > 0 and j > 0:\n matrix[i][j] += min(matrix[i - 1][j - 1],\n matrix[i - 1][j], matrix[i][j - 1])\n return sum(map(sum, matrix))\n", | |
| "title": "1277. Count Square Submatrices with All Ones", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1185 | |
| }, | |
| { | |
| "code": "class TrafficLight:\n def __init__(self):\n self.canPassRoadId = 1 # 1 := road A, 2 := road B\n\n def carArrived(\n self,\n # ID of the car\n carId: int,\n # ID of the road the car travels on. Can be 1 (road A) or 2 (road B).\n roadId: int,\n # direction of the car\n direction: int,\n # Use turnGreen() to turn light to green on current road.\n turnGreen: Callable[[], None],\n # Use crossCar() to make car cross the intersection.\n crossCar: Callable[[], None]\n ) -> None:\n if roadId != self.canPassRoadId:\n self.canPassRoadId = roadId\n turnGreen()\n crossCar()\n", | |
| "title": "1279. Traffic Light Controlled Intersection", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1186 | |
| }, | |
| { | |
| "code": "SELECT\n Students.student_id,\n Students.student_name,\n Subjects.subject_name,\n COUNT(Examinations.student_id) AS attended_exams\nFROM Students\nCROSS JOIN Subjects\nLEFT JOIN Examinations\n ON (\n Students.student_id = Examinations.student_id\n AND Subjects.subject_name = Examinations.subject_name)\nGROUP BY 1, 2, 3\nORDER BY Students.student_id, Subjects.subject_name;\n", | |
| "title": "1280. Students and Examinations", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1187 | |
| }, | |
| { | |
| "code": "class Solution:\n def subtractProductAndSum(self, n: int) -> int:\n prod = 1\n summ = 0\n\n while n > 0:\n prod *= n % 10\n summ += n % 10\n n //= 10\n\n return prod - summ\n", | |
| "title": "1281. Subtract the Product and Sum of Digits of an Integer", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1188 | |
| }, | |
| { | |
| "code": "class Solution:\n def groupThePeople(self, groupSizes: list[int]) -> list[list[int]]:\n ans = []\n groupSizeToIndices = defaultdict(list)\n\n for i, groupSize in enumerate(groupSizes):\n groupSizeToIndices[groupSize].append(i)\n\n for groupSize, indices in groupSizeToIndices.items():\n groupIndices = []\n for index in indices:\n groupIndices.append(index)\n if len(groupIndices) == groupSize:\n ans.append(groupIndices.copy())\n groupIndices.clear()\n\n return ans\n", | |
| "title": "1282. Group the People Given the Group Size They Belong To", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1189 | |
| }, | |
| { | |
| "code": "class Solution:\n def smallestDivisor(self, nums: list[int], threshold: int) -> int:\n l = 1\n r = max(nums)\n\n while l < r:\n m = (l + r) // 2\n if sum((num - 1) // m + 1 for num in nums) <= threshold:\n r = m\n else:\n l = m + 1\n\n return l\n", | |
| "title": "1283. Find the Smallest Divisor Given a Threshold", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1190 | |
| }, | |
| { | |
| "code": "class Solution:\n def minFlips(self, mat: list[list[int]]) -> int:\n m = len(mat)\n n = len(mat[0])\n hash = self._getHash(mat, m, n)\n if hash == 0:\n return 0\n\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n step = 0\n q = collections.deque([hash])\n seen = {hash}\n\n while q:\n step += 1\n for _ in range(len(q)):\n curr = q.popleft()\n for i in range(m):\n for j in range(n):\n next = curr ^ 1 << (i * n + j)\n # Flie the four neighbors.\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n next ^= 1 << (x * n + y)\n if next == 0:\n return step\n if next in seen:\n continue\n q.append(next)\n seen.add(next)\n\n return -1\n\n def _getHash(self, mat: list[list[int]], m: int, n: int) -> int:\n hash = 0\n for i in range(m):\n for j in range(n):\n if mat[i][j]:\n hash |= 1 << (i * n + j)\n return hash\n", | |
| "title": "1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1191 | |
| }, | |
| { | |
| "code": "WITH\n LogToRowNumber AS (\n SELECT\n log_id,\n ROW_NUMBER() OVER(ORDER BY log_id) AS `row_number`\n FROM Logs\n )\nSELECT\n MIN(log_id) AS start_id,\n MAX(log_id) AS end_id\nFROM LogToRowNumber\nGROUP BY log_id - `row_number`;\n", | |
| "title": "1285. Find the Start and End Number of Continuous Ranges", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1192 | |
| }, | |
| { | |
| "code": "class Solution:\n def findSpecialInteger(self, arr: list[int]) -> int:\n n = len(arr)\n quarter = n // 4\n\n for i in range(n - quarter):\n if arr[i] == arr[i + quarter]:\n return arr[i]\n", | |
| "title": "1287. Element Appearing More Than 25% In Sorted Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1193 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeCoveredIntervals(self, intervals: list[list[int]]) -> int:\n ans = 0\n prevEnd = 0\n\n for _, end in sorted(intervals, key=lambda x: (x[0], -x[1])):\n # The current interval is not covered by the previous one.\n if prevEnd < end:\n prevEnd = end\n ans += 1\n\n return ans\n", | |
| "title": "1288. Remove Covered Intervals", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1194 | |
| }, | |
| { | |
| "code": "class Solution:\n def minFallingPathSum(self, grid: list[list[int]]) -> int:\n n = len(grid)\n\n for i in range(1, n):\n (firstMinNum, firstMinIndex), (secondMinNum, _) = sorted(\n {(a, i) for i, a in enumerate(grid[i - 1])})[:2]\n for j in range(n):\n if j == firstMinIndex:\n grid[i][j] += secondMinNum\n else:\n grid[i][j] += firstMinNum\n\n return min(grid[-1])\n", | |
| "title": "1289. Minimum Falling Path Sum II", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1195 | |
| }, | |
| { | |
| "code": "class Solution:\n def getDecimalValue(self, head: ListNode) -> int:\n ans = 0\n\n while head:\n ans = ans * 2 + head.val\n head = head.next\n\n return ans\n", | |
| "title": "1290. Convert Binary Number in a Linked List to Integer", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1196 | |
| }, | |
| { | |
| "code": "class Solution:\n def sequentialDigits(self, low: int, high: int) -> list[int]:\n ans = []\n q = collections.deque([num for num in range(1, 10)])\n\n while q:\n num = q.popleft()\n if num > high:\n return ans\n if low <= num and num <= high:\n ans.append(num)\n lastDigit = num % 10\n if lastDigit < 9:\n q.append(num * 10 + lastDigit + 1)\n\n return ans\n", | |
| "title": "1291. Sequential Digits", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1197 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxSideLength(self, mat: list[list[int]], threshold: int) -> int:\n m = len(mat)\n n = len(mat[0])\n ans = 0\n prefix = [[0] * (n + 1) for _ in range(m + 1)]\n\n for i in range(m):\n for j in range(n):\n prefix[i + 1][j + 1] = (mat[i][j] + prefix[i][j + 1] +\n prefix[i + 1][j] - prefix[i][j])\n\n def squareSum(r1: int, c1: int, r2: int, c2: int) -> int:\n return prefix[r2 + 1][c2 + 1] - prefix[r1][c2 + 1] - prefix[r2 + 1][c1] + prefix[r1][c1]\n\n for i in range(m):\n for j in range(n):\n for length in range(ans, min(m - i, n - j)):\n if squareSum(i, j, i + length, j + length) > threshold:\n break\n ans = max(ans, length + 1)\n\n return ans\n", | |
| "title": "1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1198 | |
| }, | |
| { | |
| "code": "class Solution:\n def shortestPath(self, grid: list[list[int]], k: int) -> int:\n m = len(grid)\n n = len(grid[0])\n if m == 1 and n == 1:\n return 0\n\n DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))\n q = collections.deque([(0, 0, k)])\n seen = {(0, 0, k)}\n\n step = 0\n while q:\n step += 1\n for _ in range(len(q)):\n i, j, eliminate = q.popleft()\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if x == m - 1 and y == n - 1:\n return step\n if grid[x][y] == 1 and eliminate == 0:\n continue\n newEliminate = eliminate - grid[x][y]\n if (x, y, newEliminate) in seen:\n continue\n q.append((x, y, newEliminate))\n seen.add((x, y, newEliminate))\n\n return -1\n", | |
| "title": "1293. Shortest Path in a Grid with Obstacles Elimination", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1199 | |
| }, | |
| { | |
| "code": "SELECT\n country_name,\n (\n CASE\n WHEN AVG(Weather.weather_state * 1.0) <= 15.0 THEN 'Cold'\n WHEN AVG(Weather.weather_state * 1.0) >= 25.0 THEN 'Hot'\n ELSE 'Warm'\n END\n ) AS weather_type\nFROM Countries\nINNER JOIN Weather\n USING (country_id)\nWHERE day BETWEEN '2019-11-01' AND '2019-11-30'\nGROUP BY 1;\n", | |
| "title": "1294. Weather Type in Each Country", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1200 | |
| }, | |
| { | |
| "code": "class Solution:\n def findNumbers(self, nums: list[int]) -> int:\n ans = 0\n\n for num in nums:\n if 9 < num < 100 or 999 < num < 10000 or num == 100000:\n ans += 1\n\n return ans\n", | |
| "title": "1295. Find Numbers with Even Number of Digits", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1201 | |
| }, | |
| { | |
| "code": "class Solution:\n def isPossibleDivide(self, nums: list[int], k: int) -> bool:\n count = collections.Counter(nums)\n\n for start in sorted(count):\n value = count[start]\n if value > 0:\n for i in range(start, start + k):\n count[i] -= value\n if count[i] < 0:\n return False\n\n return True\n", | |
| "title": "1296. Divide Array in Sets of K Consecutive Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1202 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:\n # Greedily consider strings with `minSize`, so ignore `maxSize`.\n ans = 0\n letters = 0\n count = collections.Counter()\n substringCount = collections.Counter()\n\n l = 0\n for r, c in enumerate(s):\n count[c] += 1\n if count[c] == 1:\n letters += 1\n while letters > maxLetters or r - l + 1 > minSize:\n count[s[l]] -= 1\n if count[s[l]] == 0:\n letters -= 1\n l += 1\n if r - l + 1 == minSize:\n sub = s[l:l + minSize]\n substringCount[sub] += 1\n ans = max(ans, substringCount[sub])\n\n return ans\n", | |
| "title": "1297. Maximum Number of Occurrences of a Substring", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1203 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxCandies(\n self,\n status: list[int],\n candies: list[int],\n keys: list[list[int]],\n containedBoxes: list[list[int]],\n initialBoxes: list[int],\n ) -> int:\n ans = 0\n q = collections.deque()\n reachedClosedBoxes = [0] * len(status)\n\n def pushBoxesIfPossible(boxes: list[int]) -> None:\n for box in boxes:\n if status[box]:\n q.append(box)\n else:\n reachedClosedBoxes[box] = True\n\n pushBoxesIfPossible(initialBoxes)\n\n while q:\n currBox = q.popleft()\n\n # Add the candies.\n ans += candies[currBox]\n\n # Push `reachedClosedBoxes` by `key` obtained in this turn and change\n # their statuses.\n for key in keys[currBox]:\n if not status[key] and reachedClosedBoxes[key]:\n q.append(key)\n status[key] = 1 # boxes[key] is now open\n\n # Push the boxes contained in `currBox`.\n pushBoxesIfPossible(containedBoxes[currBox])\n\n return ans\n", | |
| "title": "1298. Maximum Candies You Can Get from Boxes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1204 | |
| }, | |
| { | |
| "code": "class Solution:\n def replaceElements(self, arr: list[int]) -> list[int]:\n maxOfRight = -1\n for i in reversed(range(len(arr))):\n arr[i], maxOfRight = maxOfRight, max(maxOfRight, arr[i])\n return arr\n", | |
| "title": "1299. Replace Elements with Greatest Element on Right Side", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1205 | |
| }, | |
| { | |
| "code": "class Solution:\n def findBestValue(self, arr: list[int], target: int) -> int:\n prefix = 0\n\n arr.sort()\n\n for i, a in enumerate(arr):\n ans = round((target - prefix) / (len(arr) - i))\n if ans <= a:\n return ans\n prefix += a\n\n return arr[-1]\n", | |
| "title": "1300. Sum of Mutated Array Closest to Target", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1206 | |
| }, | |
| { | |
| "code": "class Solution:\n def pathsWithMaxScore(self, board: list[str]) -> list[int]:\n MOD = 1_000_000_007\n DIRS = ((0, 1), (1, 0), (1, 1))\n n = len(board)\n # dp[i][j] := the maximum sum from (n - 1, n - 1) to (i, j)\n dp = [[-1] * (n + 1) for _ in range(n + 1)]\n # count[i][j] := the number of paths to get dp[i][j] from (n - 1, n - 1) to\n # (i, j)\n count = [[0] * (n + 1) for _ in range(n + 1)]\n\n dp[0][0] = 0\n dp[n - 1][n - 1] = 0\n count[n - 1][n - 1] = 1\n\n for i in reversed(range(n)):\n for j in reversed(range(n)):\n if board[i][j] == 'S' or board[i][j] == 'X':\n continue\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if dp[i][j] < dp[x][y]:\n dp[i][j] = dp[x][y]\n count[i][j] = count[x][y]\n elif dp[i][j] == dp[x][y]:\n count[i][j] += count[x][y]\n count[i][j] %= MOD\n\n # If there's path(s) from 'S' to (i, j) and the cell is not 'E'.\n if dp[i][j] != -1 and board[i][j] != 'E':\n dp[i][j] += int(board[i][j])\n dp[i][j] %= MOD\n\n return [dp[0][0], count[0][0]]\n", | |
| "title": "1301. Number of Paths with Max Score", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1207 | |
| }, | |
| { | |
| "code": "SELECT\n employee_id,\n COUNT(*) OVER(PARTITION BY team_id) AS team_size\nFROM Employee;\n", | |
| "title": "1303. Find the Team Size", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1208 | |
| }, | |
| { | |
| "code": "class Solution:\n def sumZero(self, n: int) -> list[int]:\n return list(range(1 - n, n, 2))\n", | |
| "title": "1304. Find N Unique Integers Sum up to Zero", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1209 | |
| }, | |
| { | |
| "code": "class Solution:\n def isSolvable(self, words: list[str], result: str) -> bool:\n words.append(result)\n rows = len(words)\n cols = max(map(len, words))\n letterToDigit = {}\n usedDigit = [False] * 10\n\n def dfs(row: int, col: int, summ: int) -> bool:\n if col == cols:\n return summ == 0\n if row == rows:\n return summ % 10 == 0 and dfs(0, col + 1, summ // 10)\n\n word = words[row]\n if col >= len(word):\n return dfs(row + 1, col, summ)\n\n letter = word[~col]\n sign = -1 if row == rows - 1 else 1\n\n if letter in letterToDigit and (\n letterToDigit[letter] > 0 or col < len(word) - 1):\n return dfs(row + 1, col, summ + sign * letterToDigit[letter])\n\n for digit, used in enumerate(usedDigit):\n if not used and (digit > 0 or col < len(word) - 1):\n letterToDigit[letter] = digit\n usedDigit[digit] = True\n if dfs(row + 1, col, summ + sign * digit):\n return True\n usedDigit[digit] = False\n if letter in letterToDigit:\n del letterToDigit[letter]\n\n return False\n\n return dfs(0, 0, 0)\n", | |
| "title": "1307. Verbal Arithmetic Puzzle", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1210 | |
| }, | |
| { | |
| "code": "SELECT\n gender,\n day,\n SUM(score_points) OVER(\n PARTITION BY gender\n ORDER BY day\n ) AS total\nFROM Scores\nORDER BY 1, 2;\n", | |
| "title": "1308. Running Total for Different Genders", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1211 | |
| }, | |
| { | |
| "code": "class Solution:\n def freqAlphabets(self, s: str) -> str:\n ans = ''\n i = 0\n\n while i < len(s):\n if i + 2 < len(s) and s[i + 2] == '#':\n ans += chr(int(s[i:i + 2]) + ord('a') - 1)\n i += 3\n else:\n ans += chr(int(s[i]) + ord('a') - 1)\n i += 1\n\n return ans\n", | |
| "title": "1309. Decrypt String from Alphabet to Integer Mapping", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1212 | |
| }, | |
| { | |
| "code": "class Solution:\n def xorQueries(self, arr: list[int], queries: list[list[int]]) -> list[int]:\n ans = []\n xors = [0] * (len(arr) + 1)\n\n for i, a in enumerate(arr):\n xors[i + 1] = xors[i] ^ a\n\n for left, right in queries:\n ans.append(xors[left] ^ xors[right + 1])\n\n return ans\n", | |
| "title": "1310. XOR Queries of a Subarray", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1213 | |
| }, | |
| { | |
| "code": "class Solution:\n def watchedVideosByFriends(\n self,\n watchedVideos: list[list[str]],\n friends: list[list[int]],\n id: int,\n level: int,\n ) -> list[str]:\n seen = [False] * 100\n seen[id] = True\n q = collections.deque([id])\n count = collections.Counter()\n\n for _ in range(level):\n for _ in range(len(q)):\n curr = q.popleft()\n for friend in friends[curr]:\n if not seen[friend]:\n seen[friend] = True\n q.append(friend)\n\n for friend in q:\n for video in watchedVideos[friend]:\n count[video] += 1\n\n return sorted(count, key=lambda video: (count[video], video))\n", | |
| "title": "1311. Get Watched Videos by Your Friends", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1214 | |
| }, | |
| { | |
| "code": "class Solution:\n def minInsertions(self, s: str) -> int:\n return len(s) - self._longestPalindromeSubseq(s)\n\n # Same as 516. Longest Palindromic Subsequence\n def _longestPalindromeSubseq(self, s: str) -> int:\n n = len(s)\n # dp[i][j] := the length of LPS(s[i..j])\n dp = [[0] * n for _ in range(n)]\n\n for i in range(n):\n dp[i][i] = 1\n\n for d in range(1, n):\n for i in range(n - d):\n j = i + d\n if s[i] == s[j]:\n dp[i][j] = 2 + dp[i + 1][j - 1]\n else:\n dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])\n\n return dp[0][n - 1]\n", | |
| "title": "1312. Minimum Insertion Steps to Make a String Palindrome", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1215 | |
| }, | |
| { | |
| "code": "class Solution:\n def decompressRLElist(self, nums: list[int]) -> list[int]:\n ans = []\n\n for i in range(0, len(nums), 2):\n ans += [nums[i + 1]] * nums[i]\n\n return ans\n", | |
| "title": "1313. Decompress Run-Length Encoded List", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1216 | |
| }, | |
| { | |
| "code": "class Solution:\n def matrixBlockSum(self, mat: list[list[int]], k: int) -> list[list[int]]:\n m = len(mat)\n n = len(mat[0])\n ans = [[0] * n for _ in range(m)]\n prefix = [[0] * (n + 1) for _ in range(m + 1)]\n\n for i in range(m):\n for j in range(n):\n prefix[i + 1][j + 1] = (mat[i][j] + prefix[i][j + 1] +\n prefix[i + 1][j] - prefix[i][j])\n\n for i in range(m):\n for j in range(n):\n r1 = max(0, i - k) + 1\n c1 = max(0, j - k) + 1\n r2 = min(m - 1, i + k) + 1\n c2 = min(n - 1, j + k) + 1\n ans[i][j] = (prefix[r2][c2] - prefix[r2][c1 - 1] -\n prefix[r1 - 1][c2] + prefix[r1 - 1][c1 - 1])\n\n return ans\n", | |
| "title": "1314. Matrix Block Sum", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1217 | |
| }, | |
| { | |
| "code": "class Solution:\n def distinctEchoSubstrings(self, text: str) -> int:\n seen = set()\n\n for k in range(1, len(text) // 2 + 1): # the target length\n same = 0\n l = 0\n for r in range(k, len(text)):\n if text[l] == text[r]:\n same += 1\n else:\n same = 0\n if same == k:\n seen.add(text[l - k + 1:l + 1])\n # Move the window thus leaving a letter behind, so we need to\n # decrease the counter.\n same -= 1\n l += 1\n\n return len(seen)\n", | |
| "title": "1316. Distinct Echo Substrings", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1218 | |
| }, | |
| { | |
| "code": "class Solution:\n def getNoZeroIntegers(self, n: int) -> list[int]:\n for A in range(n):\n B = n - A\n if '0' not in str(A) and '0' not in str(B):\n return A, B\n", | |
| "title": "1317. Convert Integer to the Sum of Two No-Zero Integers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1219 | |
| }, | |
| { | |
| "code": "class Solution:\n def minFlips(self, a: int, b: int, c: int) -> int:\n MAX_BIT = 30\n ans = 0\n\n for i in range(MAX_BIT):\n if c >> i & 1:\n ans += (a >> i & 1) == 0 and (b >> i & 1) == 0\n else: # (c >> i & 1) == 0\n ans += (a >> i & 1) + (b >> i & 1)\n\n return ans\n", | |
| "title": "1318. Minimum Flips to Make a OR b Equal to c", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1220 | |
| }, | |
| { | |
| "code": "class Solution:\n def minimumDistance(self, word: str) -> int:\n def dist(a: int, b: int) -> int:\n if a == 26: # the first hovering state\n return 0\n x1, y1 = a // 6, a % 6\n x2, y2 = b // 6, b % 6\n return abs(x1 - x2) + abs(y1 - y2)\n\n @functools.lru_cache(None)\n def dp(i: int, j: int, k: int) -> int:\n \"\"\"\n Returns the minimum distance to type the `word`, where the left finger is\n on the i-th letter, the right finger is on the j-th letter, and the\n words[0..k) have been written.\n \"\"\"\n if k == len(word):\n return 0\n nxt = ord(word[k]) - ord('A')\n moveLeft = dist(i, nxt) + dp(nxt, j, k + 1)\n moveRight = dist(j, nxt) + dp(i, nxt, k + 1)\n return min(moveLeft, moveRight)\n\n return dp(26, 26, 0)\n", | |
| "title": "1320. Minimum Distance to Type a Word Using Two Fingers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1221 | |
| }, | |
| { | |
| "code": "WITH\n Dates AS (\n SELECT DISTINCT visited_on\n FROM Customer\n WHERE visited_on >= (\n SELECT DATE_ADD(MIN(visited_on), INTERVAL 6 DAY)\n FROM Customer\n )\n )\nSELECT\n Dates.visited_on,\n SUM(Customer.amount) AS amount,\n ROUND(SUM(Customer.amount) / 7, 2) AS average_amount\nFROM Dates\nLEFT JOIN Customer\n ON (DATEDIFF(Dates.visited_on, Customer.visited_on) BETWEEN 0 AND 6)\nGROUP BY 1;\n", | |
| "title": "1321. Restaurant Growth", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1222 | |
| }, | |
| { | |
| "code": "SELECT\n ad_id,\n IFNULL(\n ROUND(\n SUM(action = 'Clicked') * 100 /(SUM(action = 'Clicked') + SUM(action = 'Viewed')),\n 2\n ),\n 0\n ) AS ctr\nFROM Ads\nGROUP BY 1\nORDER BY ctr DESC, ad_id;\n", | |
| "title": "1322. Ads Performance", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1223 | |
| }, | |
| { | |
| "code": "class Solution:\n def maximum69Number(self, num: int) -> int:\n return int(str(num).replace('6', '9', 1))\n", | |
| "title": "1323. Maximum 69 Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1224 | |
| }, | |
| { | |
| "code": "class Solution:\n def printVertically(self, s: str) -> list[str]:\n ans = []\n words = s.split()\n maxLength = max(len(word) for word in words)\n\n for i in range(maxLength):\n row = []\n for word in words:\n row.append(word[i] if i < len(word) else ' ')\n ans.append(''.join(row).rstrip())\n\n return ans\n", | |
| "title": "1324. Print Words Vertically", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1225 | |
| }, | |
| { | |
| "code": "class Solution:\n def removeLeafNodes(\n self,\n root: TreeNode | None,\n target: int,\n ) -> TreeNode | None:\n if not root:\n return None\n root.left = self.removeLeafNodes(root.left, target)\n root.right = self.removeLeafNodes(root.right, target)\n return None if self._isLeaf(root) and root.val == target else root\n\n def _isLeaf(self, root: TreeNode | None) -> bool:\n return not root.left and not root.right\n", | |
| "title": "1325. Delete Leaves With a Given Value", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1226 | |
| }, | |
| { | |
| "code": "class Solution:\n def minTaps(self, n: int, ranges: list[int]) -> int:\n nums = [0] * (n + 1)\n\n for i, range_ in enumerate(ranges):\n l = max(0, i - range_)\n r = min(n, range_ + i)\n nums[l] = max(nums[l], r - l)\n\n ans = 0\n end = 0\n farthest = 0\n\n for i in range(n):\n farthest = max(farthest, i + nums[i])\n if i == end:\n ans += 1\n end = farthest\n\n return ans if end == n else -1\n", | |
| "title": "1326. Minimum Number of Taps to Open to Water a Garden", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1227 | |
| }, | |
| { | |
| "code": "SELECT\n Products.product_name,\n SUM(Orders.unit) AS unit\nFROM Products\nINNER JOIN Orders\n USING (product_id)\nWHERE DATE_FORMAT(Orders.order_date, '%Y-%m') = '2020-02'\nGROUP BY product_id\nHAVING SUM(Orders.unit) >= 100;\n", | |
| "title": "1327. List the Products Ordered in a Period", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1228 | |
| }, | |
| { | |
| "code": "class Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n if len(palindrome) == 1:\n return ''\n\n ans = list(palindrome)\n\n for i in range(len(palindrome) // 2):\n if palindrome[i] != 'a':\n ans[i] = 'a'\n return ''.join(ans)\n\n ans[-1] = 'b'\n return ''.join(ans)\n", | |
| "title": "1328. Break a Palindrome", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1229 | |
| }, | |
| { | |
| "code": "class Solution:\n def diagonalSort(self, mat: list[list[int]]) -> list[list[int]]:\n m = len(mat)\n n = len(mat[0])\n\n count = collections.defaultdict(list)\n\n for i in range(m):\n for j in range(n):\n count[i - j].append(mat[i][j])\n\n for value in count.values():\n value.sort(reverse=1)\n\n for i in range(m):\n for j in range(n):\n mat[i][j] = count[i - j].pop()\n\n return mat\n", | |
| "title": "1329. Sort the Matrix Diagonally", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1230 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxValueAfterReverse(self, nums: list[int]) -> int:\n mn = math.inf\n mx = -math.inf\n\n for a, b in zip(nums, nums[1:]):\n mn = min(mn, max(a, b))\n mx = max(mx, min(a, b))\n diff = max(0, (mx - mn) * 2)\n\n for a, b in zip(nums, nums[1:]):\n headDiff = -abs(a - b) + abs(nums[0] - b)\n tailDiff = -abs(a - b) + abs(nums[-1] - a)\n diff = max(diff, headDiff, tailDiff)\n\n return sum(abs(a - b) for a, b in zip(nums, nums[1:])) + diff\n", | |
| "title": "1330. Reverse Subarray To Maximize Array Value", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1231 | |
| }, | |
| { | |
| "code": "class Solution:\n def arrayRankTransform(self, arr: list[int]) -> list[int]:\n rank = {}\n\n for a in sorted(arr):\n if a not in rank:\n rank[a] = len(rank) + 1\n\n return map(rank.get, arr)\n", | |
| "title": "1331. Rank Transform of an Array", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1232 | |
| }, | |
| { | |
| "code": "class Solution:\n def removePalindromeSub(self, s: str) -> int:\n return 1 if s == s[::-1] else 2\n", | |
| "title": "1332. Remove Palindromic Subsequences", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1233 | |
| }, | |
| { | |
| "code": "class Solution:\n def filterRestaurants(\n self,\n restaurants: list[list[int]],\n veganFriendly: int,\n maxPrice: int,\n maxDistance: int,\n ) -> list[int]:\n restaurants.sort(key=lambda x: (-x[1], -x[0]))\n return [i for i, _, v, p, d in restaurants\n if v >= veganFriendly and p <= maxPrice and d <= maxDistance]\n", | |
| "title": "1333. Filter Restaurants by Vegan-Friendly, Price and Distance", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1234 | |
| }, | |
| { | |
| "code": "class Solution:\n def findTheCity(\n self,\n n: int,\n edges: list[list[int]],\n distanceThreshold: int,\n ) -> int:\n ans = -1\n minCitiesCount = n\n dist = self._floydWarshall(n, edges, distanceThreshold)\n\n for i in range(n):\n citiesCount = sum(dist[i][j] <= distanceThreshold for j in range(n))\n if citiesCount <= minCitiesCount:\n ans = i\n minCitiesCount = citiesCount\n\n return ans\n\n def _floydWarshall(\n self,\n n: int,\n edges: list[list[int]],\n distanceThreshold: int,\n ) -> list[list[int]]:\n dist = [[distanceThreshold + 1] * n for _ in range(n)]\n\n for i in range(n):\n dist[i][i] = 0\n\n for u, v, w in edges:\n dist[u][v] = w\n dist[v][u] = w\n\n for k in range(n):\n for i in range(n):\n for j in range(n):\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n\n return dist\n", | |
| "title": "1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1235 | |
| }, | |
| { | |
| "code": "class Solution:\n def minDifficulty(self, jobDifficulty: list[int], d: int) -> int:\n n = len(jobDifficulty)\n if d > n:\n return -1\n\n # dp[i][k] := the minimum difficulty to schedule the first i jobs in k days\n dp = [[math.inf] * (d + 1) for _ in range(n + 1)]\n dp[0][0] = 0\n\n for i in range(1, n + 1):\n for k in range(1, d + 1):\n maxDifficulty = 0 # max(job[j + 1..i])\n for j in range(i - 1, k - 2, -1): # 1-based\n maxDifficulty = max(maxDifficulty, jobDifficulty[j]) # 0-based\n dp[i][k] = min(dp[i][k], dp[j][k - 1] + maxDifficulty)\n\n return dp[n][d]\n", | |
| "title": "1335. Minimum Difficulty of a Job Schedule", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1236 | |
| }, | |
| { | |
| "code": "WITH\n Users AS (\n SELECT\n Visits.user_id,\n Visits.visit_date,\n COUNT(Transactions.transaction_date) AS transaction_count\n FROM Visits\n LEFT JOIN Transactions\n ON (\n Visits.user_id = Transactions.user_id\n AND Visits.visit_date = Transactions.transaction_date)\n GROUP BY 1, 2\n ),\n RowNumbers AS (\n SELECT ROW_NUMBER() OVER() AS `row_number`\n FROM Transactions\n UNION ALL\n SELECT 0\n )\nSELECT\n RowNumbers.`row_number` AS transactions_count,\n COUNT(Users.user_id) AS visits_count\nFROM RowNumbers\nLEFT JOIN Users\n ON (RowNumbers.`row_number` = Users.transaction_count)\nWHERE RowNumbers.`row_number` <= (\n SELECT MAX(transaction_count) FROM Users\n )\nGROUP BY 1\nORDER BY 1;\n", | |
| "title": "1336. Number of Transactions per Visit", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1237 | |
| }, | |
| { | |
| "code": "class Solution:\n def kWeakestRows(self, mat: list[list[int]], k: int) -> list[int]:\n rowSums = [(sum(row), i) for i, row in enumerate(mat)]\n return [i for _, i in sorted(rowSums)[:k]]\n", | |
| "title": "1337. The K Weakest Rows in a Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1238 | |
| }, | |
| { | |
| "code": "class Solution:\n def minSetSize(self, arr: list[int]) -> int:\n count = collections.Counter(arr).most_common()\n count.sort(key=lambda x: -x[1])\n\n summ = 0\n for i, (_, freq) in enumerate(count):\n summ += freq\n if summ >= len(arr) // 2:\n return i + 1\n", | |
| "title": "1338. Reduce Array Size to The Half", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1239 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxJumps(self, arr: list[int], d: int) -> int:\n n = len(arr)\n # dp[i] := the maximum jumps starting from arr[i]\n dp = [1] * n\n # a dcreasing stack that stores indices\n stack = []\n\n for i in range(n + 1):\n while stack and (i == n or arr[stack[-1]] < arr[i]):\n indices = [stack.pop()]\n while stack and arr[stack[-1]] == arr[indices[0]]:\n indices.append(stack.pop())\n for j in indices:\n if i < n and i - j <= d:\n # Can jump from i to j.\n dp[i] = max(dp[i], dp[j] + 1)\n if stack and j - stack[-1] <= d:\n # Can jump from stack[-1] to j\n dp[stack[-1]] = max(dp[stack[-1]], dp[j] + 1)\n stack.append(i)\n\n return max(dp)\n", | |
| "title": "1340. Jump Game V", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1240 | |
| }, | |
| { | |
| "code": "(\n SELECT Users.name AS results\n FROM MovieRating\n INNER JOIN Users\n USING (user_id)\n GROUP BY user_id\n ORDER BY COUNT(MovieRating.movie_id) DESC, Users.name\n LIMIT 1\n)\nUNION ALL\n(\n SELECT Movies.title AS results\n FROM MovieRating\n INNER JOIN Movies\n USING (movie_id)\n WHERE DATE_FORMAT(created_at, '%Y-%m') = '2020-02'\n GROUP BY movie_id\n ORDER BY AVG(MovieRating.rating) DESC, Movies.title\n LIMIT 1\n);\n", | |
| "title": "1341. Movie Rating", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1241 | |
| }, | |
| { | |
| "code": "class Solution:\n def numberOfSteps(self, num: int) -> int:\n if num == 0:\n return 0\n subtractSteps = num.bit_count()\n divideSteps = num.bit_length() - 1\n return subtractSteps + divideSteps\n", | |
| "title": "1342. Number of Steps to Reduce a Number to Zero", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1242 | |
| }, | |
| { | |
| "code": "class Solution:\n def numOfSubarrays(self, arr: list[int], k: int, threshold: int) -> int:\n ans = 0\n windowSum = 0\n\n for i in range(len(arr)):\n windowSum += arr[i]\n if i >= k:\n windowSum -= arr[i - k]\n if i >= k - 1 and windowSum // k >= threshold:\n ans += 1\n\n return ans\n", | |
| "title": "1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1243 | |
| }, | |
| { | |
| "code": "class Solution:\n def angleClock(self, hour: int, minutes: int) -> float:\n hourAngle = (hour % 12) * 30 + minutes * 0.5\n minuteAngle = minutes * 6\n ans = abs(hourAngle - minuteAngle)\n\n return min(ans, 360 - ans)\n", | |
| "title": "1344. Angle Between Hands of a Clock", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1244 | |
| }, | |
| { | |
| "code": "class Solution:\n def minJumps(self, arr: list[int]) -> int:\n n = len(arr)\n # {num: indices}\n graph = collections.defaultdict(list)\n step = 0\n q = collections.deque([0])\n seen = {0}\n\n for i, a in enumerate(arr):\n graph[a].append(i)\n\n while q:\n for _ in range(len(q)):\n i = q.popleft()\n if i == n - 1:\n return step\n seen.add(i)\n u = arr[i]\n if i + 1 < n:\n graph[u].append(i + 1)\n if i - 1 >= 0:\n graph[u].append(i - 1)\n for v in graph[u]:\n if v in seen:\n continue\n q.append(v)\n graph[u].clear()\n step += 1\n", | |
| "title": "1345. Jump Game IV", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1245 | |
| }, | |
| { | |
| "code": "class Solution:\n def checkIfExist(self, arr: list[int]) -> bool:\n seen = set()\n\n for a in arr:\n if a * 2 in seen or a % 2 == 0 and a // 2 in seen:\n return True\n seen.add(a)\n\n return False\n", | |
| "title": "1346. Check If N and Its Double Exist", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1246 | |
| }, | |
| { | |
| "code": "class Solution:\n def minSteps(self, s: str, t: str) -> int:\n count = collections.Counter(s)\n count.subtract(collections.Counter(t))\n return sum(abs(value) for value in count.values()) // 2\n", | |
| "title": "1347. Minimum Number of Steps to Make Two Strings Anagram", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1247 | |
| }, | |
| { | |
| "code": "from sortedcontainers import SortedList\n\n\nclass TweetCounts:\n def __init__(self):\n self.tweetNameToTimes = collections.defaultdict(SortedList)\n\n def recordTweet(self, tweetName: str, time: int) -> None:\n self.tweetNameToTimes[tweetName].add(time)\n\n def getTweetCountsPerFrequency(self, freq: str, tweetName: str,\n startTime: int, endTime: int) -> list[int]:\n counts = []\n times = self.tweetNameToTimes[tweetName]\n chunk = 60 if freq == 'minute' else 3600 if freq == 'hour' else 86400\n\n # I := startTime of each chunk\n for i in range(startTime, endTime + 1, chunk):\n j = min(i + chunk, endTime + 1) # EndTime of each chunk\n counts.append(bisect_left(times, j) - bisect_left(times, i))\n\n return counts\n", | |
| "title": "1348. Tweet Counts Per Frequency", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1248 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxStudents(self, seats: list[list[str]]) -> int:\n m = len(seats)\n n = len(seats[0])\n DIRS = ((-1, -1), (0, -1), (1, -1), (-1, 1), (0, 1), (1, 1))\n seen = [[0] * n for _ in range(m)]\n match = [[-1] * n for _ in range(m)]\n\n def dfs(i: int, j: int, sessionId: int) -> int:\n for dx, dy in DIRS:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if seats[x][y] != '.' or seen[x][y] == sessionId:\n continue\n seen[x][y] = sessionId\n if match[x][y] == -1 or dfs(*divmod(match[x][y], n), sessionId):\n match[x][y] = i * n + j\n match[i][j] = x * n + y\n return 1\n return 0\n\n def hungarian() -> int:\n count = 0\n for i in range(m):\n for j in range(n):\n if seats[i][j] == '.' and match[i][j] == -1:\n sessionId = i * n + j\n seen[i][j] = sessionId\n count += dfs(i, j, sessionId)\n return count\n\n return sum(seats[i][j] == '.'\n for i in range(m)\n for j in range(n)) - hungarian()\n", | |
| "title": "1349. Maximum Students Taking Exam", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1249 | |
| }, | |
| { | |
| "code": "SELECT\n Students.id,\n Students.name\nFROM Students\nLEFT JOIN Departments\n ON (Students.department_id = Departments.id)\nWHERE Departments.id IS NULL;\n", | |
| "title": "1350. Students With Invalid Departments", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1250 | |
| }, | |
| { | |
| "code": "class Solution:\n def countNegatives(self, grid: list[list[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n ans = 0\n i = m - 1\n j = 0\n\n while i >= 0 and j < n:\n if grid[i][j] < 0:\n ans += n - j\n i -= 1\n else:\n j += 1\n\n return ans\n", | |
| "title": "1351. Count Negative Numbers in a Sorted Matrix", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1251 | |
| }, | |
| { | |
| "code": "class ProductOfNumbers:\n def __init__(self):\n self.prefix = [1]\n\n def add(self, num: int) -> None:\n if num == 0:\n self.prefix = [1]\n else:\n self.prefix.append(self.prefix[-1] * num)\n\n def getProduct(self, k: int) -> int:\n return 0 if k >= len(self.prefix) else self.prefix[-1] // self.prefix[len(self.prefix) - k - 1]\n", | |
| "title": "1352. Product of the Last K Numbers", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1252 | |
| }, | |
| { | |
| "code": "class Solution:\n def maxEvents(self, events: list[list[int]]) -> int:\n ans = 0\n minHeap = []\n i = 0 # events' index\n\n events.sort(key=lambda x: x[0])\n\n while minHeap or i < len(events):\n # If no events are available to attend today, let time flies to the next\n # available event.\n if not minHeap:\n d = events[i][0]\n # All the events starting from today are newly available.\n while i < len(events) and events[i][0] == d:\n heapq.heappush(minHeap, events[i][1])\n i += 1\n # Greedily attend the event that'll end the earliest since it has higher\n # chance can't be attended in the future.\n heapq.heappop(minHeap)\n ans += 1\n d += 1\n # Pop the events that can't be attended.\n while minHeap and minHeap[0] < d:\n heapq.heappop(minHeap)\n\n return ans\n", | |
| "title": "1353. Maximum Number of Events That Can Be Attended", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1253 | |
| }, | |
| { | |
| "code": "class Solution:\n def isPossible(self, target: list[int]) -> bool:\n if len(target) == 1:\n return target[0] == 1\n\n summ = sum(target)\n maxHeap = [-num for num in target]\n heapq.heapify(maxHeap)\n\n while -maxHeap[0] > 1:\n mx = -heapq.heappop(maxHeap)\n restSum = summ - mx\n # Only occurs if n == 2.\n if restSum == 1:\n return True\n updated = mx % restSum\n # updated == 0 (invalid) or didn't change.\n if updated == 0 or updated == mx:\n return False\n heapq.heappush(maxHeap, -updated)\n summ = summ - mx + updated\n\n return True\n", | |
| "title": "1354. Construct Target Array With Multiple Sums", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1254 | |
| }, | |
| { | |
| "code": "WITH\n RankedFriends AS (\n SELECT\n activity,\n RANK() OVER(ORDER BY COUNT(id) ASC) AS rank_asc,\n RANK() OVER(ORDER BY COUNT(id) DESC) AS rank_desc\n FROM Friends\n GROUP BY 1\n )\nSELECT activity\nFROM RankedFriends\nWHERE rank_asc > 1 AND rank_desc > 1;\n", | |
| "title": "1355. Activity Participants", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1255 | |
| }, | |
| { | |
| "code": "class Solution:\n def sortByBits(self, arr: list[int]) -> list[int]:\n return sorted(arr, key=lambda x: (x.bit_count(), x))\n", | |
| "title": "1356. Sort Integers by The Number of 1 Bits", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1256 | |
| }, | |
| { | |
| "code": "class Cashier:\n def __init__(\n self,\n n: int,\n discount: int,\n products: list[int],\n prices: list[int],\n ):\n self.n = n\n self.discount = discount\n self.productToPrice = dict(zip(products, prices))\n self.count = 0\n\n def getBill(self, product: list[int], amount: list[int]) -> float:\n self.count += 1\n total = sum(self.productToPrice[p] * amount[i]\n for i, p in enumerate(product))\n if self.count % self.n == 0:\n return total * (1 - self.discount / 100)\n return total\n", | |
| "title": "1357. Apply Discount Every n Orders", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1257 | |
| }, | |
| { | |
| "code": "class Solution:\n # Similar to 3. Longest SubWithout Repeating Characters\n def numberOfSubstrings(self, s: str) -> int:\n ans = 0\n # lastSeen[c] := the index of the last time c appeared\n lastSeen = {c: -1 for c in 'abc'}\n\n for i, c in enumerate(s):\n lastSeen[c] = i\n # s[0..i], s[1..i], s[min(lastSeen)..i] are satisfied strings.\n ans += 1 + min(lastSeen.values())\n\n return ans\n", | |
| "title": "1358. Number of Substrings Containing All Three Characters", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1258 | |
| }, | |
| { | |
| "code": "class Solution:\n def countOrders(self, n: int) -> int:\n MOD = 1_000_000_007\n ans = 1\n\n for i in range(1, n + 1):\n ans = ans * i * (i * 2 - 1) % MOD\n\n return ans\n", | |
| "title": "1359. Count All Valid Pickup and Delivery Options", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1259 | |
| }, | |
| { | |
| "code": "class Solution:\n def daysBetweenDates(self, date1: str, date2: str) -> int:\n days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\n def isLeapYear(year: int) -> bool:\n return year % 4 == 0 and year % 100 != 0 or year % 400 == 0\n\n def daysFrom1971(date: str) -> int:\n year, month, day = map(int, date.split('-'))\n return (365 * (year - 1971) + sum(map(isLeapYear, range(1971, year))) +\n sum(days[:month]) + day + (month > 2 and isLeapYear(year)))\n\n return abs(daysFrom1971(date1) - daysFrom1971(date2))\n", | |
| "title": "1360. Number of Days Between Two Dates", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1260 | |
| }, | |
| { | |
| "code": "class Solution:\n def closestDivisors(self, num: int) -> list[int]:\n for root in reversed(range(math.isqrt(num + 2) + 1)):\n for cand in [num + 1, num + 2]:\n if cand % root == 0:\n return [root, cand // root]\n", | |
| "title": "1362. Closest Divisors", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1261 | |
| }, | |
| { | |
| "code": "class Solution:\n def largestMultipleOfThree(self, digits: list[int]) -> str:\n ans = ''\n mod1 = [1, 4, 7, 2, 5, 8]\n mod2 = [2, 5, 8, 1, 4, 7]\n count = collections.Counter(digits)\n summ = sum(digits)\n\n while summ % 3 != 0:\n for digit in (mod1 if summ % 3 == 1 else mod2):\n if count[digit]:\n count[digit] -= 1\n summ -= digit\n break\n\n for digit in reversed(range(10)):\n ans += str(digit) * count[digit]\n\n return '0' if len(ans) and ans[0] == '0' else ans\n", | |
| "title": "1363. Largest Multiple of Three", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1262 | |
| }, | |
| { | |
| "code": "SELECT\n Invoices.invoice_id,\n Customers.customer_name,\n Invoices.price,\n COUNT(Contacts.user_id) AS contacts_cnt,\n COUNT(CustomerEmails.email) AS trusted_contacts_cnt\nFROM Invoices\nINNER JOIN Customers\n ON (Invoices.user_id = Customers.customer_id)\nLEFT JOIN Contacts\n ON (Customers.customer_id = Contacts.user_id)\nLEFT JOIN Customers AS CustomerEmails\n ON (Contacts.contact_email = CustomerEmails.email)\nGROUP BY 1\nORDER BY 1;\n", | |
| "title": "1364. Number of Trusted Contacts of a Customer", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1263 | |
| }, | |
| { | |
| "code": "class Solution:\n def smallerNumbersThanCurrent(self, nums: list[int]) -> list[int]:\n MAX = 100\n count = collections.Counter(nums)\n\n for i in range(1, MAX + 1):\n count[i] += count[i - 1]\n\n return [0 if num == 0 else count[num - 1]\n for num in nums]\n", | |
| "title": "1365. How Many Numbers Are Smaller Than the Current Number", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1264 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass\nclass Team:\n name: str\n rank: list[int]\n\n def __init__(self, name: str, teamSize: int):\n self.name = name\n self.rank = [0] * teamSize\n\n\nclass Solution:\n def rankTeams(self, votes: list[str]) -> str:\n teamSize = len(votes[0])\n teams = [Team(chr(ord('A') + i), teamSize) for i in range(26)]\n\n for vote in votes:\n for i in range(teamSize):\n teams[ord(vote[i]) - ord('A')].rank[i] += 1\n\n teams.sort(key=lambda x: (x.rank, -ord(x.name)), reverse=True)\n return ''.join(team.name for team in teams[:teamSize])\n", | |
| "title": "1366. Rank Teams by Votes", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1265 | |
| }, | |
| { | |
| "code": "class Solution:\n def isSubPath(self, head: ListNode | None, root: TreeNode | None) -> bool:\n if not root:\n return False\n return (self._isContinuousSubPath(head, root) or\n self.isSubPath(head, root.left) or\n self.isSubPath(head, root.right))\n\n def _isContinuousSubPath(\n self,\n head: ListNode | None,\n root: TreeNode | None,\n ) -> bool:\n if not head:\n return True\n if not root:\n return False\n return (head.val == root.val and\n (self._isContinuousSubPath(head.next, root.left) or\n self._isContinuousSubPath(head.next, root.right)))\n", | |
| "title": "1367. Linked List in Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1266 | |
| }, | |
| { | |
| "code": "class Solution:\n def minCost(self, grid: list[list[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n DIRS = ((0, 1), (0, -1), (1, 0), (-1, 0))\n dp = [[-1] * n for _ in range(m)]\n q = collections.deque()\n\n def dfs(i: int, j: int, cost: int) -> None:\n if i < 0 or i == m or j < 0 or j == n:\n return\n if dp[i][j] != -1:\n return\n dp[i][j] = cost\n q.append((i, j))\n dx, dy = DIRS[grid[i][j] - 1]\n dfs(i + dx, j + dy, cost)\n\n dfs(0, 0, 0)\n\n cost = 0\n while q:\n cost += 1\n for _ in range(len(q)):\n i, j = q.popleft()\n for dx, dy in DIRS:\n dfs(i + dx, j + dy, cost)\n\n return dp[-1][-1]\n", | |
| "title": "1368. Minimum Cost to Make at Least One Valid Path in a Grid", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1267 | |
| }, | |
| { | |
| "code": "WITH\n RankedUserActivity AS (\n SELECT\n *,\n COUNT(*) OVER(PARTITION BY username) AS `count`,\n RANK() OVER(\n PARTITION BY username\n ORDER BY endDate DESC\n ) AS `rank`\n FROM UserActivity\n )\nSELECT\n username,\n activity,\n startDate,\n endDate\nFROM RankedUserActivity\nWHERE `count` = 1 OR `rank` = 2;\n", | |
| "title": "1369. Get the Second Most Recent Activity", | |
| "notes": "", | |
| "language": "sql", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1268 | |
| }, | |
| { | |
| "code": "class Solution:\n def sortString(self, s: str) -> str:\n ans = []\n count = collections.Counter(s)\n\n while count:\n for chars in string.ascii_lowercase, reversed(string.ascii_lowercase):\n ans += [c for c in chars if c in count]\n count -= dict.fromkeys(count, 1)\n\n return ''.join(ans)\n", | |
| "title": "1370. Increasing Decreasing String", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1269 | |
| }, | |
| { | |
| "code": "class Solution:\n def findTheLongestSubstring(self, s: str) -> int:\n VOWELS = 'aeiou'\n ans = 0\n prefix = 0 # the binary prefix\n prefixToIndex = {0: -1}\n\n for i, c in enumerate(s):\n index = VOWELS.find(c)\n if index != -1:\n prefix ^= 1 << index\n prefixToIndex.setdefault(prefix, i)\n ans = max(ans, i - prefixToIndex[prefix])\n\n return ans\n", | |
| "title": "1371. Find the Longest Substring Containing Vowels in Even Counts", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1270 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass(frozen=True)\nclass T:\n leftMax: int\n rightMax: int\n subtreeMax: int\n\n\nclass Solution:\n def longestZigZag(self, root: TreeNode | None) -> int:\n def dfs(root: TreeNode | None) -> T:\n if not root:\n return T(-1, -1, -1)\n left = dfs(root.left)\n right = dfs(root.right)\n leftZigZag = left.rightMax + 1\n rightZigZag = right.leftMax + 1\n subtreeMax = max(leftZigZag, rightZigZag,\n left.subtreeMax, right.subtreeMax)\n return T(leftZigZag, rightZigZag, subtreeMax)\n\n return dfs(root).subtreeMax\n", | |
| "title": "1372. Longest ZigZag Path in a Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1271 | |
| }, | |
| { | |
| "code": "from dataclasses import dataclass\n\n\n@dataclass\nclass T:\n isBST: bool | None = False\n mx: int | None = None\n mn: int | None = None\n summ: int | None = None\n\n\nclass Solution:\n def maxSumBST(self, root: TreeNode | None) -> int:\n self.ans = 0\n\n def traverse(root: TreeNode | None) -> T:\n if not root:\n return T(True, -math.inf, math.inf, 0)\n\n left: T = traverse(root.left)\n right: T = traverse(root.right)\n\n if not left.isBST or not right.isBST:\n return T()\n if root.val <= left.mx or root.val >= right.mn:\n return T()\n\n # The `root` is a valid BST.\n summ = root.val + left.summ + right.summ\n self.ans = max(self.ans, summ)\n return T(True, max(root.val, right.mx), min(root.val, left.mn), summ)\n\n traverse(root)\n return self.ans\n", | |
| "title": "1373. Maximum Sum BST in Binary Tree", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1272 | |
| }, | |
| { | |
| "code": "class Solution:\n def generateTheString(self, n: int) -> str:\n s = 'a' * n\n if n % 2 == 0:\n s = s[:-1] + 'b'\n return s\n", | |
| "title": "1374. Generate a String With Characters That Have Odd Counts", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1273 | |
| }, | |
| { | |
| "code": "class Solution:\n def numTimesAllBlue(self, flips: list[int]) -> int:\n ans = 0\n rightmost = 0\n\n for i, flip in enumerate(flips):\n rightmost = max(rightmost, flip)\n # max(flips[0..i]) = rightmost = i + 1,\n # so flips[0..i] is a permutation of 1, 2, ..., i + 1.\n if rightmost == i + 1:\n ans += 1\n\n return ans\n", | |
| "title": "1375. Number of Times Binary String Is Prefix-Aligned", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collectionId": 4, | |
| "id": 1274 | |
| }, | |
| { | |
| "code": "class Solution:\n def frogPosition(\n self,\n n: int,\n edges: list[list[int]],\n t: int,\n target: int,\n ) -> float:\n tree = [[] for _ in range(n + 1)]\n q = collections.deque([1])\n seen = [False] * (n + 1)\n prob = [0] * (n + 1)\n\n prob[1] = 1\n seen[1] = True\n\n for u, v in edges:\n tree[u].append(v)\n tree[v].append(u)\n\n for _ in range(t):\n for _ in range(len(q)):\n a = q.popleft()\n nChildren = sum(not seen[b] for b in tree[a])\n for b in tree[a]:\n if seen[b]:\n continue\n seen[b] = True\n prob[b] = prob[a] / nChildren\n q.append(b)\n if nChildren > 0:\n prob[a] = 0\n\n return prob[target]\n", | |
| "title": "1377. Frog Position After T Seconds", | |
| "notes": "", | |
| "language": "python", | |
| "timestamp": 1752218312231, | |
| "isFavorite": false, | |
| "collecti | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment