Upload folder using huggingface_hub (part 13)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- cp/cp-10091.jsonlAdded+4
- cp/cp-10093.jsonlAdded+4
- cp/cp-10094.jsonlAdded+4
- cp/cp-10095.jsonlAdded+4
- cp/cp-10096.jsonlAdded+4
- cp/cp-10098.jsonlAdded+4
- cp/cp-10099.jsonlAdded+4
- cp/cp-10100.jsonlAdded+4
- cp/cp-10101.jsonlAdded+4
- cp/cp-10102.jsonlAdded+4
- cp/cp-10104.jsonlAdded+4
- cp/cp-10105.jsonlAdded+4
- cp/cp-10106.jsonlAdded+4
- cp/cp-10109.jsonlAdded+4
- cp/cp-10112.jsonlAdded+4
- cp/cp-10113.jsonlAdded+4
- cp/cp-10114.jsonlAdded+4
- cp/cp-10115.jsonlAdded+4
- cp/cp-10116.jsonlAdded+4
- cp/cp-10117.jsonlAdded+4
- cp/cp-10119.jsonlAdded+4
- cp/cp-10121.jsonlAdded+4
- cp/cp-10122.jsonlAdded+4
- cp/cp-10123.jsonlAdded+4
- cp/cp-10124.jsonlAdded+4
- cp/cp-10125.jsonlAdded+4
- cp/cp-10126.jsonlAdded+4
- cp/cp-10128.jsonlAdded+4
- cp/cp-10129.jsonlAdded+4
- cp/cp-10130.jsonlAdded+4
- cp/cp-10131.jsonlAdded+4
- cp/cp-10133.jsonlAdded+4
- cp/cp-10134.jsonlAdded+4
- cp/cp-10135.jsonlAdded+4
- cp/cp-10137.jsonlAdded+4
- cp/cp-10138.jsonlAdded+4
- cp/cp-10140.jsonlAdded+4
- cp/cp-10141.jsonlAdded+4
- cp/cp-10143.jsonlAdded+4
- cp/cp-10144.jsonlAdded+4
- cp/cp-10145.jsonlAdded+4
- cp/cp-10146.jsonlAdded+4
- cp/cp-10147.jsonlAdded+4
- cp/cp-10148.jsonlAdded+4
- cp/cp-10149.jsonlAdded+4
- cp/cp-10150.jsonlAdded+4
- cp/cp-10151.jsonlAdded+4
- cp/cp-10152.jsonlAdded+4
- cp/cp-10153.jsonlAdded+4
- cp/cp-10154.jsonlAdded+4
1234{"type": "session", "harness": "opencode", "id": "cp-10091", "name": "LeetCode 0600: Non Negative Integers Without Consecutive Ones"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Non-negative Integers without Consecutive Ones (Difficulty: Hard)\nTags: Dynamic Programming\n\nGiven a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.\n\nExample 1:\nInput: n = 5\nOutput: 5\nExplanation:\nHere are the non-negative integers <= 5 with their corresponding binary representations:\n0 : 0\n1 : 1\n2 : 10\n3 : 11\n4 : 100\n5 : 101\nAmong them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.\n\nExample 2:\nInput: n = 1\nOutput: 2\n\nExample 3:\nInput: n = 2\nOutput: 3\n\nConstraints:\n- 1 <= n <= 10^9"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def findIntegers(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n dp = [0] * 32\n dp[0], dp[1] = 1, 2\n for i in range(2, len(dp)):\n dp[i] = dp[i-1] + dp[i-2]\n result, prev_bit = 0, 0\n for i in reversed(range(31)):\n if (num & (1 << i)) != 0:\n result += dp[i]\n if prev_bit == 1:\n result -= 1\n break\n prev_bit = 1\n else:\n prev_bit = 0\n return result + 1\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10093", "name": "LeetCode 0605: Can Place Flowers"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Can Place Flowers (Difficulty: Easy)\nTags: Array, Greedy\n\nYou have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.\nGiven an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.\n\nExample 1:\nInput: flowerbed = [1,0,0,0,1], n = 1\nOutput: true\n\nExample 2:\nInput: flowerbed = [1,0,0,0,1], n = 2\nOutput: false\n\nConstraints:\n- 1 <= flowerbed.length <= 2 * 10^4\n- flowerbed[i] is 0 or 1.\n- There are no two adjacent flowers in flowerbed.\n- 0 <= n <= flowerbed.length"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def canPlaceFlowers(self, flowerbed, n):\n \"\"\"\n :type flowerbed: List[int]\n :type n: int\n :rtype: bool\n \"\"\"\n for i in range(len(flowerbed)):\n if flowerbed[i] == 0 and (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 return False\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10094", "name": "LeetCode 0606: Construct String From Binary Tree"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Construct String from Binary Tree (Difficulty: Medium)\nTags: String, Tree, Depth-First Search, Binary Tree\n\nGiven the root node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:\n\nExample 1:\nInput: root = [1,2,3,4]\nOutput: \"1(2(4))(3)\"\nExplanation: Originally, it needs to be \"1(2(4)())(3()())\", but you need to omit all the empty parenthesis pairs. And it will be \"1(2(4))(3)\".\n\nExample 2:\nInput: root = [1,2,3,null,4]\nOutput: \"1(2()(4))(3)\"\nExplanation: Almost the same as the first example, except the () after 2 is necessary to indicate the absence of a left child for 2 and the presence of a right child.\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 104].\n- -1000 <= Node.val <= 1000"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nclass Solution(object):\n def tree2str(self, t):\n \"\"\"\n :type t: TreeNode\n :rtype: str\n \"\"\"\n if not t: return \"\"\n s = str(t.val)\n if t.left or t.right:\n s += \"(\" + self.tree2str(t.left) + \")\"\n if t.right:\n s += \"(\" + self.tree2str(t.right) + \")\"\n return s\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10095", "name": "LeetCode 0609: Find Duplicate File In System"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Find Duplicate File in System (Difficulty: Medium)\nTags: Array, Hash Table, String\n\nGiven a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.\nA group of duplicate files consists of at least two files that have the same content.\nA single directory info string in the input list has the following format:\nIt means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory \"root/d1/d2/.../dm\". Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.\nThe output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:\nFollow up:\n\nExample 1:\nInput: paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\",\"root 4.txt(efgh)\"]\nOutput: [[\"root/a/2.txt\",\"root/c/d/4.txt\",\"root/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\n\nExample 2:\nInput: paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\"]\nOutput: [[\"root/a/2.txt\",\"root/c/d/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\n\nConstraints:\n- 1 <= paths.length <= 2 * 10^4\n- 1 <= paths[i].length <= 3000\n- 1 <= sum(paths[i].length) <= 5 * 10^5\n- paths[i] consist of English letters, digits, '/', '.', '(', ')', and ' '.\n- You may assume no files or directories share the same name in the same directory.\n- You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * l), l is the average length of file content\n# Space: O(n * l)\n\nimport collections\n\n\nclass Solution(object):\n def findDuplicate(self, paths):\n \"\"\"\n :type paths: List[str]\n :rtype: List[List[str]]\n \"\"\"\n files = collections.defaultdict(list)\n for path in paths:\n s = path.split(\" \")\n for i in range(1,len(s)):\n file_name = s[0] + \"/\" + s[i][0:s[i].find(\"(\")]\n file_content = s[i][s[i].find(\"(\")+1:s[i].find(\")\")]\n files[file_content].append(file_name)\n\n result = []\n for file_content, file_names in files.iteritems():\n if len(file_names)>1:\n result.append(file_names)\n return result\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10096", "name": "LeetCode 0611: Valid Triangle Number"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Valid Triangle Number (Difficulty: Medium)\nTags: Array, Two Pointers, Binary Search, Greedy, Sorting\n\nGiven an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.\n\nExample 1:\nInput: nums = [2,2,3,4]\nOutput: 3\nExplanation: Valid combinations are: \n2,3,4 (using the first 2)\n2,3,4 (using the second 2)\n2,2,3\n\nExample 2:\nInput: nums = [4,2,3,4]\nOutput: 4\n\nConstraints:\n- 1 <= nums.length <= 1000\n- 0 <= nums[i] <= 1000"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(1)\n\nclass Solution(object):\n def triangleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result = 0\n nums.sort()\n for i in reversed(range(2, len(nums))):\n left, right = 0, i-1\n while left < right:\n if nums[left]+nums[right] > nums[i]:\n result += right-left\n right -= 1\n else:\n left += 1\n return result\n\n\n# Time: O(n^2)\n# Space: O(1)\nclass Solution2(object):\n def triangleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result = 0\n nums.sort()\n for i in range(len(nums)-2):\n if nums[i] == 0:\n continue\n k = i+2\n for j in range(i+1, len(nums)-1):\n while k < len(nums) and nums[i] + nums[j] > nums[k]:\n k += 1\n result += k-j-1\n return result\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10098", "name": "LeetCode 0617: Merge Two Binary Trees"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Merge Two Binary Trees (Difficulty: Easy)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nYou are given two binary trees root1 and root2.\nImagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.\nReturn the merged tree.\nNote: The merging process must start from the root nodes of both trees.\n\nExample 1:\nInput: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]\nOutput: [3,4,5,5,4,null,7]\n\nExample 2:\nInput: root1 = [1], root2 = [1,2]\nOutput: [2,2]\n\nConstraints:\n- The number of nodes in both trees is in the range [0, 2000].\n- -10^4 <= Node.val <= 10^4"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nclass Solution(object):\n def mergeTrees(self, t1, t2):\n \"\"\"\n :type t1: TreeNode\n :type t2: TreeNode\n :rtype: TreeNode\n \"\"\"\n if t1 is None:\n return t2\n if t2 is None:\n return t1\n t1.val += t2.val\n t1.left = self.mergeTrees(t1.left, t2.left)\n t1.right = self.mergeTrees(t1.right, t2.right)\n return t1\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10099", "name": "LeetCode 0621: Task Scheduler"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Task Scheduler (Difficulty: Medium)\nTags: Array, Hash Table, Greedy, Sorting, Heap (Priority Queue), Counting\n\nYou are given an array of CPU tasks, each labeled with a letter from A to Z, and a number n. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there's a constraint: there has to be a gap of at least n intervals between two tasks with the same label.\nReturn the minimum number of CPU intervals required to complete all tasks.\n\nExample 1:\nInput: tasks = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 2\nOutput: 8\nExplanation: A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B.\nAfter completing task A, you must wait two intervals before doing A again. The same applies to task B. In the 3 rd interval, neither A nor B can be done, so you idle. By the 4 th interval, you can do A again as 2 intervals have passed.\n\nExample 2:\nInput: tasks = [\"A\",\"C\",\"A\",\"B\",\"D\",\"B\"], n = 1\nOutput: 6\nExplanation: A possible sequence is: A -> B -> C -> D -> A -> B.\nWith a cooling interval of 1, you can repeat a task after just one other task.\n\nExample 3:\nInput: tasks = [\"A\",\"A\",\"A\", \"B\",\"B\",\"B\"], n = 3\nOutput: 10\nExplanation: A possible sequence is: A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B.\nThere are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.\n\nConstraints:\n- 1 <= tasks.length <= 10^4\n- tasks[i] is an uppercase English letter.\n- 0 <= n <= 100"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(26) = O(1)\n\nfrom collections import Counter\n\n\nclass Solution(object):\n def leastInterval(self, tasks, n):\n \"\"\"\n :type tasks: List[str]\n :type n: int\n :rtype: int\n \"\"\"\n counter = Counter(tasks)\n _, max_count = counter.most_common(1)[0]\n return max((max_count-1) * (n+1) + counter.values().count(max_count), len(tasks))\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10100", "name": "LeetCode 0622: Design Circular Queue"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Design Circular Queue (Difficulty: Medium)\nTags: Array, Linked List, Design, Queue\n\nDesign your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called \"Ring Buffer\".\nOne of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.\nImplement the MyCircularQueue class:\nYou must solve the problem without using the built-in queue data structure in your programming language.\n\nExample 1:\nInput\n[\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]\nOutput\n[null, true, true, true, false, 3, true, true, true, 4]\n\nExplanation\nMyCircularQueue myCircularQueue = new MyCircularQueue(3);\nmyCircularQueue.enQueue(1); // return True\nmyCircularQueue.enQueue(2); // return True\nmyCircularQueue.enQueue(3); // return True\nmyCircularQueue.enQueue(4); // return False\nmyCircularQueue.Rear(); // return 3\nmyCircularQueue.isFull(); // return True\nmyCircularQueue.deQueue(); // return True\nmyCircularQueue.enQueue(4); // return True\nmyCircularQueue.Rear(); // return 4\n\nConstraints:\n- 1 <= k <= 1000\n- 0 <= value <= 1000\n- At most 3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(k)\n\nclass MyCircularQueue(object):\n\n def __init__(self, k):\n \"\"\"\n Initialize your data structure here. Set the size of the queue to be k.\n :type k: int\n \"\"\"\n self.__start = 0\n self.__size = 0\n self.__buffer = [0] * k\n\n def enQueue(self, value):\n \"\"\"\n Insert an element into the circular queue. Return true if the operation is successful.\n :type value: int\n :rtype: bool\n \"\"\"\n if self.isFull():\n return False\n self.__buffer[(self.__start+self.__size) % len(self.__buffer)] = value\n self.__size += 1\n return True\n\n def deQueue(self):\n \"\"\"\n Delete an element from the circular queue. Return true if the operation is successful.\n :rtype: bool\n \"\"\"\n if self.isEmpty():\n return False\n self.__start = (self.__start+1) % len(self.__buffer)\n self.__size -= 1\n return True\n\n def Front(self):\n \"\"\"\n Get the front item from the queue.\n :rtype: int\n \"\"\"\n return -1 if self.isEmpty() else self.__buffer[self.__start]\n\n def Rear(self):\n \"\"\"\n Get the last item from the queue.\n :rtype: int\n \"\"\"\n return -1 if self.isEmpty() else self.__buffer[(self.__start+self.__size-1) % len(self.__buffer)]\n\n def isEmpty(self):\n \"\"\"\n Checks whether the circular queue is empty or not.\n :rtype: bool\n \"\"\"\n return self.__size == 0\n\n def isFull(self):\n \"\"\"\n Checks whether the circular queue is full or not.\n :rtype: bool\n \"\"\"\n return self.__size == len(self.__buffer)\n\n\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10101", "name": "LeetCode 0623: Add One Row To Tree"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Add One Row to Tree (Difficulty: Medium)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.\nNote that the root node is at depth 1.\nThe adding rule is:\n\nExample 1:\nInput: root = [4,2,6,3,1,5], val = 1, depth = 2\nOutput: [4,1,1,2,null,null,6,3,1,5]\n\nExample 2:\nInput: root = [4,2,null,3,1], val = 1, depth = 3\nOutput: [4,2,null,1,1,3,null,null,1]\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 104].\n- The depth of the tree is in the range [1, 104].\n- -100 <= Node.val <= 100\n- -10^5 <= val <= 10^5\n- 1 <= depth <= the depth of tree + 1"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def addOneRow(self, root, v, d):\n \"\"\"\n :type root: TreeNode\n :type v: int\n :type d: int\n :rtype: TreeNode\n \"\"\"\n if d in (0, 1):\n node = TreeNode(v)\n if d == 1:\n node.left = root\n else:\n node.right = root\n return node\n if root and d >= 2:\n root.left = self.addOneRow(root.left, v, d-1 if d > 2 else 1)\n root.right = self.addOneRow(root.right, v, d-1 if d > 2 else 0)\n return root\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10102", "name": "LeetCode 0624: Maximum Distance In Arrays"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Maximum Distance in Arrays (Difficulty: Medium)\nTags: Array, Greedy\n\nYou are given m arrays, where each array is sorted in ascending order.\nYou can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their absolute difference |a - b|.\nReturn the maximum distance.\n\nExample 1:\nInput: arrays = [[1,2,3],[4,5],[1,2,3]]\nOutput: 4\nExplanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.\n\nExample 2:\nInput: arrays = [[1],[1]]\nOutput: 0\n\nConstraints:\n- m == arrays.length\n- 2 <= m <= 10^5\n- 1 <= arrays[i].length <= 500\n- -10^4 <= arrays[i][j] <= 10^4\n- arrays[i] is sorted in ascending order.\n- There will be at most 105 integers in all the arrays."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxDistance(self, arrays):\n \"\"\"\n :type arrays: List[List[int]]\n :rtype: int\n \"\"\"\n result, min_val, max_val = 0, arrays[0][0], arrays[0][-1]\n for i in range(1, len(arrays)):\n result = max(result, \\\n max(max_val - arrays[i][0], \\\n arrays[i][-1] - min_val))\n min_val = min(min_val, arrays[i][0])\n max_val = max(max_val, arrays[i][-1])\n return result\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10104", "name": "LeetCode 0628: Maximum Product Of Three Numbers"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Maximum Product of Three Numbers (Difficulty: Easy)\nTags: Array, Math, Sorting\n\nGiven an integer array nums, find three numbers whose product is maximum and return the maximum product.\n\nExample 1:\nInput: nums = [1,2,3]\nOutput: 6\n\nExample 2:\nInput: nums = [1,2,3,4]\nOutput: 24\n\nExample 3:\nInput: nums = [-1,-2,-3]\nOutput: -6\n\nConstraints:\n- 3 <= nums.length <= 10^4\n- -1000 <= nums[i] <= 1000"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maximumProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n min1, min2 = float(\"inf\"), float(\"inf\")\n max1, max2, max3 = float(\"-inf\"), float(\"-inf\"), float(\"-inf\")\n\n for n in nums:\n if n <= min1:\n min2 = min1\n min1 = n\n elif n <= min2:\n min2 = n\n\n if n >= max1:\n max3 = max2\n max2 = max1\n max1 = n\n elif n >= max2:\n max3 = max2\n max2 = n\n elif n >= max3:\n max3 = n\n\n return max(min1 * min2 * max1, max1 * max2 * max3)\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10105", "name": "LeetCode 0629: K Inverse Pairs Array"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: K Inverse Pairs Array (Difficulty: Hard)\nTags: Dynamic Programming\n\nFor an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j].\nGiven two integers n and k, return the number of different arrays consisting of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 109 + 7.\n\nExample 1:\nInput: n = 3, k = 0\nOutput: 1\nExplanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.\n\nExample 2:\nInput: n = 3, k = 1\nOutput: 2\nExplanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.\n\nConstraints:\n- 1 <= n <= 1000\n- 0 <= k <= 1000"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * k)\n# Space: O(k)\n\n# knapsack dp, combinatorics, sliding window, two pointers\nclass Solution(object):\n def kInversePairs(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n dp = [1]\n for i in range(n):\n new_dp = [0]*min(len(dp)+((i+1)-1), k+1)\n for j in range(len(new_dp)):\n new_dp[j] = dp[j] if j < len(dp) else 0\n if j-1 >= 0:\n new_dp[j] = (new_dp[j]+new_dp[j-1])%MOD\n if j-(i+1) >= 0:\n new_dp[j] = (new_dp[j]-dp[j-(i+1)])%MOD\n dp = new_dp\n return dp[k] if k < len(dp) else 0\n\n\n# Time: O(n * k)\n# Space: O(k)\n# knapsack dp, combinatorics, sliding window, two pointers\nclass Solution2(object):\n def kInversePairs(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n dp = [0]*(k+1)\n dp[0] = 1\n for i in range(n):\n new_dp = [0]*len(dp)\n for j in range(len(dp)):\n new_dp[j] = dp[j]\n if j-1 >= 0:\n new_dp[j] = (new_dp[j]+new_dp[j-1])%MOD\n if j-(i+1) >= 0:\n new_dp[j] = (new_dp[j]-dp[j-(i+1)])%MOD\n dp = new_dp\n return dp[-1]\n\n\n# Time: O(n * k)\n# Space: O(k)\n# knapsack dp, combinatorics, sliding window, two pointers\nclass Solution3(object):\n def kInversePairs(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n dp = [0]*(k+1)\n dp[0] = 1\n for i in range(n):\n new_dp = [0]*len(dp)\n curr = 0\n for j in range(len(dp)):\n curr = (curr+dp[j])%MOD\n if j-(i+1) >= 0:\n curr = (curr-dp[j-(i+1)])%MOD\n new_dp[j] = curr\n dp = new_dp\n return dp[-1]\n\n\n# Time: O(n^2 * k)\n# Space: O(k)\n# knapsack dp, combinatorics\nclass Solution_TLE(object):\n def kInversePairs(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n dp = [0]*(k+1)\n dp[0] = 1\n for i in range(n):\n dp = [reduce(lambda total, k: (total+dp[j-k])%MOD, range(min(i+1, j+1)), 0) for j in range(len(dp))]\n return dp[-1]%MOD\n\n\nclass Solution_ConstructPermutation(object):\n def kInversePairs(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n dp = [[] for _ in range(k+1)]\n dp[0].append([])\n for i in range(n):\n dp = [[[x+int(x >= i-k) for x in p]+[i-k] for k in range(min(i+1, j+1)) for p in dp[j-k]] for j in range(len(dp))]\n assert(all(sum(int(p[j] > p[i]) for i in range(n) for j in range(i)) == len(dp)-1) for p in dp[-1])\n return len(dp[-1])%MOD\n\n\nclass Solution_ConstructPermutation2(object):\n def kInversePairs(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n dp = [[] for _ in range(k+1)]\n dp[0].append([])\n for i in range(n):\n dp = [[p[:len(p)-k]+[i]+p[len(p)-k:] for k in range(min(i+1, j+1)) for p in dp[j-k]] for j in range(len(dp))]\n assert(all(sum(int(p[j] > p[i]) for i in range(n) for j in range(i)) == len(dp)-1) for p in dp[-1])\n return len(dp[-1])%MOD\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10106", "name": "LeetCode 0630: Course Schedule Iii"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Course Schedule III (Difficulty: Hard)\nTags: Array, Greedy, Sorting, Heap (Priority Queue)\n\nThere are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi.\nYou will start on the 1st day and you cannot take two or more courses simultaneously.\nReturn the maximum number of courses that you can take.\n\nExample 1:\nInput: courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]\nOutput: 3\nExplanation: \nThere are totally 4 courses, but you can take 3 courses at most:\nFirst, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.\nSecond, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. \nThird, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. \nThe 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.\n\nExample 2:\nInput: courses = [[1,2]]\nOutput: 1\n\nExample 3:\nInput: courses = [[3,2],[4,3]]\nOutput: 0\n\nConstraints:\n- 1 <= courses.length <= 10^4\n- 1 <= durationi, lastDayi <= 10^4"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(k), k is the number of courses you can take\n\nimport collections\nimport heapq\n\n\nclass Solution(object):\n def scheduleCourse(self, courses):\n \"\"\"\n :type courses: List[List[int]]\n :rtype: int\n \"\"\"\n courses.sort(key=lambda t_end: t_end[1])\n max_heap = []\n now = 0\n for t, end in courses:\n now += t\n heapq.heappush(max_heap, -t)\n if now > end:\n now += heapq.heappop(max_heap)\n return len(max_heap)\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10109", "name": "LeetCode 0633: Sum Of Square Numbers"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Sum of Square Numbers (Difficulty: Medium)\nTags: Math, Two Pointers, Binary Search\n\nGiven a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.\n\nExample 1:\nInput: c = 5\nOutput: true\nExplanation: 1 * 1 + 2 * 2 = 5\n\nExample 2:\nInput: c = 3\nOutput: false\n\nConstraints:\n- 0 <= c <= 2^31 - 1"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(sqrt(c) * logc)\n# Space: O(1)\n\nimport math\n\n\nclass Solution(object):\n def judgeSquareSum(self, c):\n \"\"\"\n :type c: int\n :rtype: bool\n \"\"\"\n for a in range(int(math.sqrt(c))+1):\n b = int(math.sqrt(c-a**2))\n if a**2 + b**2 == c:\n return True\n return False\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10112", "name": "LeetCode 0636: Exclusive Time Of Functions"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Exclusive Time of Functions (Difficulty: Medium)\nTags: Array, Stack\n\nOn a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1.\nFunction calls are stored in a call stack: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.\nYou are given a list logs, where logs[i] represents the ith log message formatted as a string \"{function_id}:{\"start\" | \"end\"}:{timestamp}\". For example, \"0:start:3\" means a function call with function ID 0 started at the beginning of timestamp 3, and \"1:end:2\" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times, possibly recursively.\nA function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3.\nReturn the exclusive time of each function in an array, where the value at the ith index represents the exclusive time for the function with ID i.\n\nExample 1:\nInput: n = 2, logs = [\"0:start:0\",\"1:start:2\",\"1:end:5\",\"0:end:6\"]\nOutput: [3,4]\nExplanation:\nFunction 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.\nFunction 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.\nFunction 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.\nSo function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.\n\nExample 2:\nInput: n = 1, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"0:start:6\",\"0:end:6\",\"0:end:7\"]\nOutput: [8]\nExplanation:\nFunction 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls itself again.\nFunction 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.\nFunction 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.\nSo function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.\n\nExample 3:\nInput: n = 2, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"1:start:6\",\"1:end:6\",\"0:end:7\"]\nOutput: [7,1]\nExplanation:\nFunction 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls function 1.\nFunction 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6.\nFunction 0 resumes execution at the beginning of time 6 and executes for 2 units of time.\nSo function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.\n\nConstraints:\n- 1 <= n <= 100\n- 2 <= logs.length <= 500\n- 0 <= function_id < n\n- 0 <= timestamp <= 10^9\n- No two start events will happen at the same timestamp.\n- No two end events will happen at the same timestamp.\n- Each function has an \"end\" log for each \"start\" log."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def exclusiveTime(self, n, logs):\n \"\"\"\n :type n: int\n :type logs: List[str]\n :rtype: List[int]\n \"\"\"\n result = [0] * n\n stk, prev = [], 0\n for log in logs:\n tokens = log.split(\":\")\n if tokens[1] == \"start\":\n if stk:\n result[stk[-1]] += int(tokens[2]) - prev\n stk.append(int(tokens[0]))\n prev = int(tokens[2])\n else:\n result[stk.pop()] += int(tokens[2]) - prev + 1\n prev = int(tokens[2]) + 1\n return result\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10113", "name": "LeetCode 0637: Average Of Levels In Binary Tree"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Average of Levels in Binary Tree (Difficulty: Easy)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nExample 1:\nInput: root = [3,9,20,null,null,15,7]\nOutput: [3.00000,14.50000,11.00000]\nExplanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.\nHence return [3, 14.5, 11].\n\nExample 2:\nInput: root = [3,9,20,15,7]\nOutput: [3.00000,14.50000,11.00000]\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 104].\n- -2^31 <= Node.val <= 2^31 - 1"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n\nclass Solution(object):\n def averageOfLevels(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[float]\n \"\"\"\n result = []\n q = [root]\n while q:\n total, count = 0, 0\n next_q = []\n for n in q:\n total += n.val\n count += 1\n if n.left:\n next_q.append(n.left)\n if n.right:\n next_q.append(n.right)\n q = next_q\n result.append(float(total) / count)\n return result\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10114", "name": "LeetCode 0638: Shopping Offers"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Shopping Offers (Difficulty: Medium)\nTags: Array, Dynamic Programming, Backtracking, Bit Manipulation, Memoization, Bitmask\n\nIn LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.\nYou are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy.\nYou are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer.\nReturn the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.\n\nExample 1:\nInput: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]\nOutput: 14\nExplanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively. \nIn special offer 1, you can pay $5 for 3A and 0B\nIn special offer 2, you can pay $10 for 1A and 2B. \nYou need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.\n\nExample 2:\nInput: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]\nOutput: 11\nExplanation: The price of A is $2, and $3 for B, $4 for C. \nYou may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. \nYou need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. \nYou cannot add more items, though only $9 for 2A ,2B and 1C.\n\nConstraints:\n- n == price.length == needs.length\n- 1 <= n <= 6\n- 0 <= price[i], needs[i] <= 10\n- 1 <= special.length <= 100\n- special[i].length == n + 1\n- 0 <= special[i][j] <= 50\n- The input is generated that at least one of special[i][j] is non-zero for 0 <= j <= n - 1."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * 2^n)\n# Space: O(n)\n\nclass Solution(object):\n def shoppingOffers(self, price, special, needs):\n \"\"\"\n :type price: List[int]\n :type special: List[List[int]]\n :type needs: List[int]\n :rtype: int\n \"\"\"\n def shoppingOffersHelper(price, special, needs, i):\n if i == len(special):\n return sum(map(lambda x, y: x*y, price, needs))\n result = shoppingOffersHelper(price, special, needs, i+1)\n for j in range(len(needs)):\n needs[j] -= special[i][j]\n if all(need >= 0 for need in needs):\n result = min(result, special[i][-1] + shoppingOffersHelper(price, special, needs, i))\n for j in range(len(needs)):\n needs[j] += special[i][j]\n return result\n\n return shoppingOffersHelper(price, special, needs, 0)\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10115", "name": "LeetCode 0639: Decode Ways Ii"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Decode Ways II (Difficulty: Hard)\nTags: String, Dynamic Programming\n\nA message containing letters from A-Z can be encoded into numbers using the following mapping:\nTo decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into:\nNote that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\".\nIn addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message \"1*\" may represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\". Decoding \"1*\" is equivalent to decoding any of the encoded messages it can represent.\nGiven a string s consisting of digits and '*' characters, return the number of ways to decode it.\nSince the answer may be very large, return it modulo 109 + 7.\n\nExample 1:\n'A' -> \"1\"\n'B' -> \"2\"\n...\n'Z' -> \"26\"\n\nExample 2:\nInput: s = \"*\"\nOutput: 9\nExplanation: The encoded message can represent any of the encoded messages \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", or \"9\".\nEach of these can be decoded to the strings \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", and \"I\" respectively.\nHence, there are a total of 9 ways to decode \"*\".\n\nExample 3:\nInput: s = \"1*\"\nOutput: 18\nExplanation: The encoded message can represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\".\nEach of these encoded messages have 2 ways to be decoded (e.g. \"11\" can be decoded to \"AA\" or \"K\").\nHence, there are a total of 9 * 2 = 18 ways to decode \"1*\".\n\nExample 4:\nInput: s = \"2*\"\nOutput: 15\nExplanation: The encoded message can represent any of the encoded messages \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", or \"29\".\n\"21\", \"22\", \"23\", \"24\", \"25\", and \"26\" have 2 ways of being decoded, but \"27\", \"28\", and \"29\" only have 1 way.\nHence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode \"2*\".\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s[i] is a digit or '*'."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def numDecodings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n M, W = 1000000007, 3\n dp = [0] * W\n dp[0] = 1\n dp[1] = 9 if s[0] == '*' else dp[0] if s[0] != '0' else 0\n for i in range(1, len(s)):\n if s[i] == '*':\n dp[(i + 1) % W] = 9 * dp[i % W]\n if s[i - 1] == '1':\n dp[(i + 1) % W] = (dp[(i + 1) % W] + 9 * dp[(i - 1) % W]) % M\n elif s[i - 1] == '2':\n dp[(i + 1) % W] = (dp[(i + 1) % W] + 6 * dp[(i - 1) % W]) % M\n elif s[i - 1] == '*':\n dp[(i + 1) % W] = (dp[(i + 1) % W] + 15 * dp[(i - 1) % W]) % M\n else:\n dp[(i + 1) % W] = dp[i % W] if s[i] != '0' else 0\n if s[i - 1] == '1':\n dp[(i + 1) % W] = (dp[(i + 1) % W] + dp[(i - 1) % W]) % M\n elif s[i - 1] == '2' and s[i] <= '6':\n dp[(i + 1) % W] = (dp[(i + 1) % W] + dp[(i - 1) % W]) % M\n elif s[i - 1] == '*':\n dp[(i + 1) % W] = (dp[(i + 1) % W] + (2 if s[i] <= '6' else 1) * dp[(i - 1) % W]) % M\n return dp[len(s) % W]\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10116", "name": "LeetCode 0640: Solve The Equation"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Solve the Equation (Difficulty: Medium)\nTags: Math, String, Simulation\n\nSolve a given equation and return the value of 'x' in the form of a string \"x=#value\". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return \"No solution\" if there is no solution for the equation, or \"Infinite solutions\" if there are infinite solutions for the equation.\nIf there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.\n\nExample 1:\nInput: equation = \"x+5-3+x=6+x-2\"\nOutput: \"x=2\"\n\nExample 2:\nInput: equation = \"x=x\"\nOutput: \"Infinite solutions\"\n\nExample 3:\nInput: equation = \"2x=x\"\nOutput: \"x=0\"\n\nConstraints:\n- 3 <= equation.length <= 1000\n- equation has exactly one '='.\n- equation consists of integers with an absolute value in the range [0, 100] without any leading zeros, and the variable 'x'.\n- The input is generated that if there is a single solution, it will be an integer."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport re\n\n\nclass Solution(object):\n def solveEquation(self, equation):\n \"\"\"\n :type equation: str\n :rtype: str\n \"\"\"\n a, b, side = 0, 0, 1\n for eq, sign, num, isx in re.findall('(=)|([-+]?)(\\d*)(x?)', equation):\n if eq:\n side = -1\n elif isx:\n a += side * int(sign + '1') * int(num or 1)\n elif num:\n b -= side * int(sign + num)\n return 'x=%d' % (b / a) if a else 'No solution' if b else 'Infinite solutions'\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10117", "name": "LeetCode 0641: Design Circular Deque"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Design Circular Deque (Difficulty: Medium)\nTags: Array, Linked List, Design, Queue\n\nDesign your implementation of the circular double-ended queue (deque).\nImplement the MyCircularDeque class:\n\nExample 1:\nInput\n[\"MyCircularDeque\", \"insertLast\", \"insertLast\", \"insertFront\", \"insertFront\", \"getRear\", \"isFull\", \"deleteLast\", \"insertFront\", \"getFront\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]\nOutput\n[null, true, true, true, false, 2, true, true, true, 4]\n\nExplanation\nMyCircularDeque myCircularDeque = new MyCircularDeque(3);\nmyCircularDeque.insertLast(1); // return True\nmyCircularDeque.insertLast(2); // return True\nmyCircularDeque.insertFront(3); // return True\nmyCircularDeque.insertFront(4); // return False, the queue is full.\nmyCircularDeque.getRear(); // return 2\nmyCircularDeque.isFull(); // return True\nmyCircularDeque.deleteLast(); // return True\nmyCircularDeque.insertFront(4); // return True\nmyCircularDeque.getFront(); // return 4\n\nConstraints:\n- 1 <= k <= 1000\n- 0 <= value <= 1000\n- At most 2000 calls will be made to insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty, isFull."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(k)\n\nclass MyCircularDeque(object):\n\n def __init__(self, k):\n \"\"\"\n Initialize your data structure here. Set the size of the deque to be k.\n :type k: int\n \"\"\"\n self.__start = 0\n self.__size = 0\n self.__buffer = [0] * k\n\n def insertFront(self, value):\n \"\"\"\n Adds an item at the front of Deque. Return true if the operation is successful.\n :type value: int\n :rtype: bool\n \"\"\"\n if self.isFull():\n return False\n self.__start = (self.__start-1) % len(self.__buffer)\n self.__buffer[self.__start] = value\n self.__size += 1\n return True\n\n def insertLast(self, value):\n \"\"\"\n Adds an item at the rear of Deque. Return true if the operation is successful.\n :type value: int\n :rtype: bool\n \"\"\"\n if self.isFull():\n return False\n self.__buffer[(self.__start+self.__size) % len(self.__buffer)] = value\n self.__size += 1\n return True\n\n def deleteFront(self):\n \"\"\"\n Deletes an item from the front of Deque. Return true if the operation is successful.\n :rtype: bool\n \"\"\"\n if self.isEmpty():\n return False\n self.__start = (self.__start+1) % len(self.__buffer)\n self.__size -= 1\n return True\n\n def deleteLast(self):\n \"\"\"\n Deletes an item from the rear of Deque. Return true if the operation is successful.\n :rtype: bool\n \"\"\"\n if self.isEmpty():\n return False\n self.__size -= 1\n return True\n\n def getFront(self):\n \"\"\"\n Get the front item from the deque.\n :rtype: int\n \"\"\"\n return -1 if self.isEmpty() else self.__buffer[self.__start]\n\n def getRear(self):\n \"\"\"\n Get the last item from the deque.\n :rtype: int\n \"\"\"\n return -1 if self.isEmpty() else self.__buffer[(self.__start+self.__size-1) % len(self.__buffer)]\n\n def isEmpty(self):\n \"\"\"\n Checks whether the circular deque is empty or not.\n :rtype: bool\n \"\"\"\n return self.__size == 0\n\n def isFull(self):\n \"\"\"\n Checks whether the circular deque is full or not.\n :rtype: bool\n \"\"\"\n return self.__size == len(self.__buffer)\n\n\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10119", "name": "LeetCode 0643: Maximum Average Subarray I"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Maximum Average Subarray I (Difficulty: Easy)\nTags: Array, Sliding Window\n\nYou are given an integer array nums consisting of n elements, and an integer k.\nFind a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted.\n\nExample 1:\nInput: nums = [1,12,-5,-6,50,3], k = 4\nOutput: 12.75000\nExplanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75\n\nExample 2:\nInput: nums = [5], k = 1\nOutput: 5.00000\n\nConstraints:\n- n == nums.length\n- 1 <= k <= n <= 10^5\n- -10^4 <= nums[i] <= 10^4"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def findMaxAverage(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: float\n \"\"\"\n result = total = sum(nums[:k])\n for i in range(k, len(nums)):\n total += nums[i] - nums[i-k]\n result = max(result, total)\n return float(result) / k\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10121", "name": "LeetCode 0645: Set Mismatch"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Set Mismatch (Difficulty: Easy)\nTags: Array, Hash Table, Bit Manipulation, Sorting\n\nYou have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.\nYou are given an integer array nums representing the data status of this set after the error.\nFind the number that occurs twice and the number that is missing and return them in the form of an array.\n\nExample 1:\nInput: nums = [1,2,2,4]\nOutput: [2,3]\n\nExample 2:\nInput: nums = [1,1]\nOutput: [1,2]\n\nConstraints:\n- 2 <= nums.length <= 10^4\n- 1 <= nums[i] <= 10^4"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def findErrorNums(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n x_xor_y = 0\n for i in range(len(nums)):\n x_xor_y ^= nums[i] ^ (i+1)\n bit = x_xor_y & ~(x_xor_y-1)\n result = [0] * 2\n for i, num in enumerate(nums):\n result[bool(num & bit)] ^= num\n result[bool((i+1) & bit)] ^= i+1\n if result[0] not in nums:\n result[0], result[1] = result[1], result[0]\n return result\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def findErrorNums(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n result = [0] * 2\n for i in nums:\n if nums[abs(i)-1] < 0:\n result[0] = abs(i)\n else:\n nums[abs(i)-1] *= -1\n for i in range(len(nums)):\n if nums[i] > 0:\n result[1] = i+1\n else:\n nums[i] *= -1\n return result\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution3(object):\n def findErrorNums(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n N = len(nums)\n x_minus_y = sum(nums) - N*(N+1)//2\n x_plus_y = (sum(x*x for x in nums) - N*(N+1)*(2*N+1)/6) // x_minus_y\n return (x_plus_y+x_minus_y) // 2, (x_plus_y-x_minus_y) // 2\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10122", "name": "LeetCode 0646: Maximum Length Of Pair Chain"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Maximum Length of Pair Chain (Difficulty: Medium)\nTags: Array, Dynamic Programming, Greedy, Sorting\n\nYou are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.\nA pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.\nReturn the length longest chain which can be formed.\nYou do not need to use up all the given intervals. You can select pairs in any order.\n\nExample 1:\nInput: pairs = [[1,2],[2,3],[3,4]]\nOutput: 2\nExplanation: The longest chain is [1,2] -> [3,4].\n\nExample 2:\nInput: pairs = [[1,2],[7,8],[4,5]]\nOutput: 3\nExplanation: The longest chain is [1,2] -> [4,5] -> [7,8].\n\nConstraints:\n- n == pairs.length\n- 1 <= n <= 1000\n- -1000 <= lefti < righti <= 1000"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def findLongestChain(self, pairs):\n \"\"\"\n :type pairs: List[List[int]]\n :rtype: int\n \"\"\"\n pairs.sort(key=lambda x: x[1])\n cnt, i = 0, 0\n for j in range(len(pairs)):\n if j == 0 or pairs[i][1] < pairs[j][0]:\n cnt += 1\n i = j\n return cnt\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10123", "name": "LeetCode 0647: Palindromic Substrings"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Palindromic Substrings (Difficulty: Medium)\nTags: Two Pointers, String, Dynamic Programming\n\nGiven a string s, return the number of palindromic substrings in it.\nA string is a palindrome when it reads the same backward as forward.\nA substring is a contiguous sequence of characters within the string.\n\nExample 1:\nInput: s = \"abc\"\nOutput: 3\nExplanation: Three palindromic strings: \"a\", \"b\", \"c\".\n\nExample 2:\nInput: s = \"aaa\"\nOutput: 6\nExplanation: Six palindromic strings: \"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\".\n\nConstraints:\n- 1 <= s.length <= 1000\n- s consists of lowercase English letters."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def countSubstrings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n def manacher(s):\n s = '^#' + '#'.join(s) + '#$'\n P = [0] * len(s)\n C, R = 0, 0\n for i in range(1, len(s) - 1):\n i_mirror = 2*C-i\n if R > i:\n P[i] = min(R-i, P[i_mirror])\n while s[i+1+P[i]] == s[i-1-P[i]]:\n P[i] += 1\n if i+P[i] > R:\n C, R = i, i+P[i]\n return P\n return sum((max_len+1)//2 for max_len in manacher(s))\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10124", "name": "LeetCode 0648: Replace Words"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Replace Words (Difficulty: Medium)\nTags: Array, Hash Table, String, Trie\n\nIn English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word derivative. For example, when the root \"help\" is followed by the word \"ful\", we can form a derivative \"helpful\".\nGiven a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length.\nReturn the sentence after the replacement.\n\nExample 1:\nInput: dictionary = [\"cat\",\"bat\",\"rat\"], sentence = \"the cattle was rattled by the battery\"\nOutput: \"the cat was rat by the bat\"\n\nExample 2:\nInput: dictionary = [\"a\",\"b\",\"c\"], sentence = \"aadsfasf absbs bbab cadsfafs\"\nOutput: \"a a b c\"\n\nConstraints:\n- 1 <= dictionary.length <= 1000\n- 1 <= dictionary[i].length <= 100\n- dictionary[i] consists of only lower-case letters.\n- 1 <= sentence.length <= 10^6\n- sentence consists of only lower-case letters and spaces.\n- The number of words in sentence is in the range [1, 1000]\n- The length of each word in sentence is in the range [1, 1000]\n- Every two consecutive words in sentence will be separated by exactly one space.\n- sentence does not have leading or trailing spaces."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(t), t is the number of nodes in trie\n\nimport collections\n\n\nclass Solution(object):\n def replaceWords(self, dictionary, sentence):\n \"\"\"\n :type dictionary: List[str]\n :type sentence: str\n :rtype: str\n \"\"\"\n _trie = lambda: collections.defaultdict(_trie)\n trie = _trie()\n for word in dictionary:\n reduce(dict.__getitem__, word, trie).setdefault(\"_end\")\n\n def replace(word):\n curr = trie\n for i, c in enumerate(word):\n if c not in curr:\n break\n curr = curr[c]\n if \"_end\" in curr:\n return word[:i+1]\n return word\n\n return \" \".join(map(replace, sentence.split()))\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10125", "name": "LeetCode 0649: Dota2 Senate"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Dota2 Senate (Difficulty: Medium)\nTags: String, Greedy, Queue\n\nIn the world of Dota2, there are two parties: the Radiant and the Dire.\nThe Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:\nGiven a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n.\nThe round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.\nSuppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be \"Radiant\" or \"Dire\".\n\nExample 1:\nInput: senate = \"RD\"\nOutput: \"Radiant\"\nExplanation: \nThe first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.\n\nExample 2:\nInput: senate = \"RDD\"\nOutput: \"Dire\"\nExplanation: \nThe first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd the third senator comes from Dire and he can ban the first senator's right in round 1. \nAnd in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.\n\nConstraints:\n- n == senate.length\n- 1 <= n <= 10^4\n- senate[i] is either 'R' or 'D'."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def predictPartyVictory(self, senate):\n \"\"\"\n :type senate: str\n :rtype: str\n \"\"\"\n n = len(senate)\n radiant, dire = collections.deque(), collections.deque()\n for i, c in enumerate(senate):\n if c == 'R':\n radiant.append(i)\n else:\n dire.append(i)\n while radiant and dire:\n r_idx, d_idx = radiant.popleft(), dire.popleft()\n if r_idx < d_idx:\n radiant.append(r_idx+n)\n else:\n dire.append(d_idx+n)\n return \"Radiant\" if len(radiant) > len(dire) else \"Dire\"\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10126", "name": "LeetCode 0650: 2 Keys Keyboard"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: 2 Keys Keyboard (Difficulty: Medium)\nTags: Math, Dynamic Programming\n\nThere is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:\nGiven an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.\n\nExample 1:\nInput: n = 3\nOutput: 3\nExplanation: Initially, we have one character 'A'.\nIn step 1, we use Copy All operation.\nIn step 2, we use Paste operation to get 'AA'.\nIn step 3, we use Paste operation to get 'AAA'.\n\nExample 2:\nInput: n = 1\nOutput: 0\n\nConstraints:\n- 1 <= n <= 1000"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(sqrt(n))\n# Space: O(1)\n\nclass Solution(object):\n def minSteps(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n result = 0\n p = 2\n # the answer is the sum of prime factors\n while p**2 <= n:\n while n % p == 0:\n result += p\n n //= p\n p += 1\n if n > 1:\n result += n\n return result\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10128", "name": "LeetCode 0652: Find Duplicate Subtrees"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Find Duplicate Subtrees (Difficulty: Medium)\nTags: Hash Table, Tree, Depth-First Search, Binary Tree\n\nGiven the root of a binary tree, return all duplicate subtrees.\nFor each kind of duplicate subtrees, you only need to return the root node of any one of them.\nTwo trees are duplicate if they have the same structure with the same node values.\n\nExample 1:\nInput: root = [1,2,3,4,null,2,4,null,null,4]\nOutput: [[2,4],[4]]\n\nExample 2:\nInput: root = [2,1,1]\nOutput: [[1]]\n\nExample 3:\nInput: root = [2,2,2,3,null,3,null]\nOutput: [[2,3],[3]]\n\nConstraints:\n- The number of the nodes in the tree will be in the range [1, 5000]\n- -200 <= Node.val <= 200"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def findDuplicateSubtrees(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[TreeNode]\n \"\"\"\n def getid(root, lookup, trees):\n if not root:\n return -1\n node_id = lookup[root.val,\n getid(root.left, lookup, trees),\n getid(root.right, lookup, trees)]\n trees[node_id].append(root)\n return node_id\n\n trees = collections.defaultdict(list)\n lookup = collections.defaultdict()\n lookup.default_factory = lookup.__len__\n getid(root, lookup, trees)\n return [roots[0] for roots in trees.itervalues() if len(roots) > 1]\n\n\n# Time: O(n * h)\n# Space: O(n * h)\nclass Solution2(object):\n def findDuplicateSubtrees(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[TreeNode]\n \"\"\"\n def postOrderTraversal(node, lookup, result):\n if not node:\n return \"\"\n s = \"(\" + postOrderTraversal(node.left, lookup, result) + \\\n str(node.val) + \\\n postOrderTraversal(node.right, lookup, result) + \\\n \")\"\n if lookup[s] == 1:\n result.append(node)\n lookup[s] += 1\n return s\n\n lookup = collections.defaultdict(int)\n result = []\n postOrderTraversal(root, lookup, result)\n return result\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10129", "name": "LeetCode 0653: Two Sum Iv Input Is A Bst"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Two Sum IV - Input is a BST (Difficulty: Easy)\nTags: Hash Table, Two Pointers, Tree, Depth-First Search, Breadth-First Search, Binary Search Tree, Binary Tree\n\nGiven the root of a binary search tree and an integer k, return true if there exist two elements in the BST such that their sum is equal to k, or false otherwise.\n\nExample 1:\nInput: root = [5,3,6,2,4,null,7], k = 9\nOutput: true\n\nExample 2:\nInput: root = [5,3,6,2,4,null,7], k = 28\nOutput: false\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 104].\n- -10^4 <= Node.val <= 10^4\n- root is guaranteed to be a valid binary search tree.\n- -10^5 <= k <= 10^5"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nclass Solution(object):\n def findTarget(self, root, k):\n \"\"\"\n :type root: TreeNode\n :type k: int\n :rtype: bool\n \"\"\"\n class BSTIterator(object):\n def __init__(self, root, forward):\n self.__node = root\n self.__forward = forward\n self.__s = []\n self.__cur = None\n self.next()\n\n def val(self):\n return self.__cur\n\n def next(self):\n while self.__node or self.__s:\n if self.__node:\n self.__s.append(self.__node)\n self.__node = self.__node.left if self.__forward else self.__node.right\n else:\n self.__node = self.__s.pop()\n self.__cur = self.__node.val\n self.__node = self.__node.right if self.__forward else self.__node.left\n break\n\n\n if not root:\n return False\n left, right = BSTIterator(root, True), BSTIterator(root, False)\n while left.val() < right.val():\n if left.val() + right.val() == k:\n return True\n elif left.val() + right.val() < k:\n left.next()\n else:\n right.next()\n return False\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10130", "name": "LeetCode 0654: Maximum Binary Tree"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Maximum Binary Tree (Difficulty: Medium)\nTags: Array, Divide and Conquer, Stack, Tree, Monotonic Stack, Binary Tree\n\nYou are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:\nReturn the maximum binary tree built from nums.\n\nExample 1:\nInput: nums = [3,2,1,6,0,5]\nOutput: [6,3,5,null,2,0,null,null,1]\nExplanation: The recursive calls are as follow:\n- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].\n - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].\n - Empty array, so no child.\n - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].\n - Empty array, so no child.\n - Only one element, so child is a node with value 1.\n - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].\n - Only one element, so child is a node with value 0.\n - Empty array, so no child.\n\nExample 2:\nInput: nums = [3,2,1]\nOutput: [3,null,2,null,1]\n\nConstraints:\n- 1 <= nums.length <= 1000\n- 0 <= nums[i] <= 1000\n- All integers in nums are unique."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def constructMaximumBinaryTree(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: TreeNode\n \"\"\"\n # https://github.com/kamyu104/LintCode/blob/master/C++/max-tree.cpp\n nodeStack = []\n for num in nums:\n node = TreeNode(num)\n while nodeStack and num > nodeStack[-1].val:\n node.left = nodeStack.pop()\n if nodeStack:\n nodeStack[-1].right = node\n nodeStack.append(node)\n return nodeStack[0]\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10131", "name": "LeetCode 0655: Print Binary Tree"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Print Binary Tree (Difficulty: Medium)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules:\nReturn the constructed matrix res.\n\nExample 1:\nInput: root = [1,2]\nOutput: \n[[\"\",\"1\",\"\"],\n [\"2\",\"\",\"\"]]\n\nExample 2:\nInput: root = [1,2,3,null,4]\nOutput: \n[[\"\",\"\",\"\",\"1\",\"\",\"\",\"\"],\n [\"\",\"2\",\"\",\"\",\"\",\"3\",\"\"],\n [\"\",\"\",\"4\",\"\",\"\",\"\",\"\"]]\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 210].\n- -99 <= Node.val <= 99\n- The depth of the tree will be in the range [1, 10]."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(h * 2^h)\n# Space: O(h * 2^h)\n\nclass Solution(object):\n def printTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[str]]\n \"\"\"\n def getWidth(root):\n if not root:\n return 0\n return 2 * max(getWidth(root.left), getWidth(root.right)) + 1\n\n def getHeight(root):\n if not root:\n return 0\n return max(getHeight(root.left), getHeight(root.right)) + 1\n\n def preorderTraversal(root, level, left, right, result):\n if not root:\n return\n mid = left + (right-left)/2\n result[level][mid] = str(root.val)\n preorderTraversal(root.left, level+1, left, mid-1, result)\n preorderTraversal(root.right, level+1, mid+1, right, result)\n\n h, w = getHeight(root), getWidth(root)\n result = [[\"\"] * w for _ in range(h)]\n preorderTraversal(root, 0, 0, w-1, result)\n return result\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10133", "name": "LeetCode 0657: Robot Return To Origin"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Robot Return to Origin (Difficulty: Easy)\nTags: String, Simulation\n\nThere is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.\nYou are given a string moves that represents the move sequence of the robot where moves[i] represents its ith move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down).\nReturn true if the robot returns to the origin after it finishes all of its moves, or false otherwise.\nNote: The way that the robot is \"facing\" is irrelevant. 'R' will always make the robot move to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.\n\nExample 1:\nInput: moves = \"UD\"\nOutput: true\nExplanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.\n\nExample 2:\nInput: moves = \"LL\"\nOutput: false\nExplanation: The robot moves left twice. It ends up two \"moves\" to the left of the origin. We return false because it is not at the origin at the end of its moves.\n\nConstraints:\n- 1 <= moves.length <= 2 * 10^4\n- moves only contains the characters 'U', 'D', 'L' and 'R'."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def judgeCircle(self, moves):\n \"\"\"\n :type moves: str\n :rtype: bool\n \"\"\"\n count = collections.Counter(moves)\n return count['L'] == count['R'] and count['U'] == count['D']\n\n \n# Time: O(n)\n# Space: O(1)\nclass Solution(object):\n def judgeCircle(self, moves):\n \"\"\"\n :type moves: str\n :rtype: bool\n \"\"\"\n v, h = 0, 0\n for move in moves:\n if move == 'U':\n v += 1\n elif move == 'D':\n v -= 1\n elif move == 'R':\n h += 1\n elif move == 'L':\n h -= 1\n return v == 0 and h == 0\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10134", "name": "LeetCode 0658: Find K Closest Elements"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Find K Closest Elements (Difficulty: Medium)\nTags: Array, Two Pointers, Binary Search, Sliding Window, Sorting, Heap (Priority Queue)\n\nGiven a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.\nAn integer a is closer to x than an integer b if:\n\nExample 1:\nInput: arr = [1,2,3,4,5], k = 4, x = 3\nOutput: [1,2,3,4]\n\nExample 2:\nInput: arr = [1,1,2,3,4,5], k = 4, x = -1\nOutput: [1,1,2,3]\n\nConstraints:\n- 1 <= k <= arr.length\n- 1 <= arr.length <= 10^4\n- arr is sorted in ascending order.\n- -10^4 <= arr[i], x <= 10^4"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn + k)\n# Space: O(1)\n\nimport bisect\n\n\nclass Solution(object):\n def findClosestElements(self, arr, k, x):\n \"\"\"\n :type arr: List[int]\n :type k: int\n :type x: int\n :rtype: List[int]\n \"\"\"\n i = bisect.bisect_left(arr, x)\n left, right = i-1, i\n while k:\n if right >= len(arr) or \\\n (left >= 0 and abs(arr[left]-x) <= abs(arr[right]-x)):\n left -= 1\n else:\n right += 1\n k -= 1\n return arr[left+1:right]\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10135", "name": "LeetCode 0659: Split Array Into Consecutive Subsequences"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Split Array into Consecutive Subsequences (Difficulty: Medium)\nTags: Array, Hash Table, Greedy, Heap (Priority Queue)\n\nYou are given an integer array nums that is sorted in non-decreasing order.\nDetermine if it is possible to split nums into one or more subsequences such that both of the following conditions are true:\nReturn true if you can split nums according to the above conditions, or false otherwise.\nA subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).\n\nExample 1:\nInput: nums = [1,2,3,3,4,5]\nOutput: true\nExplanation: nums can be split into the following subsequences:\n[1,2,3,3,4,5] --> 1, 2, 3\n[1,2,3,3,4,5] --> 3, 4, 5\n\nExample 2:\nInput: nums = [1,2,3,3,4,4,5,5]\nOutput: true\nExplanation: nums can be split into the following subsequences:\n[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5\n[1,2,3,3,4,4,5,5] --> 3, 4, 5\n\nExample 3:\nInput: nums = [1,2,3,4,4,5]\nOutput: false\nExplanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.\n\nConstraints:\n- 1 <= nums.length <= 10^4\n- -1000 <= nums[i] <= 1000\n- nums is sorted in non-decreasing order."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def isPossible(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n pre, cur = float(\"-inf\"), 0\n cnt1, cnt2, cnt3 = 0, 0, 0\n i = 0\n while i < len(nums):\n cnt = 0\n cur = nums[i]\n while i < len(nums) and cur == nums[i]:\n cnt += 1\n i += 1\n\n if cur != pre + 1:\n if cnt1 != 0 or cnt2 != 0:\n return False\n cnt1, cnt2, cnt3 = cnt, 0, 0\n else:\n if cnt < cnt1 + cnt2:\n return False\n cnt1, cnt2, cnt3 = max(0, cnt - (cnt1 + cnt2 + cnt3)), \\\n cnt1, \\\n cnt2 + min(cnt3, cnt - (cnt1 + cnt2))\n pre = cur\n return cnt1 == 0 and cnt2 == 0\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10137", "name": "LeetCode 0661: Image Smoother"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Image Smoother (Difficulty: Easy)\nTags: Array, Matrix\n\nAn image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).\nGiven an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it.\n\nExample 1:\nInput: img = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: [[0,0,0],[0,0,0],[0,0,0]]\nExplanation:\nFor the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0\nFor the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0\nFor the point (1,1): floor(8/9) = floor(0.88888889) = 0\n\nExample 2:\nInput: img = [[100,200,100],[200,50,200],[100,200,100]]\nOutput: [[137,141,137],[141,138,141],[137,141,137]]\nExplanation:\nFor the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137\nFor the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141\nFor the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138\n\nConstraints:\n- m == img.length\n- n == img[i].length\n- 1 <= m, n <= 200\n- 0 <= img[i][j] <= 255"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def imageSmoother(self, M):\n \"\"\"\n :type M: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n def getGray(M, i, j):\n total, count = 0, 0.0\n for r in range(-1, 2):\n for c in range(-1, 2):\n ii, jj = i + r, j + c\n if 0 <= ii < len(M) and 0 <= jj < len(M[0]):\n total += M[ii][jj]\n count += 1.0\n return int(total / count)\n\n result = [[0 for _ in range(len(M[0]))] for _ in range(len(M))]\n for i in range(len(M)):\n for j in range(len(M[0])):\n result[i][j] = getGray(M, i, j)\n return result\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10138", "name": "LeetCode 0662: Maximum Width Of Binary Tree"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Maximum Width of Binary Tree (Difficulty: Medium)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven the root of a binary tree, return the maximum width of the given tree.\nThe maximum width of a tree is the maximum width among all levels.\nThe width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.\nIt is guaranteed that the answer will in the range of a 32-bit signed integer.\n\nExample 1:\nInput: root = [1,3,2,5,3,null,9]\nOutput: 4\nExplanation: The maximum width exists in the third level with length 4 (5,3,null,9).\n\nExample 2:\nInput: root = [1,3,2,5,null,null,9,6,null,7]\nOutput: 7\nExplanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).\n\nExample 3:\nInput: root = [1,3,2,5]\nOutput: 2\nExplanation: The maximum width exists in the second level with length 2 (3,2).\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 3000].\n- -100 <= Node.val <= 100"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nclass Solution(object):\n def widthOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def dfs(node, i, depth, leftmosts):\n if not node:\n return 0\n if depth >= len(leftmosts):\n leftmosts.append(i)\n return max(i-leftmosts[depth]+1, \\\n dfs(node.left, i*2, depth+1, leftmosts), \\\n dfs(node.right, i*2+1, depth+1, leftmosts))\n\n leftmosts = []\n return dfs(root, 1, 0, leftmosts)\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10140", "name": "LeetCode 0664: Strange Printer"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Strange Printer (Difficulty: Hard)\nTags: String, Dynamic Programming\n\nThere is a strange printer with the following two special properties:\nGiven a string s, return the minimum number of turns the printer needed to print it.\n\nExample 1:\nInput: s = \"aaabbb\"\nOutput: 2\nExplanation: Print \"aaa\" first and then print \"bbb\".\n\nExample 2:\nInput: s = \"aba\"\nOutput: 2\nExplanation: Print \"aaa\" first and then print \"b\" from the second place of the string, which will cover the existing character 'a'.\n\nConstraints:\n- 1 <= s.length <= 100\n- s consists of lowercase English letters."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(n^2)\n\nclass Solution(object):\n def strangePrinter(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n def dp(s, i, j, lookup):\n if i > j:\n return 0\n if (i, j) not in lookup:\n lookup[(i, j)] = dp(s, i, j-1, lookup) + 1\n for k in range(i, j):\n if s[k] == s[j]:\n lookup[(i, j)] = min(lookup[(i, j)], \\\n dp(s, i, k, lookup) + dp(s, k+1, j-1, lookup))\n return lookup[(i, j)]\n\n lookup = {}\n return dp(s, 0, len(s)-1, lookup)\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10141", "name": "LeetCode 0665: Non Decreasing Array"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Non-decreasing Array (Difficulty: Medium)\nTags: Array\n\nGiven an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.\nWe define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).\n\nExample 1:\nInput: nums = [4,2,3]\nOutput: true\nExplanation: You could modify the first 4 to 1 to get a non-decreasing array.\n\nExample 2:\nInput: nums = [4,2,1]\nOutput: false\nExplanation: You cannot get a non-decreasing array by modifying at most one element.\n\nConstraints:\n- n == nums.length\n- 1 <= n <= 10^4\n- -10^5 <= nums[i] <= 10^5"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def checkPossibility(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n modified, prev = False, nums[0]\n for i in range(1, len(nums)):\n if prev > nums[i]:\n if modified:\n return False\n if i-2 < 0 or nums[i-2] <= nums[i]:\n prev = nums[i] # nums[i-1] = nums[i], prev = nums[i]\n# else:\n# prev = nums[i-1] # nums[i] = nums[i-1], prev = nums[i]\n modified = True\n else:\n prev = nums[i]\n return True\n\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10143", "name": "LeetCode 0667: Beautiful Arrangement Ii"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Beautiful Arrangement II (Difficulty: Medium)\nTags: Array, Math\n\nGiven two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement:\nReturn the list answer. If there multiple valid answers, return any of them.\n\nExample 1:\nInput: n = 3, k = 1\nOutput: [1,2,3]\nExplanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1\n\nExample 2:\nInput: n = 3, k = 2\nOutput: [1,3,2]\nExplanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.\n\nConstraints:\n- 1 <= k < n <= 10^4"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def constructArray(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: List[int]\n \"\"\"\n result = []\n left, right = 1, n\n while left <= right:\n if k % 2:\n result.append(left)\n left += 1\n else:\n result.append(right)\n right -= 1\n if k > 1:\n k -= 1\n return result\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10144", "name": "LeetCode 0668: Kth Smallest Number In Multiplication Table"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Kth Smallest Number in Multiplication Table (Difficulty: Hard)\nTags: Math, Binary Search\n\nNearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed).\nGiven three integers m, n, and k, return the kth smallest element in the m x n multiplication table.\n\nExample 1:\nInput: m = 3, n = 3, k = 5\nOutput: 3\nExplanation: The 5th smallest number is 3.\n\nExample 2:\nInput: m = 2, n = 3, k = 6\nOutput: 6\nExplanation: The 6th smallest number is 6.\n\nConstraints:\n- 1 <= m, n <= 3 * 10^4\n- 1 <= k <= m * n"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * log(m * n))\n# Space: O(1)\n\nclass Solution(object):\n def findKthNumber(self, m, n, k):\n \"\"\"\n :type m: int\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n def count(target, m, n):\n return sum(min(target//i, n) for i in range(1, m+1))\n\n left, right = 1, m*n\n while left <= right:\n mid = left + (right-left)/2\n if count(mid, m, n) >= k:\n right = mid-1\n else:\n left = mid+1\n return left\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10145", "name": "LeetCode 0669: Trim A Binary Search Tree"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Trim a Binary Search Tree (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Search Tree, Binary Tree\n\nGiven the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.\nReturn the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.\n\nExample 1:\nInput: root = [1,0,2], low = 1, high = 2\nOutput: [1,null,2]\n\nExample 2:\nInput: root = [3,0,4,null,2,null,null,1], low = 1, high = 3\nOutput: [3,2,null,1]\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 104].\n- 0 <= Node.val <= 10^4\n- The value of each node in the tree is unique.\n- root is guaranteed to be a valid binary search tree.\n- 0 <= low <= high <= 10^4"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nclass Solution(object):\n def trimBST(self, root, L, R):\n \"\"\"\n :type root: TreeNode\n :type L: int\n :type R: int\n :rtype: TreeNode\n \"\"\"\n if not root:\n return None\n if root.val < L:\n return self.trimBST(root.right, L, R)\n if root.val > R:\n return self.trimBST(root.left, L, R)\n root.left, root.right = self.trimBST(root.left, L, R), self.trimBST(root.right, L, R)\n return root\n\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10146", "name": "LeetCode 0670: Maximum Swap"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Maximum Swap (Difficulty: Medium)\nTags: Math, Greedy\n\nYou are given an integer num. You can swap two digits at most once to get the maximum valued number.\nReturn the maximum valued number you can get.\n\nExample 1:\nInput: num = 2736\nOutput: 7236\nExplanation: Swap the number 2 and the number 7.\n\nExample 2:\nInput: num = 9973\nOutput: 9973\nExplanation: No swap.\n\nConstraints:\n- 0 <= num <= 10^8"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn), logn is the length of the number string\n# Space: O(logn)\n\nclass Solution(object):\n def maximumSwap(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n digits = list(str(num))\n left, right = 0, 0\n max_idx = len(digits)-1\n for i in reversed(range(len(digits))):\n if digits[i] > digits[max_idx]:\n max_idx = i\n elif digits[max_idx] > digits[i]:\n left, right = i, max_idx\n digits[left], digits[right] = digits[right], digits[left]\n return int(\"\".join(digits))\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10147", "name": "LeetCode 0671: Second Minimum Node In A Binary Tree"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Second Minimum Node In a Binary Tree (Difficulty: Easy)\nTags: Tree, Depth-First Search, Binary Tree\n\nGiven a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds.\nGiven such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.\nIf no such second minimum value exists, output -1 instead.\n\nExample 1:\nInput: root = [2,2,5,null,null,5,7]\nOutput: 5\nExplanation: The smallest value is 2, the second smallest value is 5.\n\nExample 2:\nInput: root = [2,2,2]\nOutput: -1\nExplanation: The smallest value is 2, but there isn't any second smallest value.\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 25].\n- 1 <= Node.val <= 2^31 - 1\n- root.val == min(root.left.val, root.right.val) for each internal node of the tree."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nimport heapq\n\n\nclass Solution(object):\n def findSecondMinimumValue(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def findSecondMinimumValueHelper(root, max_heap, lookup):\n if not root:\n return\n if root.val not in lookup:\n heapq.heappush(max_heap, -root.val)\n lookup.add(root.val)\n if len(max_heap) > 2:\n lookup.remove(-heapq.heappop(max_heap))\n findSecondMinimumValueHelper(root.left, max_heap, lookup)\n findSecondMinimumValueHelper(root.right, max_heap, lookup)\n\n max_heap, lookup = [], set()\n findSecondMinimumValueHelper(root, max_heap, lookup)\n if len(max_heap) < 2:\n return -1\n return -max_heap[0]\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10148", "name": "LeetCode 0672: Bulb Switcher Ii"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Bulb Switcher II (Difficulty: Medium)\nTags: Math, Bit Manipulation, Depth-First Search, Breadth-First Search\n\nThere is a room with n bulbs labeled from 1 to n that all are turned on initially, and four buttons on the wall. Each of the four buttons has a different functionality where:\nYou must make exactly presses button presses in total. For each press, you may pick any of the four buttons to press.\nGiven the two integers n and presses, return the number of different possible statuses after performing all presses button presses.\n\nExample 1:\nInput: n = 1, presses = 1\nOutput: 2\nExplanation: Status can be:\n- [off] by pressing button 1\n- [on] by pressing button 2\n\nExample 2:\nInput: n = 2, presses = 1\nOutput: 3\nExplanation: Status can be:\n- [off, off] by pressing button 1\n- [on, off] by pressing button 2\n- [off, on] by pressing button 3\n\nExample 3:\nInput: n = 3, presses = 1\nOutput: 4\nExplanation: Status can be:\n- [off, off, off] by pressing button 1\n- [off, on, off] by pressing button 2\n- [on, off, on] by pressing button 3\n- [off, on, on] by pressing button 4\n\nConstraints:\n- 1 <= n <= 1000\n- 0 <= presses <= 1000"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def flipLights(self, n, m):\n \"\"\"\n :type n: int\n :type m: int\n :rtype: int\n \"\"\"\n if m == 0:\n return 1\n if n == 1:\n return 2\n if m == 1 and n == 2:\n return 3\n if m == 1 or n == 2:\n return 4\n if m == 2:\n return 7\n return 8\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10149", "name": "LeetCode 0673: Number Of Longest Increasing Subsequence"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Number of Longest Increasing Subsequence (Difficulty: Medium)\nTags: Array, Dynamic Programming, Binary Indexed Tree, Segment Tree\n\nGiven an integer array nums, return the number of longest increasing subsequences.\nNotice that the sequence has to be strictly increasing.\n\nExample 1:\nInput: nums = [1,3,5,4,7]\nOutput: 2\nExplanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].\n\nExample 2:\nInput: nums = [2,2,2,2,2]\nOutput: 5\nExplanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.\n\nConstraints:\n- 1 <= nums.length <= 2000\n- -10^6 <= nums[i] <= 10^6\n- The answer is guaranteed to fit inside a 32-bit integer."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def findNumberOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result, max_len = 0, 0\n dp = [[1, 1] for _ in range(len(nums))] # {length, number} pair\n for i in range(len(nums)):\n for j in range(i):\n if nums[i] > nums[j]:\n if dp[i][0] == dp[j][0]+1:\n dp[i][1] += dp[j][1]\n elif dp[i][0] < dp[j][0]+1:\n dp[i] = [dp[j][0]+1, dp[j][1]]\n if max_len == dp[i][0]:\n result += dp[i][1]\n elif max_len < dp[i][0]:\n max_len = dp[i][0]\n result = dp[i][1]\n return result\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10150", "name": "LeetCode 0674: Longest Continuous Increasing Subsequence"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Longest Continuous Increasing Subsequence (Difficulty: Easy)\nTags: Array\n\nGiven an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.\nA continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1].\n\nExample 1:\nInput: nums = [1,3,5,4,7]\nOutput: 3\nExplanation: The longest continuous increasing subsequence is [1,3,5] with length 3.\nEven though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element\n4.\n\nExample 2:\nInput: nums = [2,2,2,2,2]\nOutput: 1\nExplanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly\nincreasing.\n\nConstraints:\n- 1 <= nums.length <= 10^4\n- -10^9 <= nums[i] <= 10^9"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result, count = 0, 0\n for i in range(len(nums)):\n if i == 0 or nums[i-1] < nums[i]:\n count += 1\n result = max(result, count)\n else:\n count = 1\n return result\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10151", "name": "LeetCode 0675: Cut Off Trees For Golf Event"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Cut Off Trees for Golf Event (Difficulty: Hard)\nTags: Array, Breadth-First Search, Heap (Priority Queue), Matrix\n\nYou are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix. In this matrix:\nIn one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.\nYou must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell).\nStarting from the point (0, 0), return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return -1.\nNote: The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.\n\nExample 1:\nInput: forest = [[1,2,3],[0,0,4],[7,6,5]]\nOutput: 6\nExplanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.\n\nExample 2:\nInput: forest = [[1,2,3],[0,0,0],[7,6,5]]\nOutput: -1\nExplanation: The trees in the bottom row cannot be accessed as the middle row is blocked.\n\nExample 3:\nInput: forest = [[2,3,4],[0,0,5],[8,7,6]]\nOutput: 6\nExplanation: You can follow the same path as Example 1 to cut off all the trees.\nNote that you can cut off the first tree at (0, 0) before making any steps.\n\nConstraints:\n- m == forest.length\n- n == forest[i].length\n- 1 <= m, n <= 50\n- 0 <= forest[i][j] <= 10^9\n- Heights of all trees are distinct."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(t * (logt + m * n)), t is the number of trees\n# Space: O(t + m * n)\n\nimport collections\nimport heapq\n\n\nclass Solution(object):\n def cutOffTree(self, forest):\n \"\"\"\n :type forest: List[List[int]]\n :rtype: int\n \"\"\"\n def dot(p1, p2):\n return p1[0]*p2[0]+p1[1]*p2[1]\n\n def minStep(p1, p2):\n min_steps = abs(p1[0]-p2[0])+abs(p1[1]-p2[1])\n closer, detour = [p1], []\n lookup = set()\n while True:\n if not closer: # cannot find a path in the closer expansions\n if not detour: # no other possible path\n return -1\n # try other possible paths in detour expansions with extra 2-step cost\n min_steps += 2\n closer, detour = detour, closer\n i, j = closer.pop()\n if (i, j) == p2:\n return min_steps\n if (i, j) not in lookup:\n lookup.add((i, j))\n for I, J in (i+1, j), (i-1, j), (i, j+1), (i, j-1):\n if 0 <= I < m and 0 <= J < n and forest[I][J] and (I, J) not in lookup:\n is_closer = dot((I-i, J-j), (p2[0]-i, p2[1]-j)) > 0\n (closer if is_closer else detour).append((I, J))\n return min_steps\n\n m, n = len(forest), len(forest[0])\n min_heap = []\n for i in range(m):\n for j in range(n):\n if forest[i][j] > 1:\n heapq.heappush(min_heap, (forest[i][j], (i, j)))\n\n start = (0, 0)\n result = 0\n while min_heap:\n tree = heapq.heappop(min_heap)\n step = minStep(start, tree[1])\n if step < 0:\n return -1\n result += step\n start = tree[1]\n return result\n\n\n# Time: O(t * (logt + m * n)), t is the number of trees\n# Space: O(t + m * n)\nclass Solution_TLE(object):\n def cutOffTree(self, forest):\n \"\"\"\n :type forest: List[List[int]]\n :rtype: int\n \"\"\"\n def minStep(p1, p2):\n min_steps = 0\n lookup = {p1}\n q = collections.deque([p1])\n while q:\n size = len(q)\n for _ in range(size):\n (i, j) = q.popleft()\n if (i, j) == p2:\n return min_steps\n for i, j in (i+1, j), (i-1, j), (i, j+1), (i, j-1):\n if not (0 <= i < m and 0 <= j < n and forest[i][j] and (i, j) not in lookup):\n continue\n q.append((i, j))\n lookup.add((i, j))\n min_steps += 1\n return -1\n\n m, n = len(forest), len(forest[0])\n min_heap = []\n for i in range(m):\n for j in range(n):\n if forest[i][j] > 1:\n heapq.heappush(min_heap, (forest[i][j], (i, j)))\n\n start = (0, 0)\n result = 0\n while min_heap:\n tree = heapq.heappop(min_heap)\n step = minStep(start, tree[1])\n if step < 0:\n return -1\n result += step\n start = tree[1]\n return result\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10152", "name": "LeetCode 0676: Implement Magic Dictionary"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Implement Magic Dictionary (Difficulty: Medium)\nTags: Hash Table, String, Depth-First Search, Design, Trie\n\nDesign a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.\nImplement the MagicDictionary class:\n\nExample 1:\nInput\n[\"MagicDictionary\", \"buildDict\", \"search\", \"search\", \"search\", \"search\"]\n[[], [[\"hello\", \"leetcode\"]], [\"hello\"], [\"hhllo\"], [\"hell\"], [\"leetcoded\"]]\nOutput\n[null, null, false, true, false, false]\n\nExplanation\nMagicDictionary magicDictionary = new MagicDictionary();\nmagicDictionary.buildDict([\"hello\", \"leetcode\"]);\nmagicDictionary.search(\"hello\"); // return False\nmagicDictionary.search(\"hhllo\"); // We can change the second 'h' to 'e' to match \"hello\" so we return True\nmagicDictionary.search(\"hell\"); // return False\nmagicDictionary.search(\"leetcoded\"); // return False\n\nConstraints:\n- 1 <= dictionary.length <= 100\n- 1 <= dictionary[i].length <= 100\n- dictionary[i] consists of only lower-case English letters.\n- All the strings in dictionary are distinct.\n- 1 <= searchWord.length <= 100\n- searchWord consists of only lower-case English letters.\n- buildDict will be called only once before search.\n- At most 100 calls will be made to search."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n), n is the length of the word\n# Space: O(d)\n\nimport collections\n\n\nclass MagicDictionary(object):\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n _trie = lambda: collections.defaultdict(_trie)\n self.trie = _trie()\n\n\n def buildDict(self, dictionary):\n \"\"\"\n Build a dictionary through a list of words\n :type dictionary: List[str]\n :rtype: void\n \"\"\"\n for word in dictionary:\n reduce(dict.__getitem__, word, self.trie).setdefault(\"_end\")\n\n\n def search(self, word):\n \"\"\"\n Returns if there is any word in the trie that equals to the given word after modifying exactly one character\n :type word: str\n :rtype: bool\n \"\"\"\n def find(word, curr, i, mistakeAllowed):\n if i == len(word):\n return \"_end\" in curr and not mistakeAllowed\n\n if word[i] not in curr:\n return any(find(word, curr[c], i+1, False) for c in curr if c != \"_end\") \\\n if mistakeAllowed else False\n\n if mistakeAllowed:\n return find(word, curr[word[i]], i+1, True) or \\\n any(find(word, curr[c], i+1, False) \\\n for c in curr if c not in (\"_end\", word[i]))\n return find(word, curr[word[i]], i+1, False)\n\n return find(word, self.trie, 0, True)\n\n\n\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10153", "name": "LeetCode 0677: Map Sum Pairs"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Map Sum Pairs (Difficulty: Medium)\nTags: Hash Table, String, Design, Trie\n\nDesign a map that allows you to do the following:\nImplement the MapSum class:\n\nExample 1:\nInput\n[\"MapSum\", \"insert\", \"sum\", \"insert\", \"sum\"]\n[[], [\"apple\", 3], [\"ap\"], [\"app\", 2], [\"ap\"]]\nOutput\n[null, null, 3, null, 5]\n\nExplanation\nMapSum mapSum = new MapSum();\nmapSum.insert(\"apple\", 3); \nmapSum.sum(\"ap\"); // return 3 (apple = 3)\nmapSum.insert(\"app\", 2); \nmapSum.sum(\"ap\"); // return 5 (apple + app = 3 + 2 = 5)\n\nConstraints:\n- 1 <= key.length, prefix.length <= 50\n- key and prefix consist of only lowercase English letters.\n- 1 <= val <= 1000\n- At most 50 calls will be made to insert and sum."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n), n is the length of key\n# Space: O(t), t is the number of nodes in trie\n\nimport collections\n\n\nclass MapSum(object):\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n _trie = lambda: collections.defaultdict(_trie)\n self.__root = _trie()\n\n\n def insert(self, key, val):\n \"\"\"\n :type key: str\n :type val: int\n :rtype: void\n \"\"\"\n # Time: O(n)\n curr = self.__root\n for c in key:\n curr = curr[c]\n delta = val\n if \"_end\" in curr:\n delta -= curr[\"_end\"]\n\n curr = self.__root\n for c in key:\n curr = curr[c]\n if \"_count\" in curr:\n curr[\"_count\"] += delta\n else:\n curr[\"_count\"] = delta\n curr[\"_end\"] = val\n\n\n def sum(self, prefix):\n \"\"\"\n :type prefix: str\n :rtype: int\n \"\"\"\n # Time: O(n)\n curr = self.__root\n for c in prefix:\n if c not in curr:\n return 0\n curr = curr[c]\n return curr[\"_count\"]\n\n\n\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-10154", "name": "LeetCode 0678: Valid Parenthesis String"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Valid Parenthesis String (Difficulty: Medium)\nTags: String, Dynamic Programming, Stack, Greedy\n\nGiven a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.\nThe following rules define a valid string:\n\nExample 1:\nInput: s = \"()\"\nOutput: true\n\nExample 2:\nInput: s = \"(*)\"\nOutput: true\n\nExample 3:\nInput: s = \"(*))\"\nOutput: true\n\nConstraints:\n- 1 <= s.length <= 100\n- s[i] is '(', ')' or '*'."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def checkValidString(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n lower, upper = 0, 0 # keep lower bound and upper bound of '(' counts\n for c in s:\n lower += 1 if c == '(' else -1\n upper -= 1 if c == ')' else -1\n if upper < 0: break\n lower = max(lower, 0)\n return lower == 0 # range of '(' count is valid\n\n"}}cp/cp-10091.jsonlAdded+4
cp/cp-10093.jsonlAdded+4
cp/cp-10094.jsonlAdded+4
cp/cp-10095.jsonlAdded+4
cp/cp-10096.jsonlAdded+4
cp/cp-10098.jsonlAdded+4
cp/cp-10099.jsonlAdded+4
cp/cp-10100.jsonlAdded+4
cp/cp-10101.jsonlAdded+4
cp/cp-10102.jsonlAdded+4
cp/cp-10104.jsonlAdded+4
cp/cp-10105.jsonlAdded+4
cp/cp-10106.jsonlAdded+4
cp/cp-10109.jsonlAdded+4
cp/cp-10112.jsonlAdded+4
cp/cp-10113.jsonlAdded+4
cp/cp-10114.jsonlAdded+4
cp/cp-10115.jsonlAdded+4
cp/cp-10116.jsonlAdded+4
cp/cp-10117.jsonlAdded+4
cp/cp-10119.jsonlAdded+4
cp/cp-10121.jsonlAdded+4
cp/cp-10122.jsonlAdded+4
cp/cp-10123.jsonlAdded+4
cp/cp-10124.jsonlAdded+4
cp/cp-10125.jsonlAdded+4
cp/cp-10126.jsonlAdded+4
cp/cp-10128.jsonlAdded+4
cp/cp-10129.jsonlAdded+4
cp/cp-10130.jsonlAdded+4
cp/cp-10131.jsonlAdded+4
cp/cp-10133.jsonlAdded+4
cp/cp-10134.jsonlAdded+4
cp/cp-10135.jsonlAdded+4
cp/cp-10137.jsonlAdded+4
cp/cp-10138.jsonlAdded+4
cp/cp-10140.jsonlAdded+4
cp/cp-10141.jsonlAdded+4
cp/cp-10143.jsonlAdded+4
cp/cp-10144.jsonlAdded+4
cp/cp-10145.jsonlAdded+4
cp/cp-10146.jsonlAdded+4
cp/cp-10147.jsonlAdded+4
cp/cp-10148.jsonlAdded+4
cp/cp-10149.jsonlAdded+4
cp/cp-10150.jsonlAdded+4
cp/cp-10151.jsonlAdded+4
cp/cp-10152.jsonlAdded+4
cp/cp-10153.jsonlAdded+4
cp/cp-10154.jsonlAdded+4