diff --git a/cp/cp-10091.jsonl b/cp/cp-10091.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1f055bfc119bef0bd7666f48afce8ce2adc056f0 --- /dev/null +++ b/cp/cp-10091.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10093.jsonl b/cp/cp-10093.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..85013ed709fca77643059ec87aa27e73c2182873 --- /dev/null +++ b/cp/cp-10093.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10094.jsonl b/cp/cp-10094.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..402ae56d954c7497dd5bcf4a735aecfc147b1648 --- /dev/null +++ b/cp/cp-10094.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10095.jsonl b/cp/cp-10095.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d107fbbb5bf6e9d764feebf85de580e0065501c9 --- /dev/null +++ b/cp/cp-10095.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10096.jsonl b/cp/cp-10096.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a4c866a8867771d69d93a851c0989108eb69878c --- /dev/null +++ b/cp/cp-10096.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10098.jsonl b/cp/cp-10098.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..975d5f2db3f39402f955fabc49cb9037dc2a28dd --- /dev/null +++ b/cp/cp-10098.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10099.jsonl b/cp/cp-10099.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4cce4ace4d703e9deffb8d87a5cb774d7bd3dff4 --- /dev/null +++ b/cp/cp-10099.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10100.jsonl b/cp/cp-10100.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..70547b943c7a49332dc226c629de333645501c43 --- /dev/null +++ b/cp/cp-10100.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10101.jsonl b/cp/cp-10101.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..49f95c437c7f0fb675327e2ad8c2ed2370d04dc8 --- /dev/null +++ b/cp/cp-10101.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10102.jsonl b/cp/cp-10102.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..284694d74e34f6f1d6944a17aa3f96a091cd3242 --- /dev/null +++ b/cp/cp-10102.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10104.jsonl b/cp/cp-10104.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..075f380d5d89d828fb6af3e4f7a313be4f46f864 --- /dev/null +++ b/cp/cp-10104.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10105.jsonl b/cp/cp-10105.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fde8c9a062f9511639d41ca045d4c883d7920a44 --- /dev/null +++ b/cp/cp-10105.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10106.jsonl b/cp/cp-10106.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3fd0d769883ec03398abd7dafff0dbaa78e3e3ec --- /dev/null +++ b/cp/cp-10106.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10109.jsonl b/cp/cp-10109.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..da918e826bf5c329da7fdf0e6a2942b5e9fe6aba --- /dev/null +++ b/cp/cp-10109.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10112.jsonl b/cp/cp-10112.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ce83be6b0c1a058e8f39f0355e29454123c10df8 --- /dev/null +++ b/cp/cp-10112.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10113.jsonl b/cp/cp-10113.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4032e80a27736628a0958869cbb60bdefea5e702 --- /dev/null +++ b/cp/cp-10113.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10114.jsonl b/cp/cp-10114.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..84d2beecf3df2e6c09958c9bf815862cf6d2fd1a --- /dev/null +++ b/cp/cp-10114.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10115.jsonl b/cp/cp-10115.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4369dcfd125a05fefeed44d4e8524f9cf173e54d --- /dev/null +++ b/cp/cp-10115.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10116.jsonl b/cp/cp-10116.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0a08d8e3d95319a09087608746e6877ab5b51a1b --- /dev/null +++ b/cp/cp-10116.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10117.jsonl b/cp/cp-10117.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3f68901ca07bfc701da50be0dd26c9f999afa942 --- /dev/null +++ b/cp/cp-10117.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10119.jsonl b/cp/cp-10119.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8d2f572d31ed7aa5afad91c2a51a389cff08ab53 --- /dev/null +++ b/cp/cp-10119.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10121.jsonl b/cp/cp-10121.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..66e25131ffb2c9bcdabd126995ef366b7540af38 --- /dev/null +++ b/cp/cp-10121.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10122.jsonl b/cp/cp-10122.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..47ecde5eba411a1ea062cbbb5b93f5513267bcb0 --- /dev/null +++ b/cp/cp-10122.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10123.jsonl b/cp/cp-10123.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f4fd2f6252e39e5013afec6c29012ae55f0e6315 --- /dev/null +++ b/cp/cp-10123.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10124.jsonl b/cp/cp-10124.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..062ada740c11ca25d76d453f004b7579bb5ae835 --- /dev/null +++ b/cp/cp-10124.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10125.jsonl b/cp/cp-10125.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d3936e9bf2a1178653459c1346567ab5c225c923 --- /dev/null +++ b/cp/cp-10125.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10126.jsonl b/cp/cp-10126.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a6146f2cbc9e8fac863b2dd69f36637be20bd585 --- /dev/null +++ b/cp/cp-10126.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10128.jsonl b/cp/cp-10128.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1673a087d255d27b16721346c2b4dce5eb0115ee --- /dev/null +++ b/cp/cp-10128.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10129.jsonl b/cp/cp-10129.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1a3369f945a4faeef0ec18d645ed584c6e3f8023 --- /dev/null +++ b/cp/cp-10129.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10130.jsonl b/cp/cp-10130.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7128ef099d5f5ad374302b7cb3025bee01ddad7f --- /dev/null +++ b/cp/cp-10130.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10131.jsonl b/cp/cp-10131.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f74030402791036c2b32cc4c2ea70543272b4e32 --- /dev/null +++ b/cp/cp-10131.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10133.jsonl b/cp/cp-10133.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e63fccfff6e706a29b56dad05f19949e6bf94052 --- /dev/null +++ b/cp/cp-10133.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10134.jsonl b/cp/cp-10134.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..74e3814dd7797f1aa377a1497ff571b0d8a729b1 --- /dev/null +++ b/cp/cp-10134.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10135.jsonl b/cp/cp-10135.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9fe2fb295e4d0945f12a9e84a21e798f36d1dde5 --- /dev/null +++ b/cp/cp-10135.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10137.jsonl b/cp/cp-10137.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..65751d219ace02872b849d98a159ada6c3c267cc --- /dev/null +++ b/cp/cp-10137.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10138.jsonl b/cp/cp-10138.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f9eb5f61733b4a906019b83d2774c8855bf422ca --- /dev/null +++ b/cp/cp-10138.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10140.jsonl b/cp/cp-10140.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..56c3158625ab03499f5874c63a10bc36813bda51 --- /dev/null +++ b/cp/cp-10140.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10141.jsonl b/cp/cp-10141.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4c5d521c349b4db14f49cd7899f7f925ba3f0ab5 --- /dev/null +++ b/cp/cp-10141.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10143.jsonl b/cp/cp-10143.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6bf83708244c44b7e4b2268ddf6e399fc8e54b63 --- /dev/null +++ b/cp/cp-10143.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10144.jsonl b/cp/cp-10144.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f2048ce4bcae13e946d13efc1e6df01155253f25 --- /dev/null +++ b/cp/cp-10144.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10145.jsonl b/cp/cp-10145.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4d12c2de77d273986d0a1cf78107c0f0ceac864d --- /dev/null +++ b/cp/cp-10145.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10146.jsonl b/cp/cp-10146.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1c0e6c13c8e463d14a929e3fdff7633fb1c24af6 --- /dev/null +++ b/cp/cp-10146.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10147.jsonl b/cp/cp-10147.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a2bd6dbfab87b0a9a2975b30c02a4b815aea2ca0 --- /dev/null +++ b/cp/cp-10147.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10148.jsonl b/cp/cp-10148.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..08ff41b4344e88983888fdbab1bf080555d9324a --- /dev/null +++ b/cp/cp-10148.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10149.jsonl b/cp/cp-10149.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3df4519f129974bceae0d9666b6c455be9321416 --- /dev/null +++ b/cp/cp-10149.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10150.jsonl b/cp/cp-10150.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ed5e63bdaeeafc4673e589209b3ed1e3de878314 --- /dev/null +++ b/cp/cp-10150.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10151.jsonl b/cp/cp-10151.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7135c6c49e7f809a5e15b0bdd34522fe53ddcd74 --- /dev/null +++ b/cp/cp-10151.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10152.jsonl b/cp/cp-10152.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2ca3596b847cd53b609843dcc7b1f05652541e64 --- /dev/null +++ b/cp/cp-10152.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10153.jsonl b/cp/cp-10153.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2bc002f277cb1dbcae45eddc3b6aed6883b7b68c --- /dev/null +++ b/cp/cp-10153.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10154.jsonl b/cp/cp-10154.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..43c0b8372151e636d75c01c28b0ccec3f1a34ea0 --- /dev/null +++ b/cp/cp-10154.jsonl @@ -0,0 +1,4 @@ +{"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"}} diff --git a/cp/cp-10155.jsonl b/cp/cp-10155.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..044e3ed521504c843d79be832ea9d10b8be41920 --- /dev/null +++ b/cp/cp-10155.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10155", "name": "LeetCode 0679: 24 Game"} +{"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: 24 Game (Difficulty: Hard)\nTags: Array, Math, Backtracking\n\nYou are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24.\nYou are restricted with the following rules:\nReturn true if you can get such expression that evaluates to 24, and false otherwise.\n\nExample 1:\nInput: cards = [4,1,8,7]\nOutput: true\nExplanation: (8-4) * (7-1) = 24\n\nExample 2:\nInput: cards = [1,2,1,2]\nOutput: false\n\nConstraints:\n- cards.length == 4\n- 1 <= cards[i] <= 9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3 * 4^n) = O(1), n = 4\n# Space: O(n^2) = O(1)\n\nfrom operator import add, sub, mul, truediv\nfrom fractions import Fraction\n\n\nclass Solution(object):\n def judgePoint24(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n if len(nums) == 1:\n return abs(nums[0]-24) < 1e-6\n ops = [add, sub, mul, truediv]\n for i in range(len(nums)):\n for j in range(len(nums)):\n if i == j:\n continue\n next_nums = [nums[k] for k in range(len(nums)) if i != k != j]\n for op in ops:\n if ((op is add or op is mul) and j > i) or \\\n (op == truediv and nums[j] == 0):\n continue\n next_nums.append(op(nums[i], nums[j]))\n if self.judgePoint24(next_nums):\n return True\n next_nums.pop()\n return False\n\n\n# Time: O(n^3 * 4^n) = O(1), n = 4\n# Space: O(n^2) = O(1)\nclass Solution2(object):\n def judgePoint24(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n def dfs(nums):\n if len(nums) == 1:\n return nums[0] == 24\n ops = [add, sub, mul, truediv]\n for i in range(len(nums)):\n for j in range(len(nums)):\n if i == j:\n continue\n next_nums = [nums[k] for k in range(len(nums))\n if i != k != j]\n for op in ops:\n if ((op is add or op is mul) and j > i) or \\\n (op == truediv and nums[j] == 0):\n continue\n next_nums.append(op(nums[i], nums[j]))\n if dfs(next_nums):\n return True\n next_nums.pop()\n return False\n\n return dfs(map(Fraction, nums))\n\n"}} diff --git a/cp/cp-10156.jsonl b/cp/cp-10156.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b533ee27e21b10dea102134a53580fa38a03f9eb --- /dev/null +++ b/cp/cp-10156.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10156", "name": "LeetCode 0680: Valid Palindrome 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: Valid Palindrome II (Difficulty: Easy)\nTags: Two Pointers, String, Greedy\n\nGiven a string s, return true if the s can be palindrome after deleting at most one character from it.\n\nExample 1:\nInput: s = \"aba\"\nOutput: true\n\nExample 2:\nInput: s = \"abca\"\nOutput: true\nExplanation: You could delete the character 'c'.\n\nExample 3:\nInput: s = \"abc\"\nOutput: false\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def validPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n def validPalindrome(s, left, right):\n while left < right:\n if s[left] != s[right]:\n return False\n left, right = left+1, right-1\n return True\n\n left, right = 0, len(s)-1\n while left < right:\n if s[left] != s[right]:\n return validPalindrome(s, left, right-1) or validPalindrome(s, left+1, right)\n left, right = left+1, right-1\n return True\n\n"}} diff --git a/cp/cp-10158.jsonl b/cp/cp-10158.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c69ea0a7daa9718a564d7f0ea800500dd56d692c --- /dev/null +++ b/cp/cp-10158.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10158", "name": "LeetCode 0682: Baseball Game"} +{"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: Baseball Game (Difficulty: Easy)\nTags: Array, Stack, Simulation\n\nYou are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.\nYou are given a list of strings operations, where operations[i] is the ith operation you must apply to the record and is one of the following:\nReturn the sum of all the scores on the record after applying all the operations.\nThe test cases are generated such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid.\n\nExample 1:\nInput: ops = [\"5\",\"2\",\"C\",\"D\",\"+\"]\nOutput: 30\nExplanation:\n\"5\" - Add 5 to the record, record is now [5].\n\"2\" - Add 2 to the record, record is now [5, 2].\n\"C\" - Invalidate and remove the previous score, record is now [5].\n\"D\" - Add 2 * 5 = 10 to the record, record is now [5, 10].\n\"+\" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].\nThe total sum is 5 + 10 + 15 = 30.\n\nExample 2:\nInput: ops = [\"5\",\"-2\",\"4\",\"C\",\"D\",\"9\",\"+\",\"+\"]\nOutput: 27\nExplanation:\n\"5\" - Add 5 to the record, record is now [5].\n\"-2\" - Add -2 to the record, record is now [5, -2].\n\"4\" - Add 4 to the record, record is now [5, -2, 4].\n\"C\" - Invalidate and remove the previous score, record is now [5, -2].\n\"D\" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].\n\"9\" - Add 9 to the record, record is now [5, -2, -4, 9].\n\"+\" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].\n\"+\" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].\nThe total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.\n\nExample 3:\nInput: ops = [\"1\",\"C\"]\nOutput: 0\nExplanation:\n\"1\" - Add 1 to the record, record is now [1].\n\"C\" - Invalidate and remove the previous score, record is now [].\nSince the record is empty, the total sum is 0.\n\nConstraints:\n- 1 <= operations.length <= 1000\n- operations[i] is \"C\", \"D\", \"+\", or a string representing an integer in the range [-3 * 10^4, 3 * 10^4].\n- For operation \"+\", there will always be at least two previous scores on the record.\n- For operations \"C\" and \"D\", there will always be at least one previous score on the record."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def calPoints(self, ops):\n \"\"\"\n :type ops: List[str]\n :rtype: int\n \"\"\"\n history = []\n for op in ops:\n if op == '+':\n history.append(history[-1] + history[-2])\n elif op == 'D':\n history.append(history[-1] * 2)\n elif op == 'C':\n history.pop()\n else:\n history.append(int(op))\n return sum(history)\n\n"}} diff --git a/cp/cp-10160.jsonl b/cp/cp-10160.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7fbaa727c85b3bf1e01fa559e790ceeadd7980e6 --- /dev/null +++ b/cp/cp-10160.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10160", "name": "LeetCode 0684: Redundant Connection"} +{"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: Redundant Connection (Difficulty: Medium)\nTags: Depth-First Search, Breadth-First Search, Union Find, Graph\n\nIn this problem, a tree is an undirected graph that is connected and has no cycles.\nYou are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph.\nReturn an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.\n\nExample 1:\nInput: edges = [[1,2],[1,3],[2,3]]\nOutput: [2,3]\n\nExample 2:\nInput: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]\nOutput: [1,4]\n\nConstraints:\n- n == edges.length\n- 3 <= n <= 1000\n- edges[i].length == 2\n- 1 <= ai < bi <= edges.length\n- ai != bi\n- There are no repeated edges.\n- The given graph is connected."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlog*n) ~= O(n), n is the length of the positions\n# Space: O(n)\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n return True\n\n\nclass Solution(object):\n def findRedundantConnection(self, edges):\n \"\"\"\n :type edges: List[List[int]]\n :rtype: List[int]\n \"\"\"\n union_find = UnionFind(len(edges)+1)\n for edge in edges:\n if not union_find.union_set(*edge):\n return edge\n return []\n"}} diff --git a/cp/cp-10161.jsonl b/cp/cp-10161.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8e4fab2925ddccfa8ae450b2365d548847d9cac0 --- /dev/null +++ b/cp/cp-10161.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10161", "name": "LeetCode 0685: Redundant Connection 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: Redundant Connection II (Difficulty: Hard)\nTags: Depth-First Search, Breadth-First Search, Union Find, Graph\n\nIn this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.\nThe given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed.\nThe resulting graph is given as a 2D-array of edges. Each element of edges is a pair [ui, vi] that represents a directed edge connecting nodes ui and vi, where ui is a parent of child vi.\nReturn an edge that can be removed so that the resulting graph is a rooted tree of n nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.\n\nExample 1:\nInput: edges = [[1,2],[1,3],[2,3]]\nOutput: [2,3]\n\nExample 2:\nInput: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]\nOutput: [4,1]\n\nConstraints:\n- n == edges.length\n- 3 <= n <= 1000\n- edges[i].length == 2\n- 1 <= ui, vi <= n\n- ui != vi"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlog*n) ~= O(n), n is the length of the positions\n# Space: O(n)\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n return True\n\n\nclass Solution(object):\n def findRedundantDirectedConnection(self, edges):\n \"\"\"\n :type edges: List[List[int]]\n :rtype: List[int]\n \"\"\"\n cand1, cand2 = [], []\n parent = {}\n for edge in edges:\n if edge[1] not in parent:\n parent[edge[1]] = edge[0]\n else:\n cand1 = [parent[edge[1]], edge[1]]\n cand2 = edge\n\n union_find = UnionFind(len(edges)+1)\n for edge in edges:\n if edge == cand2:\n continue\n if not union_find.union_set(*edge):\n return cand1 if cand2 else edge\n return cand2\n\n"}} diff --git a/cp/cp-10162.jsonl b/cp/cp-10162.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9eef4c003920fbb3ed6e9cb855c51a0f79d7730a --- /dev/null +++ b/cp/cp-10162.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10162", "name": "LeetCode 0686: Repeated String Match"} +{"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: Repeated String Match (Difficulty: Medium)\nTags: String, String Matching\n\nGiven two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b​​​​​​ to be a substring of a after repeating it, return -1.\nNotice: string \"abc\" repeated 0 times is \"\", repeated 1 time is \"abc\" and repeated 2 times is \"abcabc\".\n\nExample 1:\nInput: a = \"abcd\", b = \"cdabcdab\"\nOutput: 3\nExplanation: We return 3 because by repeating a three times \"abcdabcdabcd\", b is a substring of it.\n\nExample 2:\nInput: a = \"a\", b = \"aa\"\nOutput: 2\n\nConstraints:\n- 1 <= a.length, b.length <= 10^4\n- a and b consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + m)\n# Space: O(1)\n\nclass Solution(object):\n def repeatedStringMatch(self, A, B):\n \"\"\"\n :type A: str\n :type B: str\n :rtype: int\n \"\"\"\n def check(index):\n return all(A[(i+index) % len(A)] == c\n for i, c in enumerate(B))\n\n M, p = 10**9+7, 113\n p_inv = pow(p, M-2, M)\n q = (len(B)+len(A)-1) // len(A)\n\n b_hash, power = 0, 1\n for c in B:\n b_hash += power * ord(c)\n b_hash %= M\n power = (power*p) % M\n\n a_hash, power = 0, 1\n for i in range(len(B)):\n a_hash += power * ord(A[i%len(A)])\n a_hash %= M\n power = (power*p) % M\n\n if a_hash == b_hash and check(0): return q\n\n power = (power*p_inv) % M\n for i in range(len(B), (q+1)*len(A)):\n a_hash = (a_hash-ord(A[(i-len(B))%len(A)])) * p_inv\n a_hash += power * ord(A[i%len(A)])\n a_hash %= M\n if a_hash == b_hash and check(i-len(B)+1):\n return q if i < q*len(A) else q+1\n\n return -1\n\n"}} diff --git a/cp/cp-10163.jsonl b/cp/cp-10163.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dba111685ed8c08fc6a09cfa521d8d85e6ddf8b9 --- /dev/null +++ b/cp/cp-10163.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10163", "name": "LeetCode 0687: Longest Univalue Path"} +{"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 Univalue Path (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Tree\n\nGiven the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.\nThe length of the path between two nodes is represented by the number of edges between them.\n\nExample 1:\nInput: root = [5,4,5,1,1,null,5]\nOutput: 2\nExplanation: The shown image shows that the longest path of the same value (i.e. 5).\n\nExample 2:\nInput: root = [1,4,5,4,4,null,5]\nOutput: 2\nExplanation: The shown image shows that the longest path of the same value (i.e. 4).\n\nConstraints:\n- The number of nodes in the tree is in the range [0, 104].\n- -1000 <= Node.val <= 1000\n- The depth of the tree will not exceed 1000."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nclass Solution(object):\n def longestUnivaluePath(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n result = [0]\n def dfs(node):\n if not node:\n return 0\n left, right = dfs(node.left), dfs(node.right)\n left = (left+1) if node.left and node.left.val == node.val else 0\n right = (right+1) if node.right and node.right.val == node.val else 0\n result[0] = max(result[0], left+right)\n return max(left, right)\n\n dfs(root)\n return result[0]\n\n"}} diff --git a/cp/cp-10164.jsonl b/cp/cp-10164.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fb55f3ba760c7d7473d24a29f9ba0aaead5ece3a --- /dev/null +++ b/cp/cp-10164.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10164", "name": "LeetCode 0688: Knight Probability In Chessboard"} +{"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: Knight Probability in Chessboard (Difficulty: Medium)\nTags: Dynamic Programming\n\nOn an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1).\nA chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.\nEach time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.\nThe knight continues moving until it has made exactly k moves or has moved off the chessboard.\nReturn the probability that the knight remains on the board after it has stopped moving.\n\nExample 1:\nInput: n = 3, k = 2, row = 0, column = 0\nOutput: 0.06250\nExplanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.\nFrom each of those positions, there are also two moves that will keep the knight on the board.\nThe total probability the knight stays on the board is 0.0625.\n\nExample 2:\nInput: n = 1, k = 0, row = 0, column = 0\nOutput: 1.00000\n\nConstraints:\n- 1 <= n <= 25\n- 0 <= k <= 100\n- 0 <= row, column <= n - 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(k * n^2)\n# Space: O(n^2)\n\nclass Solution(object):\n def knightProbability(self, N, K, r, c):\n \"\"\"\n :type N: int\n :type K: int\n :type r: int\n :type c: int\n :rtype: float\n \"\"\"\n directions = \\\n [[ 1, 2], [ 1, -2], [ 2, 1], [ 2, -1], \\\n [-1, 2], [-1, -2], [-2, 1], [-2, -1]]\n dp = [[[1 for _ in range(N)] for _ in range(N)] for _ in range(2)]\n for step in range(1, K+1):\n for i in range(N):\n for j in range(N):\n dp[step%2][i][j] = 0\n for direction in directions:\n rr, cc = i+direction[0], j+direction[1]\n if 0 <= cc < N and 0 <= rr < N:\n dp[step%2][i][j] += 0.125 * dp[(step-1)%2][rr][cc]\n\n return dp[K%2][r][c]\n\n"}} diff --git a/cp/cp-10165.jsonl b/cp/cp-10165.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2fc2b788c27930f79a0f0b4344ebbefd72107e78 --- /dev/null +++ b/cp/cp-10165.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10165", "name": "LeetCode 0689: Maximum Sum Of 3 Non Overlapping Subarrays"} +{"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 Sum of 3 Non-Overlapping Subarrays (Difficulty: Hard)\nTags: Array, Dynamic Programming, Sliding Window, Prefix Sum\n\nGiven an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them.\nReturn the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.\n\nExample 1:\nInput: nums = [1,2,1,2,6,7,5,1], k = 2\nOutput: [0,3,5]\nExplanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\nWe could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.\n\nExample 2:\nInput: nums = [1,2,1,2,1,2,1,2,1], k = 2\nOutput: [0,2,4]\n\nConstraints:\n- 1 <= nums.length <= 2 * 10^4\n- 1 <= nums[i] < 216\n- 1 <= k <= floor(nums.length / 3)"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def maxSumOfThreeSubarrays(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n n = len(nums)\n accu = [0]\n for num in nums:\n accu.append(accu[-1]+num)\n\n left_pos = [0] * n\n total = accu[k]-accu[0]\n for i in range(k, n):\n if accu[i+1]-accu[i+1-k] > total:\n left_pos[i] = i+1-k\n total = accu[i+1]-accu[i+1-k]\n else:\n left_pos[i] = left_pos[i-1]\n\n right_pos = [n-k] * n\n total = accu[n]-accu[n-k]\n for i in reversed(range(n-k)):\n if accu[i+k]-accu[i] > total:\n right_pos[i] = i\n total = accu[i+k]-accu[i]\n else:\n right_pos[i] = right_pos[i+1]\n\n result, max_sum = [], 0\n for i in range(k, n-2*k+1):\n left, right = left_pos[i-1], right_pos[i+k]\n total = (accu[i+k]-accu[i]) + \\\n (accu[left+k]-accu[left]) + \\\n (accu[right+k]-accu[right])\n if total > max_sum:\n max_sum = total\n result = [left, i, right]\n return result\n\n"}} diff --git a/cp/cp-10166.jsonl b/cp/cp-10166.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..db1b1e5d776f7839b6bb4c596f37d69e5cb2b07a --- /dev/null +++ b/cp/cp-10166.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10166", "name": "LeetCode 0690: Employee Importance"} +{"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: Employee Importance (Difficulty: Medium)\nTags: Array, Hash Table, Tree, Depth-First Search, Breadth-First Search\n\nYou have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.\nYou are given an array of employees employees where:\nGiven an integer id that represents an employee's ID, return the total importance value of this employee and all their direct and indirect subordinates.\n\nExample 1:\nInput: employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1\nOutput: 11\nExplanation: Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.\nThey both have an importance value of 3.\nThus, the total importance value of employee 1 is 5 + 3 + 3 = 11.\n\nExample 2:\nInput: employees = [[1,2,[5]],[5,-3,[]]], id = 5\nOutput: -3\nExplanation: Employee 5 has an importance value of -3 and has no direct subordinates.\nThus, the total importance value of employee 5 is -3.\n\nConstraints:\n- 1 <= employees.length <= 2000\n- 1 <= employees[i].id <= 2000\n- All employees[i].id are unique.\n- -100 <= employees[i].importance <= 100\n- One employee has at most one direct leader and may have several subordinates.\n- The IDs in employees[i].subordinates are valid IDs."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nimport collections\n\n\n\"\"\"\n# Employee info\nclass Employee(object):\n def __init__(self, id, importance, subordinates):\n # It's the unique id of each node.\n # unique id of this employee\n self.id = id\n # the importance value of this employee\n self.importance = importance\n # the id of direct subordinates\n self.subordinates = subordinates\n\"\"\"\nclass Solution(object):\n def getImportance(self, employees, id):\n \"\"\"\n :type employees: Employee\n :type id: int\n :rtype: int\n \"\"\"\n if employees[id-1] is None:\n return 0\n result = employees[id-1].importance\n for id in employees[id-1].subordinates:\n result += self.getImportance(employees, id)\n return result\n\n\n# Time: O(n)\n# Space: O(w), w is the max number of nodes in the levels of the tree\nclass Solution2(object):\n def getImportance(self, employees, id):\n \"\"\"\n :type employees: Employee\n :type id: int\n :rtype: int\n \"\"\"\n result, q = 0, collections.deque([id])\n while q:\n curr = q.popleft()\n employee = employees[curr-1]\n result += employee.importance\n for id in employee.subordinates:\n q.append(id)\n return result\n\n"}} diff --git a/cp/cp-10167.jsonl b/cp/cp-10167.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5349b5507b0d2449ed5069b286543c9542e061fb --- /dev/null +++ b/cp/cp-10167.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10167", "name": "LeetCode 0691: Stickers To Spell Word"} +{"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: Stickers to Spell Word (Difficulty: Hard)\nTags: Array, Hash Table, String, Dynamic Programming, Backtracking, Bit Manipulation, Memoization, Bitmask\n\nWe are given n different types of stickers. Each sticker has a lowercase English word on it.\nYou would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.\nReturn the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.\nNote: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.\n\nExample 1:\nInput: stickers = [\"with\",\"example\",\"science\"], target = \"thehat\"\nOutput: 3\nExplanation:\nWe can use 2 \"with\" stickers, and 1 \"example\" sticker.\nAfter cutting and rearrange the letters of those stickers, we can form the target \"thehat\".\nAlso, this is the minimum number of stickers necessary to form the target string.\n\nExample 2:\nInput: stickers = [\"notice\",\"possible\"], target = \"basicbasic\"\nOutput: -1\nExplanation:\nWe cannot form the target \"basicbasic\" from cutting letters from the given stickers.\n\nConstraints:\n- n == stickers.length\n- 1 <= n <= 50\n- 1 <= stickers[i].length <= 10\n- 1 <= target.length <= 15\n- stickers[i] and target consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(T * S^T)\n# Space: O(T * S^T)\n\nimport collections\n\n\nclass Solution(object):\n def minStickers(self, stickers, target):\n \"\"\"\n :type stickers: List[str]\n :type target: str\n :rtype: int\n \"\"\"\n def minStickersHelper(sticker_counts, target, dp):\n if \"\".join(target) in dp:\n return dp[\"\".join(target)]\n target_count = collections.Counter(target)\n result = float(\"inf\")\n for sticker_count in sticker_counts:\n if sticker_count[target[0]] == 0:\n continue\n new_target = []\n for k in target_count.keys():\n if target_count[k] > sticker_count[k]:\n new_target += [k]*(target_count[k] - sticker_count[k])\n if len(new_target) != len(target):\n num = minStickersHelper(sticker_counts, new_target, dp)\n if num != -1:\n result = min(result, 1+num)\n dp[\"\".join(target)] = -1 if result == float(\"inf\") else result\n return dp[\"\".join(target)]\n\n sticker_counts = map(collections.Counter, stickers)\n dp = { \"\":0 }\n return minStickersHelper(sticker_counts, target, dp)\n\n"}} diff --git a/cp/cp-10168.jsonl b/cp/cp-10168.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2f9baac071d85eef122b1735993c851a886b1f82 --- /dev/null +++ b/cp/cp-10168.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10168", "name": "LeetCode 0692: Top K Frequent 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: Top K Frequent Words (Difficulty: Medium)\nTags: Array, Hash Table, String, Trie, Sorting, Heap (Priority Queue), Bucket Sort, Counting\n\nGiven an array of strings words and an integer k, return the k most frequent strings.\nReturn the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.\nFollow-up: Could you solve it in O(n log(k)) time and O(n) extra space?\n\nExample 1:\nInput: words = [\"i\",\"love\",\"leetcode\",\"i\",\"love\",\"coding\"], k = 2\nOutput: [\"i\",\"love\"]\nExplanation: \"i\" and \"love\" are the two most frequent words.\nNote that \"i\" comes before \"love\" due to a lower alphabetical order.\n\nExample 2:\nInput: words = [\"the\",\"day\",\"is\",\"sunny\",\"the\",\"the\",\"the\",\"sunny\",\"is\",\"is\"], k = 4\nOutput: [\"the\",\"is\",\"sunny\",\"day\"]\nExplanation: \"the\", \"is\", \"sunny\" and \"day\" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.\n\nConstraints:\n- 1 <= words.length <= 500\n- 1 <= words[i].length <= 10\n- words[i] consists of lowercase English letters.\n- k is in the range [1, The number of unique words[i]]"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + klogk) on average\n# Space: O(n)\n\nimport collections\nimport heapq\nfrom random import randint\n\n\nclass Solution(object):\n def topKFrequent(self, words, k):\n \"\"\"\n :type words: List[str]\n :type k: int\n :rtype: List[str]\n \"\"\"\n counts = collections.Counter(words)\n p = []\n for key, val in counts.iteritems():\n p.append((-val, key))\n self.kthElement(p, k-1)\n\n result = []\n sorted_p = sorted(p[:k])\n for i in range(k):\n result.append(sorted_p[i][1])\n return result\n\n def kthElement(self, nums, k): # O(n) on average\n def PartitionAroundPivot(left, right, pivot_idx, nums):\n pivot_value = nums[pivot_idx]\n new_pivot_idx = left\n nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]\n for i in range(left, right):\n if nums[i] < pivot_value:\n nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]\n new_pivot_idx += 1\n\n nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]\n return new_pivot_idx\n\n left, right = 0, len(nums) - 1\n while left <= right:\n pivot_idx = randint(left, right)\n new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, nums)\n if new_pivot_idx == k:\n return\n elif new_pivot_idx > k:\n right = new_pivot_idx - 1\n else: # new_pivot_idx < k.\n left = new_pivot_idx + 1\n\n\n# Time: O(nlogk)\n# Space: O(n)\n# Heap Solution\nclass Solution2(object):\n def topKFrequent(self, words, k):\n \"\"\"\n :type words: List[str]\n :type k: int\n :rtype: List[str]\n \"\"\"\n class MinHeapObj(object):\n def __init__(self,val):\n self.val = val\n def __lt__(self,other):\n return self.val[1] > other.val[1] if self.val[0] == other.val[0] else \\\n self.val < other.val\n def __eq__(self,other):\n return self.val == other.val\n def __str__(self):\n return str(self.val)\n\n counts = collections.Counter(words)\n min_heap = []\n for word, count in counts.iteritems():\n heapq.heappush(min_heap, MinHeapObj((count, word)))\n if len(min_heap) == k+1:\n heapq.heappop(min_heap)\n result = []\n while min_heap:\n result.append(heapq.heappop(min_heap).val[1])\n return result[::-1]\n\n\n# Time: O(n + klogk) ~ O(n + nlogn)\n# Space: O(n)\n# Bucket Sort Solution\nclass Solution3(object):\n def topKFrequent(self, words, k):\n \"\"\"\n :type words: List[str]\n :type k: int\n :rtype: List[str]\n \"\"\"\n counts = collections.Counter(words)\n buckets = [[] for _ in range(len(words)+1)]\n for word, count in counts.iteritems():\n buckets[count].append(word)\n pairs = []\n for i in reversed(range(len(words))):\n for word in buckets[i]:\n pairs.append((-i, word))\n if len(pairs) >= k:\n break\n pairs.sort()\n return [pair[1] for pair in pairs[:k]]\n\n\n# time: O(nlogn)\n# space: O(n)\n\nfrom collections import Counter\n\n\nclass Solution4(object):\n def topKFrequent(self, words, k):\n \"\"\"\n :type words: List[str]\n :type k: int\n :rtype: List[str]\n \"\"\"\n counter = Counter(words)\n candidates = counter.keys()\n candidates.sort(key=lambda w: (-counter[w], w))\n return candidates[:k]\n"}} diff --git a/cp/cp-10169.jsonl b/cp/cp-10169.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9911ac4ee8a1711f164fcac888c01fb1f1ee34b3 --- /dev/null +++ b/cp/cp-10169.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10169", "name": "LeetCode 0693: Binary Number With Alternating Bits"} +{"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: Binary Number with Alternating Bits (Difficulty: Easy)\nTags: Bit Manipulation\n\nGiven a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.\n\nExample 1:\nInput: n = 5\nOutput: true\nExplanation: The binary representation of 5 is: 101\n\nExample 2:\nInput: n = 7\nOutput: false\nExplanation: The binary representation of 7 is: 111.\n\nExample 3:\nInput: n = 11\nOutput: false\nExplanation: The binary representation of 11 is: 1011.\n\nConstraints:\n- 1 <= n <= 2^31 - 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def hasAlternatingBits(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n n, curr = divmod(n, 2)\n while n > 0:\n if curr == n % 2:\n return False\n n, curr = divmod(n, 2)\n return True\n\n"}} diff --git a/cp/cp-10171.jsonl b/cp/cp-10171.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f6a082cabf73c11791d9734e2136f365f1bb7d27 --- /dev/null +++ b/cp/cp-10171.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10171", "name": "LeetCode 0695: Max Area Of Island"} +{"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: Max Area of Island (Difficulty: Medium)\nTags: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix\n\nYou are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.\nThe area of an island is the number of cells with a value 1 in the island.\nReturn the maximum area of an island in grid. If there is no island, return 0.\n\nExample 1:\nInput: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]\nOutput: 6\nExplanation: The answer is not 11, because the island must be connected 4-directionally.\n\nExample 2:\nInput: grid = [[0,0,0,0,0,0,0,0]]\nOutput: 0\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 50\n- grid[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m * n), the max depth of dfs may be m * n\n\nclass Solution(object):\n def maxAreaOfIsland(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [[-1, 0], [ 1, 0], [ 0, 1], [ 0, -1]]\n\n def dfs(i, j, grid, area):\n if not (0 <= i < len(grid) and \\\n 0 <= j < len(grid[0]) and \\\n grid[i][j] > 0):\n return False\n grid[i][j] *= -1\n area[0] += 1\n for d in directions:\n dfs(i+d[0], j+d[1], grid, area)\n return True\n\n result = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n area = [0]\n if dfs(i, j, grid, area):\n result = max(result, area[0])\n return result\n\n"}} diff --git a/cp/cp-10172.jsonl b/cp/cp-10172.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8249e34943dc90ed2142a8060238e86f301f0d36 --- /dev/null +++ b/cp/cp-10172.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10172", "name": "LeetCode 0696: Count Binary 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: Count Binary Substrings (Difficulty: Easy)\nTags: Two Pointers, String\n\nGiven a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.\nSubstrings that occur multiple times are counted the number of times they occur.\n\nExample 1:\nInput: s = \"00110011\"\nOutput: 6\nExplanation: There are 6 substrings that have equal number of consecutive 1's and 0's: \"0011\", \"01\", \"1100\", \"10\", \"0011\", and \"01\".\nNotice that some of these substrings repeat and are counted the number of times they occur.\nAlso, \"00110011\" is not a valid substring because all the 0's (and 1's) are not grouped together.\n\nExample 2:\nInput: s = \"10101\"\nOutput: 4\nExplanation: There are 4 substrings: \"10\", \"01\", \"10\", \"01\" that have equal number of consecutive 1's and 0's.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s[i] is either '0' or '1'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def countBinarySubstrings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result, prev, curr = 0, 0, 1\n for i in range(1, len(s)):\n if s[i-1] != s[i]:\n result += min(prev, curr)\n prev, curr = curr, 1\n else:\n curr += 1\n result += min(prev, curr)\n return result\n\n"}} diff --git a/cp/cp-10173.jsonl b/cp/cp-10173.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f9912a292b4d74f992c7cd971421f86b9af29c83 --- /dev/null +++ b/cp/cp-10173.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10173", "name": "LeetCode 0697: Degree Of An 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: Degree of an Array (Difficulty: Easy)\nTags: Array, Hash Table\n\nGiven a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.\nYour task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.\n\nExample 1:\nInput: nums = [1,2,2,3,1]\nOutput: 2\nExplanation: \nThe input array has a degree of 2 because both elements 1 and 2 appear twice.\nOf the subarrays that have the same degree:\n[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]\nThe shortest length is 2. So return 2.\n\nExample 2:\nInput: nums = [1,2,2,3,1,4,2]\nOutput: 6\nExplanation: \nThe degree is 3 because the element 2 is repeated 3 times.\nSo [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.\n\nConstraints:\n- nums.length will be between 1 and 50,000.\n- nums[i] will be an integer between 0 and 49,999."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def findShortestSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n counts = collections.Counter(nums)\n left, right = {}, {}\n for i, num in enumerate(nums):\n left.setdefault(num, i)\n right[num] = i\n degree = max(counts.values())\n return min(right[num]-left[num]+1 \\\n for num in counts.keys() \\\n if counts[num] == degree)\n\n"}} diff --git a/cp/cp-10174.jsonl b/cp/cp-10174.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..924e54c81ae1eeb51c01132ed1b113a09d1ac420 --- /dev/null +++ b/cp/cp-10174.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10174", "name": "LeetCode 0698: Partition To K Equal Sum Subsets"} +{"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: Partition to K Equal Sum Subsets (Difficulty: Medium)\nTags: Array, Dynamic Programming, Backtracking, Bit Manipulation, Memoization, Bitmask\n\nGiven an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.\n\nExample 1:\nInput: nums = [4,3,2,3,5,2,1], k = 4\nOutput: true\nExplanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.\n\nExample 2:\nInput: nums = [1,2,3,4], k = 3\nOutput: false\n\nConstraints:\n- 1 <= k <= nums.length <= 16\n- 1 <= nums[i] <= 10^4\n- The frequency of each element is in the range [1, 4]."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n*2^n)\n# Space: O(2^n)\n\nclass Solution(object):\n def canPartitionKSubsets(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n def dfs(nums, target, used, todo, lookup):\n if lookup[used] is None:\n targ = (todo-1)%target + 1\n lookup[used] = any(dfs(nums, target, used | (1<>i) & 1) == 0 and num <= targ)\n return lookup[used]\n\n total = sum(nums)\n if total%k or max(nums) > total//k:\n return False\n lookup = [None] * (1 << len(nums))\n lookup[-1] = True\n return dfs(nums, total//k, 0, total, lookup)\n\n\n# Time: O(k^(n-k) * k!)\n# Space: O(n)\n# DFS solution with pruning.\nclass Solution2(object):\n def canPartitionKSubsets(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n def dfs(nums, target, i, subset_sums):\n if i == len(nums):\n return True\n for k in range(len(subset_sums)):\n if subset_sums[k]+nums[i] > target:\n continue\n subset_sums[k] += nums[i]\n if dfs(nums, target, i+1, subset_sums):\n return True\n subset_sums[k] -= nums[i]\n if not subset_sums[k]: break\n return False\n\n total = sum(nums)\n if total%k != 0 or max(nums) > total//k:\n return False\n nums.sort(reverse=True)\n subset_sums = [0] * k\n return dfs(nums, total//k, 0, subset_sums)\n\n"}} diff --git a/cp/cp-10175.jsonl b/cp/cp-10175.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..24a42a5ecd3922ef4a33a2f73ac5808e03a067f0 --- /dev/null +++ b/cp/cp-10175.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10175", "name": "LeetCode 0699: Falling Squares"} +{"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: Falling Squares (Difficulty: Hard)\nTags: Array, Segment Tree, Ordered Set\n\nThere are several squares being dropped onto the X-axis of a 2D plane.\nYou are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] represents the ith square with a side length of sideLengthi that is dropped with its left edge aligned with X-coordinate lefti.\nEach square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved.\nAfter each square is dropped, you must record the height of the current tallest stack of squares.\nReturn an integer array ans where ans[i] represents the height described above after dropping the ith square.\n\nExample 1:\nInput: positions = [[1,2],[2,3],[6,1]]\nOutput: [2,5,5]\nExplanation:\nAfter the first drop, the tallest stack is square 1 with a height of 2.\nAfter the second drop, the tallest stack is squares 1 and 2 with a height of 5.\nAfter the third drop, the tallest stack is still squares 1 and 2 with a height of 5.\nThus, we return an answer of [2, 5, 5].\n\nExample 2:\nInput: positions = [[100,100],[200,100]]\nOutput: [100,100]\nExplanation:\nAfter the first drop, the tallest stack is square 1 with a height of 100.\nAfter the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.\nThus, we return an answer of [100, 100].\nNote that square 2 only brushes the right side of square 1, which does not count as landing on it.\n\nConstraints:\n- 1 <= positions.length <= 1000\n- 1 <= lefti <= 10^8\n- 1 <= sideLengthi <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2), could be improved to O(nlogn) in cpp by ordered map (bst)\n# Space: O(n)\n\nimport bisect\n\n\nclass Solution(object):\n def fallingSquares(self, positions):\n result = []\n pos = [-1]\n heights = [0]\n maxH = 0\n for left, side in positions:\n l = bisect.bisect_right(pos, left)\n r = bisect.bisect_left(pos, left+side)\n high = max(heights[l-1:r] or [0]) + side\n pos[l:r] = [left, left+side] # Time: O(n)\n heights[l:r] = [high, heights[r-1]] # Time: O(n)\n maxH = max(maxH, high)\n result.append(maxH)\n return result\n\n\nclass SegmentTree(object):\n def __init__(self, N,\n query_fn=min,\n update_fn=lambda x, y: y,\n default_val=float(\"inf\")):\n self.N = N\n self.H = (N-1).bit_length()\n self.query_fn = query_fn\n self.update_fn = update_fn\n self.default_val = default_val\n self.tree = [default_val] * (2 * N)\n self.lazy = [None] * N\n\n def __apply(self, x, val):\n self.tree[x] = self.update_fn(self.tree[x], val)\n if x < self.N:\n self.lazy[x] = self.update_fn(self.lazy[x], val)\n\n def update(self, L, R, h):\n def pull(x):\n while x > 1:\n x //= 2\n self.tree[x] = self.query_fn(self.tree[x*2], self.tree[x*2 + 1])\n if self.lazy[x] is not None:\n self.tree[x] = self.update_fn(self.tree[x], self.lazy[x])\n\n L += self.N\n R += self.N\n L0, R0 = L, R\n while L <= R:\n if L & 1:\n self.__apply(L, h)\n L += 1\n if R & 1 == 0:\n self.__apply(R, h)\n R -= 1\n L //= 2\n R //= 2\n pull(L0)\n pull(R0)\n\n def query(self, L, R):\n def push(x):\n n = 2**self.H\n while n != 1:\n y = x // n\n if self.lazy[y] is not None:\n self.__apply(y*2, self.lazy[y])\n self.__apply(y*2 + 1, self.lazy[y])\n self.lazy[y] = None\n n //= 2\n\n result = self.default_val\n if L > R:\n return result\n\n L += self.N\n R += self.N\n push(L)\n push(R)\n while L <= R:\n if L & 1:\n result = self.query_fn(result, self.tree[L])\n L += 1\n if R & 1 == 0:\n result = self.query_fn(result, self.tree[R])\n R -= 1\n L //= 2\n R //= 2\n return result\n \n def data(self):\n showList = []\n for i in range(self.N):\n showList.append(self.query(i, i))\n return showList\n\n\nclass SegmentTree2(object):\n def __init__(self, nums,\n query_fn=min,\n update_fn=lambda x, y: y,\n default_val=float(\"inf\")):\n \"\"\"\n initialize your data structure here.\n :type nums: List[int]\n \"\"\"\n N = len(nums)\n self.__original_length = N\n self.__tree_length = 2**(N.bit_length() + (N&(N-1) != 0))-1\n self.__query_fn = query_fn\n self.__update_fn = update_fn\n self.__default_val = default_val\n self.__tree = [default_val for _ in range(self.__tree_length)]\n self.__lazy = [None for _ in range(self.__tree_length)]\n self.__constructTree(nums, 0, self.__original_length-1, 0)\n\n def update(self, i, j, val):\n self.__updateTree(val, i, j, 0, self.__original_length-1, 0)\n\n def query(self, i, j):\n return self.__queryRange(i, j, 0, self.__original_length-1, 0)\n\n def __constructTree(self, nums, left, right, idx):\n if left > right:\n return\n if left == right:\n self.__tree[idx] = self.__update_fn(self.__tree[idx], nums[left])\n return \n mid = left + (right-left)//2\n self.__constructTree(nums, left, mid, idx*2 + 1)\n self.__constructTree(nums, mid+1, right, idx*2 + 2)\n self.__tree[idx] = self.__query_fn(self.__tree[idx*2 + 1], self.__tree[idx*2 + 2])\n\n def __apply(self, left, right, idx, val):\n self.__tree[idx] = self.__update_fn(self.__tree[idx], val)\n if left != right:\n self.__lazy[idx*2 + 1] = self.__update_fn(self.__lazy[idx*2 + 1], val)\n self.__lazy[idx*2 + 2] = self.__update_fn(self.__lazy[idx*2 + 2], val)\n\n def __updateTree(self, val, range_left, range_right, left, right, idx):\n if left > right:\n return\n if self.__lazy[idx] is not None:\n self.__apply(left, right, idx, self.__lazy[idx])\n self.__lazy[idx] = None\n if range_left > right or range_right < left:\n return\n if range_left <= left and right <= range_right:\n self.__apply(left, right, idx, val)\n return\n mid = left + (right-left)//2\n self.__updateTree(val, range_left, range_right, left, mid, idx*2 + 1)\n self.__updateTree(val, range_left, range_right, mid+1, right, idx*2 + 2)\n self.__tree[idx] = self.__query_fn(self.__tree[idx*2 + 1],\n self.__tree[idx*2 + 2])\n\n def __queryRange(self, range_left, range_right, left, right, idx):\n if left > right:\n return self.__default_val\n if self.__lazy[idx] is not None:\n self.__apply(left, right, idx, self.__lazy[idx])\n self.__lazy[idx] = None\n if right < range_left or left > range_right:\n return self.__default_val\n if range_left <= left and right <= range_right:\n return self.__tree[idx]\n mid = left + (right-left)//2\n return self.__query_fn(self.__queryRange(range_left, range_right, left, mid, idx*2 + 1), \n self.__queryRange(range_left, range_right, mid + 1, right, idx*2 + 2))\n\n\n# Time: O(nlogn)\n# Space: O(n)\n# Segment Tree solution.\nclass Solution2(object):\n def fallingSquares(self, positions):\n index = set()\n for left, size in positions:\n index.add(left)\n index.add(left+size-1)\n index = sorted(list(index))\n tree = SegmentTree(len(index), max, max, 0)\n # tree = SegmentTree2([0]*len(index), max, max, 0)\n max_height = 0\n result = []\n for left, size in positions:\n L, R = bisect.bisect_left(index, left), bisect.bisect_left(index, left+size-1)\n h = tree.query(L, R) + size\n tree.update(L, R, h)\n max_height = max(max_height, h)\n result.append(max_height)\n return result\n\n\n# Time: O(n * sqrt(n))\n# Space: O(n)\nclass Solution3(object):\n def fallingSquares(self, positions):\n def query(heights, left, right, B, blocks, blocks_read):\n result = 0\n while left % B and left <= right:\n result = max(result, heights[left], blocks[left//B])\n left += 1\n while right % B != B-1 and left <= right:\n result = max(result, heights[right], blocks[right//B])\n right -= 1\n while left <= right:\n result = max(result, blocks[left//B], blocks_read[left//B])\n left += B\n return result\n\n def update(heights, left, right, B, blocks, blocks_read, h):\n while left % B and left <= right:\n heights[left] = max(heights[left], h)\n blocks_read[left//B] = max(blocks_read[left//B], h)\n left += 1\n while right % B != B-1 and left <= right:\n heights[right] = max(heights[right], h)\n blocks_read[right//B] = max(blocks_read[right//B], h)\n right -= 1\n while left <= right:\n blocks[left//B] = max(blocks[left//B], h)\n left += B\n\n index = set()\n for left, size in positions:\n index.add(left)\n index.add(left+size-1)\n index = sorted(list(index))\n W = len(index)\n B = int(W**.5)\n heights = [0] * W\n blocks = [0] * (B+2)\n blocks_read = [0] * (B+2)\n\n max_height = 0\n result = []\n for left, size in positions:\n L, R = bisect.bisect_left(index, left), bisect.bisect_left(index, left+size-1)\n h = query(heights, L, R, B, blocks, blocks_read) + size\n update(heights, L, R, B, blocks, blocks_read, h)\n max_height = max(max_height, h)\n result.append(max_height)\n return result\n\n\n# Time: O(n^2)\n# Space: O(n)\nclass Solution4(object):\n def fallingSquares(self, positions):\n \"\"\"\n :type positions: List[List[int]]\n :rtype: List[int]\n \"\"\"\n heights = [0] * len(positions)\n for i in range(len(positions)):\n left_i, size_i = positions[i]\n right_i = left_i + size_i\n heights[i] += size_i\n for j in range(i+1, len(positions)):\n left_j, size_j = positions[j]\n right_j = left_j + size_j\n if left_j < right_i and left_i < right_j: # intersect\n heights[j] = max(heights[j], heights[i])\n\n result = []\n for height in heights:\n result.append(max(result[-1], height) if result else height)\n return result\n\n"}} diff --git a/cp/cp-10176.jsonl b/cp/cp-10176.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8052354ecbe0f32efa98a05bbd8e3434b9dedf49 --- /dev/null +++ b/cp/cp-10176.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10176", "name": "LeetCode 0700: Search In 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: Search in a Binary Search Tree (Difficulty: Easy)\nTags: Tree, Binary Search Tree, Binary Tree\n\nYou are given the root of a binary search tree (BST) and an integer val.\nFind the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.\n\nExample 1:\nInput: root = [4,2,7,1,3], val = 2\nOutput: [2,1,3]\n\nExample 2:\nInput: root = [4,2,7,1,3], val = 5\nOutput: []\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 5000].\n- 1 <= Node.val <= 10^7\n- root is a binary search tree.\n- 1 <= val <= 10^7"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(h)\n# Space: O(1)\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 searchBST(self, root, val):\n \"\"\"\n :type root: TreeNode\n :type val: int\n :rtype: TreeNode\n \"\"\"\n while root and val != root.val:\n if val < root.val:\n root = root.left\n else:\n root = root.right\n return root\n\n"}} diff --git a/cp/cp-10177.jsonl b/cp/cp-10177.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..412ddbea637de23c992c11105d14e20610fbed04 --- /dev/null +++ b/cp/cp-10177.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10177", "name": "LeetCode 0701: Insert Into 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: Insert into a Binary Search Tree (Difficulty: Medium)\nTags: Tree, Binary Search Tree, Binary Tree\n\nYou are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.\nNotice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.\n\nExample 1:\nInput: root = [4,2,7,1,3], val = 5\nOutput: [4,2,7,1,3,5]\nExplanation: Another accepted tree is:\n\nExample 2:\nInput: root = [40,20,60,10,30,50,70], val = 25\nOutput: [40,20,60,10,30,50,70,null,null,25]\n\nExample 3:\nInput: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5\nOutput: [4,2,7,1,3,5]\n\nConstraints:\n- The number of nodes in the tree will be in the range [0, 104].\n- -108 <= Node.val <= 10^8\n- All the values Node.val are unique.\n- -108 <= val <= 10^8\n- It's guaranteed that val does not exist in the original BST."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(h)\n# Space: O(1)\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 insertIntoBST(self, root, val):\n \"\"\"\n :type root: TreeNode\n :type val: int\n :rtype: TreeNode\n \"\"\"\n curr, parent = root, None\n while curr:\n parent = curr\n if val <= curr.val:\n curr = curr.left\n else:\n curr = curr.right\n if not parent:\n root = TreeNode(val)\n elif val <= parent.val:\n parent.left = TreeNode(val)\n else:\n parent.right = TreeNode(val)\n return root\n\n\n# Time: O(h)\n# Space: O(h)\nclass Solution2(object):\n def insertIntoBST(self, root, val):\n \"\"\"\n :type root: TreeNode\n :type val: int\n :rtype: TreeNode\n \"\"\"\n if not root:\n root = TreeNode(val)\n else:\n if val <= root.val:\n root.left = self.insertIntoBST(root.left, val)\n else:\n root.right = self.insertIntoBST(root.right, val)\n return root\n\n"}} diff --git a/cp/cp-10179.jsonl b/cp/cp-10179.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9ed819104b30f0819864dea19a662a83ff4b8545 --- /dev/null +++ b/cp/cp-10179.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10179", "name": "LeetCode 0703: Kth Largest Element In A Stream"} +{"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 Largest Element in a Stream (Difficulty: Easy)\nTags: Tree, Design, Binary Search Tree, Heap (Priority Queue), Binary Tree, Data Stream\n\nYou are part of a university admissions office and need to keep track of the kth highest test score from applicants in real-time. This helps to determine cut-off marks for interviews and admissions dynamically as new applicants submit their scores.\nYou are tasked to implement a class which, for a given integer k, maintains a stream of test scores and continuously returns the kth highest test score after a new score has been submitted. More specifically, we are looking for the kth highest score in the sorted list of all scores.\nImplement the KthLargest class:\n\nExample 1:\nInput: [\"KthLargest\", \"add\", \"add\", \"add\", \"add\", \"add\"] [[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]\nOutput: [null, 4, 5, 5, 8, 8]\nExplanation:\nKthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]); kthLargest.add(3); // return 4 kthLargest.add(5); // return 5 kthLargest.add(10); // return 5 kthLargest.add(9); // return 8 kthLargest.add(4); // return 8\n\nExample 2:\nInput: [\"KthLargest\", \"add\", \"add\", \"add\", \"add\"] [[4, [7, 7, 7, 7, 8, 3]], [2], [10], [9], [9]]\nOutput: [null, 7, 7, 7, 8]\nExplanation:\n\nConstraints:\n- 0 <= nums.length <= 10^4\n- 1 <= k <= nums.length + 1\n- -10^4 <= nums[i] <= 10^4\n- -10^4 <= val <= 10^4\n- At most 104 calls will be made to add."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogk)\n# Space: O(k)\n\nimport heapq\n\n\nclass KthLargest(object):\n\n def __init__(self, k, nums):\n \"\"\"\n :type k: int\n :type nums: List[int]\n \"\"\"\n self.__k = k\n self.__min_heap = []\n for n in nums:\n self.add(n)\n \n\n def add(self, val):\n \"\"\"\n :type val: int\n :rtype: int\n \"\"\"\n heapq.heappush(self.__min_heap, val)\n if len(self.__min_heap) > self.__k:\n heapq.heappop(self.__min_heap)\n return self.__min_heap[0]\n\n\n\n"}} diff --git a/cp/cp-10180.jsonl b/cp/cp-10180.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b503d0b04828b2621267a500480ac28196485e4b --- /dev/null +++ b/cp/cp-10180.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10180", "name": "LeetCode 0704: Binary Search"} +{"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: Binary Search (Difficulty: Easy)\nTags: Array, Binary Search\n\nGiven an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.\nYou must write an algorithm with O(log n) runtime complexity.\n\nExample 1:\nInput: nums = [-1,0,3,5,9,12], target = 9\nOutput: 4\nExplanation: 9 exists in nums and its index is 4\n\nExample 2:\nInput: nums = [-1,0,3,5,9,12], target = 2\nOutput: -1\nExplanation: 2 does not exist in nums so return -1\n\nConstraints:\n- 1 <= nums.length <= 10^4\n- -10^4 < nums[i], target < 10^4\n- All the integers in nums are unique.\n- nums is sorted in ascending order."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nclass Solution(object):\n def search(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n left, right = 0, len(nums)-1\n while left <= right:\n mid = left + (right-left)//2\n if nums[mid] > target:\n right = mid-1\n elif nums[mid] < target:\n left = mid+1\n else:\n return mid\n return -1\n\n"}} diff --git a/cp/cp-10181.jsonl b/cp/cp-10181.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..17461dab57f2736f3fdbaddd7bec50030c967798 --- /dev/null +++ b/cp/cp-10181.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10181", "name": "LeetCode 0705: Design Hashset"} +{"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 HashSet (Difficulty: Easy)\nTags: Array, Hash Table, Linked List, Design, Hash Function\n\nDesign a HashSet without using any built-in hash table libraries.\nImplement MyHashSet class:\n\nExample 1:\nInput\n[\"MyHashSet\", \"add\", \"add\", \"contains\", \"contains\", \"add\", \"contains\", \"remove\", \"contains\"]\n[[], [1], [2], [1], [3], [2], [2], [2], [2]]\nOutput\n[null, null, null, true, false, null, true, null, false]\n\nExplanation\nMyHashSet myHashSet = new MyHashSet();\nmyHashSet.add(1); // set = [1]\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(1); // return True\nmyHashSet.contains(3); // return False, (not found)\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(2); // return True\nmyHashSet.remove(2); // set = [1]\nmyHashSet.contains(2); // return False, (already removed)\n\nConstraints:\n- 0 <= key <= 10^6\n- At most 104 calls will be made to add, remove, and contains."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(n)\n\nclass ListNode(object):\n def __init__(self, key, val):\n self.val = val\n self.key = key\n self.next = None\n self.prev = None\n\n\nclass LinkedList(object):\n def __init__(self):\n self.head = None\n self.tail = None\n\n def insert(self, node):\n node.next, node.prev = None, None # avoid dirty node\n if self.head is None:\n self.head = node\n else:\n self.tail.next = node\n node.prev = self.tail\n self.tail = node\n\n def delete(self, node):\n if node.prev:\n node.prev.next = node.next\n else:\n self.head = node.next\n if node.next:\n node.next.prev = node.prev\n else:\n self.tail = node.prev\n node.next, node.prev = None, None # make node clean\n\n def find(self, key):\n curr = self.head\n while curr:\n if curr.key == key:\n break\n curr = curr.next\n return curr\n\n\nclass MyHashSet(object):\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.__data = [LinkedList() for _ in range(10000)]\n\n def add(self, key):\n \"\"\"\n :type key: int\n :rtype: void\n \"\"\"\n l = self.__data[key % len(self.__data)]\n node = l.find(key)\n if not node:\n l.insert(ListNode(key, 0))\n\n def remove(self, key):\n \"\"\"\n :type key: int\n :rtype: void\n \"\"\"\n l = self.__data[key % len(self.__data)]\n node = l.find(key)\n if node:\n l.delete(node)\n\n def contains(self, key):\n \"\"\"\n Returns true if this set did not already contain the specified element\n :type key: int\n :rtype: bool\n \"\"\"\n l = self.__data[key % len(self.__data)]\n node = l.find(key)\n return node is not None\n\n\n\n"}} diff --git a/cp/cp-10182.jsonl b/cp/cp-10182.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..67f7589a43b81b37927f5a2bce5157ba83c24c23 --- /dev/null +++ b/cp/cp-10182.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10182", "name": "LeetCode 0706: Design Hashmap"} +{"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 HashMap (Difficulty: Easy)\nTags: Array, Hash Table, Linked List, Design, Hash Function\n\nDesign a HashMap without using any built-in hash table libraries.\nImplement the MyHashMap class:\n\nExample 1:\nInput\n[\"MyHashMap\", \"put\", \"put\", \"get\", \"get\", \"put\", \"get\", \"remove\", \"get\"]\n[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]\nOutput\n[null, null, null, 1, -1, null, 1, null, -1]\n\nExplanation\nMyHashMap myHashMap = new MyHashMap();\nmyHashMap.put(1, 1); // The map is now [[1,1]]\nmyHashMap.put(2, 2); // The map is now [[1,1], [2,2]]\nmyHashMap.get(1); // return 1, The map is now [[1,1], [2,2]]\nmyHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]]\nmyHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)\nmyHashMap.get(2); // return 1, The map is now [[1,1], [2,1]]\nmyHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]\nmyHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]\n\nConstraints:\n- 0 <= key, value <= 10^6\n- At most 104 calls will be made to put, get, and remove."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(n)\n\nclass ListNode(object):\n def __init__(self, key, val):\n self.val = val\n self.key = key\n self.next = None\n self.prev = None\n\n\nclass LinkedList(object):\n def __init__(self):\n self.head = None\n self.tail = None\n\n def insert(self, node):\n node.next, node.prev = None, None # avoid dirty node\n if self.head is None:\n self.head = node\n else:\n self.tail.next = node\n node.prev = self.tail\n self.tail = node\n\n def delete(self, node):\n if node.prev:\n node.prev.next = node.next\n else:\n self.head = node.next\n if node.next:\n node.next.prev = node.prev\n else:\n self.tail = node.prev\n node.next, node.prev = None, None # make node clean\n\n def find(self, key):\n curr = self.head\n while curr:\n if curr.key == key:\n break\n curr = curr.next\n return curr\n\n\nclass MyHashMap(object):\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.__data = [LinkedList() for _ in range(10000)]\n\n def put(self, key, value):\n \"\"\"\n value will always be positive.\n :type key: int\n :type value: int\n :rtype: void\n \"\"\"\n l = self.__data[key % len(self.__data)]\n node = l.find(key)\n if node:\n node.val = value\n else:\n l.insert(ListNode(key, value))\n\n def get(self, key):\n \"\"\"\n Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key\n :type key: int\n :rtype: int\n \"\"\"\n l = self.__data[key % len(self.__data)]\n node = l.find(key)\n if node:\n return node.val\n else:\n return -1\n\n def remove(self, key):\n \"\"\"\n Removes the mapping of the specified value key if this map contains a mapping for the key\n :type key: int\n :rtype: void\n \"\"\"\n l = self.__data[key % len(self.__data)]\n node = l.find(key)\n if node:\n l.delete(node)\n\n\n\n"}} diff --git a/cp/cp-10183.jsonl b/cp/cp-10183.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6eec279e8d3384ce6c6ebb93c70be42bec59b2f0 --- /dev/null +++ b/cp/cp-10183.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10183", "name": "LeetCode 0707: Design Linked List"} +{"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 Linked List (Difficulty: Medium)\nTags: Linked List, Design\n\nDesign your implementation of the linked list. You can choose to use a singly or doubly linked list.\nA node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node.\nIf you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.\nImplement the MyLinkedList class:\n\nExample 1:\nInput\n[\"MyLinkedList\", \"addAtHead\", \"addAtTail\", \"addAtIndex\", \"get\", \"deleteAtIndex\", \"get\"]\n[[], [1], [3], [1, 2], [1], [1], [1]]\nOutput\n[null, null, null, null, 2, null, 3]\n\nExplanation\nMyLinkedList myLinkedList = new MyLinkedList();\nmyLinkedList.addAtHead(1);\nmyLinkedList.addAtTail(3);\nmyLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3\nmyLinkedList.get(1); // return 2\nmyLinkedList.deleteAtIndex(1); // now the linked list is 1->3\nmyLinkedList.get(1); // return 3\n\nConstraints:\n- 0 <= index, val <= 1000\n- Please do not use the built-in LinkedList library.\n- At most 2000 calls will be made to get, addAtHead, addAtTail, addAtIndex and deleteAtIndex."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Node(object):\n def __init__(self, value):\n self.val = value\n self.next = self.prev = None\n\n\nclass MyLinkedList(object):\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.__head = self.__tail = Node(-1)\n self.__head.next = self.__tail\n self.__tail.prev = self.__head\n self.__size = 0\n\n def get(self, index):\n \"\"\"\n Get the value of the index-th node in the linked list. If the index is invalid, return -1.\n :type index: int\n :rtype: int\n \"\"\"\n if 0 <= index <= self.__size // 2:\n return self.__forward(0, index, self.__head.next).val\n elif self.__size // 2 < index < self.__size:\n return self.__backward(self.__size, index, self.__tail).val\n return -1\n\n def addAtHead(self, val):\n \"\"\"\n Add a node of value val before the first element of the linked list.\n After the insertion, the new node will be the first node of the linked list.\n :type val: int\n :rtype: void\n \"\"\"\n self.__add(self.__head, val)\n\n def addAtTail(self, val):\n \"\"\"\n Append a node of value val to the last element of the linked list.\n :type val: int\n :rtype: void\n \"\"\"\n self.__add(self.__tail.prev, val)\n\n def addAtIndex(self, index, val):\n \"\"\"\n Add a node of value val before the index-th node in the linked list.\n If index equals to the length of linked list,\n the node will be appended to the end of linked list.\n If index is greater than the length, the node will not be inserted.\n :type index: int\n :type val: int\n :rtype: void\n \"\"\"\n if 0 <= index <= self.__size // 2:\n self.__add(self.__forward(0, index, self.__head.next).prev, val)\n elif self.__size // 2 < index <= self.__size:\n self.__add(self.__backward(self.__size, index, self.__tail).prev, val)\n\n def deleteAtIndex(self, index):\n \"\"\"\n Delete the index-th node in the linked list, if the index is valid.\n :type index: int\n :rtype: void\n \"\"\"\n if 0 <= index <= self.__size // 2:\n self.__remove(self.__forward(0, index, self.__head.next))\n elif self.__size // 2 < index < self.__size:\n self.__remove(self.__backward(self.__size, index, self.__tail))\n\n def __add(self, preNode, val):\n node = Node(val)\n node.prev = preNode\n node.next = preNode.next\n node.prev.next = node.next.prev = node\n self.__size += 1\n \n def __remove(self, node):\n node.prev.next = node.next\n node.next.prev = node.prev\n self.__size -= 1\n \n def __forward(self, start, end, curr):\n while start != end:\n start += 1\n curr = curr.next\n return curr\n \n def __backward(self, start, end, curr):\n while start != end:\n start -= 1\n curr = curr.prev\n return curr\n\n\n\n"}} diff --git a/cp/cp-10186.jsonl b/cp/cp-10186.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cdeea55c1f9ec0ee1511f53e7deafc6d900ee7fb --- /dev/null +++ b/cp/cp-10186.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10186", "name": "LeetCode 0710: Random Pick With Blacklist"} +{"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: Random Pick with Blacklist (Difficulty: Hard)\nTags: Array, Hash Table, Math, Binary Search, Sorting, Randomized\n\nYou are given an integer n and an array of unique integers blacklist. Design an algorithm to pick a random integer in the range [0, n - 1] that is not in blacklist. Any integer that is in the mentioned range and not in blacklist should be equally likely to be returned.\nOptimize your algorithm such that it minimizes the number of calls to the built-in random function of your language.\nImplement the Solution class:\n\nExample 1:\nInput\n[\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n[[7, [2, 3, 5]], [], [], [], [], [], [], []]\nOutput\n[null, 0, 4, 1, 6, 1, 0, 4]\n\nExplanation\nSolution solution = new Solution(7, [2, 3, 5]);\nsolution.pick(); // return 0, any integer from [0,1,4,6] should be ok. Note that for every call of pick,\n // 0, 1, 4, and 6 must be equally likely to be returned (i.e., with probability 1/4).\nsolution.pick(); // return 4\nsolution.pick(); // return 1\nsolution.pick(); // return 6\nsolution.pick(); // return 1\nsolution.pick(); // return 0\nsolution.pick(); // return 4\n\nConstraints:\n- 1 <= n <= 10^9\n- 0 <= blacklist.length <= min(105, n - 1)\n- 0 <= blacklist[i] < n\n- All the values of blacklist are unique.\n- At most 2 * 10^4 calls will be made to pick."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(b)\n# pick: O(1)\n# Space: O(b)\n\nimport random\n\n\nclass Solution(object):\n \n def __init__(self, N, blacklist):\n \"\"\"\n :type N: int\n :type blacklist: List[int]\n \"\"\"\n self.__n = N-len(blacklist)\n self.__lookup = {}\n white = iter(set(range(self.__n, N))-set(blacklist))\n for black in blacklist:\n if black < self.__n:\n self.__lookup[black] = next(white)\n \n \n def pick(self):\n \"\"\"\n :rtype: int\n \"\"\"\n index = random.randint(0, self.__n-1)\n return self.__lookup[index] if index in self.__lookup else index\n\n\n# Time: ctor: O(blogb)\n# pick: O(logb)\n# Space: O(b)\nimport random\n\nclass Solution2(object):\n \n def __init__(self, N, blacklist):\n \"\"\"\n :type N: int\n :type blacklist: List[int]\n \"\"\"\n self.__n = N-len(blacklist)\n blacklist.sort()\n self.__blacklist = blacklist\n \n def pick(self):\n \"\"\"\n :rtype: int\n \"\"\"\n index = random.randint(0, self.__n-1)\n left, right = 0, len(self.__blacklist)-1\n while left <= right:\n mid = left+(right-left)//2\n if index+mid < self.__blacklist[mid]:\n right = mid-1\n else:\n left = mid+1\n return index+left\n\n\n\n"}} diff --git a/cp/cp-10188.jsonl b/cp/cp-10188.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f4435374a23f883d424dbf24c2ce3242ef00a18d --- /dev/null +++ b/cp/cp-10188.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10188", "name": "LeetCode 0712: Minimum Ascii Delete Sum For Two Strings"} +{"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: Minimum ASCII Delete Sum for Two Strings (Difficulty: Medium)\nTags: String, Dynamic Programming\n\nGiven two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.\n\nExample 1:\nInput: s1 = \"sea\", s2 = \"eat\"\nOutput: 231\nExplanation: Deleting \"s\" from \"sea\" adds the ASCII value of \"s\" (115) to the sum.\nDeleting \"t\" from \"eat\" adds 116 to the sum.\nAt the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.\n\nExample 2:\nInput: s1 = \"delete\", s2 = \"leet\"\nOutput: 403\nExplanation: Deleting \"dee\" from \"delete\" to turn the string into \"let\",\nadds 100[d] + 101[e] + 101[e] to the sum.\nDeleting \"e\" from \"leet\" adds 101[e] to the sum.\nAt the end, both strings are equal to \"let\", and the answer is 100+101+101+101 = 403.\nIf instead we turned both strings into \"lee\" or \"eet\", we would get answers of 433 or 417, which are higher.\n\nConstraints:\n- 1 <= s1.length, s2.length <= 1000\n- s1 and s2 consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(n)\n\nclass Solution(object):\n def minimumDeleteSum(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: int\n \"\"\"\n dp = [[0] * (len(s2)+1) for _ in range(2)]\n for j in range(len(s2)):\n dp[0][j+1] = dp[0][j] + ord(s2[j])\n\n for i in range(len(s1)):\n dp[(i+1)%2][0] = dp[i%2][0] + ord(s1[i])\n for j in range(len(s2)):\n if s1[i] == s2[j]:\n dp[(i+1)%2][j+1] = dp[i%2][j]\n else:\n dp[(i+1)%2][j+1] = min(dp[i%2][j+1] + ord(s1[i]), \\\n dp[(i+1)%2][j] + ord(s2[j]))\n\n return dp[len(s1)%2][-1]\n\n\n# Time: O(m * n)\n# Space: O(m * n)\nclass Solution2(object):\n def minimumDeleteSum(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: int\n \"\"\"\n dp = [[0] * (len(s2)+1) for _ in range(len(s1)+1)]\n for i in range(len(s1)):\n dp[i+1][0] = dp[i][0] + ord(s1[i])\n for j in range(len(s2)):\n dp[0][j+1] = dp[0][j] + ord(s2[j])\n\n for i in range(len(s1)):\n for j in range(len(s2)):\n if s1[i] == s2[j]:\n dp[i+1][j+1] = dp[i][j]\n else:\n dp[i+1][j+1] = min(dp[i][j+1] + ord(s1[i]), \\\n dp[i+1][j] + ord(s2[j]))\n\n return dp[-1][-1]\n\n"}} diff --git a/cp/cp-10189.jsonl b/cp/cp-10189.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dbe0c20c4fa232915189848cf055747b60222d2b --- /dev/null +++ b/cp/cp-10189.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10189", "name": "LeetCode 0713: Subarray Product Less Than K"} +{"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: Subarray Product Less Than K (Difficulty: Medium)\nTags: Array, Binary Search, Sliding Window, Prefix Sum\n\nGiven an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.\n\nExample 1:\nInput: nums = [10,5,2,6], k = 100\nOutput: 8\nExplanation: The 8 subarrays that have product less than 100 are:\n[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]\nNote that [10, 5, 2] is not included as the product of 100 is not strictly less than k.\n\nExample 2:\nInput: nums = [1,2,3], k = 0\nOutput: 0\n\nConstraints:\n- 1 <= nums.length <= 3 * 10^4\n- 1 <= nums[i] <= 1000\n- 0 <= k <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def numSubarrayProductLessThanK(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n if k <= 1: return 0\n result, start, prod = 0, 0, 1\n for i, num in enumerate(nums):\n prod *= num\n while prod >= k:\n prod /= nums[start]\n start += 1\n result += i-start+1\n return result\n\n\n"}} diff --git a/cp/cp-10190.jsonl b/cp/cp-10190.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd5d161d457b1430086a1ba5cfcea88f9576322e --- /dev/null +++ b/cp/cp-10190.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10190", "name": "LeetCode 0714: Best Time To Buy And Sell Stock With Transaction Fee"} +{"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: Best Time to Buy and Sell Stock with Transaction Fee (Difficulty: Medium)\nTags: Array, Dynamic Programming, Greedy\n\nYou are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.\nFind the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.\nNote:\n\nExample 1:\nInput: prices = [1,3,2,8,4,9], fee = 2\nOutput: 8\nExplanation: The maximum profit can be achieved by:\n- Buying at prices[0] = 1\n- Selling at prices[3] = 8\n- Buying at prices[4] = 4\n- Selling at prices[5] = 9\nThe total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.\n\nExample 2:\nInput: prices = [1,3,7,5,10,3], fee = 3\nOutput: 6\n\nConstraints:\n- 1 <= prices.length <= 5 * 10^4\n- 1 <= prices[i] < 5 * 10^4\n- 0 <= fee < 5 * 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n\nclass Solution(object):\n def maxProfit(self, prices, fee):\n \"\"\"\n :type prices: List[int]\n :type fee: int\n :rtype: int\n \"\"\"\n cash, hold = 0, -prices[0]\n for i in range(1, len(prices)):\n cash = max(cash, hold+prices[i]-fee)\n hold = max(hold, cash-prices[i])\n return cash\n\n"}} diff --git a/cp/cp-10191.jsonl b/cp/cp-10191.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..134413fe32c1f94b7a858290e78f959bedaa1904 --- /dev/null +++ b/cp/cp-10191.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10191", "name": "LeetCode 0715: Range Module"} +{"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: Range Module (Difficulty: Hard)\nTags: Design, Segment Tree, Ordered Set\n\nA Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them.\nA half-open interval [left, right) denotes all the real numbers x where left <= x < right.\nImplement the RangeModule class:\n\nExample 1:\nInput\n[\"RangeModule\", \"addRange\", \"removeRange\", \"queryRange\", \"queryRange\", \"queryRange\"]\n[[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]]\nOutput\n[null, null, null, true, false, true]\n\nExplanation\nRangeModule rangeModule = new RangeModule();\nrangeModule.addRange(10, 20);\nrangeModule.removeRange(14, 16);\nrangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked)\nrangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)\nrangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation)\n\nConstraints:\n- 1 <= left < right <= 10^9\n- At most 104 calls will be made to addRange, queryRange, and removeRange."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: addRange: O(n)\n# removeRange: O(n)\n# queryRange: O(logn)\n# Space: O(n)\n\nimport bisect\n\n\nclass RangeModule(object):\n\n def __init__(self):\n self.__intervals = []\n\n def addRange(self, left, right):\n \"\"\"\n :type left: int\n :type right: int\n :rtype: void\n \"\"\"\n tmp = []\n i = 0\n for interval in self.__intervals:\n if right < interval[0]:\n tmp.append((left, right))\n break\n elif interval[1] < left:\n tmp.append(interval)\n else:\n left = min(left, interval[0])\n right = max(right, interval[1])\n i += 1\n if i == len(self.__intervals):\n tmp.append((left, right))\n while i < len(self.__intervals):\n tmp.append(self.__intervals[i])\n i += 1\n self.__intervals = tmp\n\n def queryRange(self, left, right):\n \"\"\"\n :type left: int\n :type right: int\n :rtype: bool\n \"\"\"\n i = bisect.bisect_left(self.__intervals, (left, float(\"inf\")))\n if i: i -= 1\n return bool(self.__intervals) and \\\n self.__intervals[i][0] <= left and \\\n right <= self.__intervals[i][1]\n\n def removeRange(self, left, right):\n \"\"\"\n :type left: int\n :type right: int\n :rtype: void\n \"\"\"\n tmp = []\n for interval in self.__intervals:\n if interval[1] <= left or interval[0] >= right:\n tmp.append(interval)\n else:\n if interval[0] < left:\n tmp.append((interval[0], left))\n if right < interval[1]:\n tmp.append((right, interval[1]))\n self.__intervals = tmp\n\n\n\n"}} diff --git a/cp/cp-10193.jsonl b/cp/cp-10193.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9c561bddfc518bee45bb071df138234c5fa6748f --- /dev/null +++ b/cp/cp-10193.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10193", "name": "LeetCode 0717: 1 Bit And 2 Bit Characters"} +{"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: 1-bit and 2-bit Characters (Difficulty: Easy)\nTags: Array\n\nWe have two special characters:\nGiven a binary array bits that ends with 0, return true if the last character must be a one-bit character.\n\nExample 1:\nInput: bits = [1,0,0]\nOutput: true\nExplanation: The only way to decode it is two-bit character and one-bit character.\nSo the last character is one-bit character.\n\nExample 2:\nInput: bits = [1,1,1,0]\nOutput: false\nExplanation: The only way to decode it is two-bit character and two-bit character.\nSo the last character is not one-bit character.\n\nConstraints:\n- 1 <= bits.length <= 1000\n- bits[i] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n\nclass Solution(object):\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n parity = 0\n for i in reversed(range(len(bits)-1)):\n if bits[i] == 0:\n break\n parity ^= bits[i]\n return parity == 0\n\n"}} diff --git a/cp/cp-10194.jsonl b/cp/cp-10194.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cc96fc7f4fdfe5449d9baf3f73e3fec9a592aed0 --- /dev/null +++ b/cp/cp-10194.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10194", "name": "LeetCode 0718: Maximum Length Of Repeated Subarray"} +{"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 Repeated Subarray (Difficulty: Medium)\nTags: Array, Binary Search, Dynamic Programming, Sliding Window, Rolling Hash, Hash Function\n\nGiven two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.\n\nExample 1:\nInput: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]\nOutput: 3\nExplanation: The repeated subarray with maximum length is [3,2,1].\n\nExample 2:\nInput: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]\nOutput: 5\nExplanation: The repeated subarray with maximum length is [0,0,0,0,0].\n\nConstraints:\n- 1 <= nums1.length, nums2.length <= 1000\n- 0 <= nums1[i], nums2[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(min(m, n))\n\nimport collections\n\n\nclass Solution(object):\n def findLength(self, A, B):\n \"\"\"\n :type A: List[int]\n :type B: List[int]\n :rtype: int\n \"\"\"\n if len(A) < len(B): return self.findLength(B, A)\n result = 0\n dp = [[0] * (len(B)+1) for _ in range(2)]\n for i in range(len(A)):\n for j in range(len(B)):\n if A[i] == B[j]:\n dp[(i+1)%2][j+1] = dp[i%2][j]+1\n else:\n dp[(i+1)%2][j+1] = 0\n result = max(result, max(dp[(i+1)%2]))\n return result\n\n\n# Time: O(m * n * log(min(m, n)))\n# Space: O(min(m, n))\n# Binary search + rolling hash solution (226 ms)\nclass Solution2(object):\n def findLength(self, A, B):\n \"\"\"\n :type A: List[int]\n :type B: List[int]\n :rtype: int\n \"\"\"\n if len(A) > len(B): return self.findLength(B, A)\n M, p = 10**9+7, 113\n p_inv = pow(p, M-2, M)\n def check(guess):\n def rolling_hashes(source, length):\n if length == 0:\n yield 0, 0\n return\n\n val, power = 0, 1\n for i, x in enumerate(source):\n val = (val + x*power) % M\n if i < length - 1:\n power = (power*p) % M\n else:\n yield val, i-(length-1)\n val = (val-source[i-(length-1)])*p_inv % M\n\n hashes = collections.defaultdict(list)\n for hash_val, i in rolling_hashes(A, guess):\n hashes[hash_val].append(i)\n for hash_val, j in rolling_hashes(B, guess):\n if any(A[i:i+guess] == B[j:j+guess] for i in hashes[hash_val]):\n return True\n return False\n\n left, right = 0, min(len(A), len(B)) + 1\n while left < right:\n mid = left + (right-left)/2\n if not check(mid): # find the min idx such that check(idx) == false\n right = mid\n else:\n left = mid+1\n return left-1\n\n\n# Time: O(m * n * min(m, n) * log(min(m, n)))\n# Space: O(min(m^2, n^2))\n# Binary search (122 ms)\nclass Solution3(object):\n def findLength(self, A, B):\n \"\"\"\n :type A: List[int]\n :type B: List[int]\n :rtype: int\n \"\"\"\n if len(A) > len(B): return self.findLength(B, A)\n\n def check(length):\n lookup = set(A[i:i+length] \\\n for i in range(len(A)-length+1))\n return any(B[j:j+length] in lookup \\\n for j in range(len(B)-length+1))\n\n A = ''.join(map(chr, A))\n B = ''.join(map(chr, B))\n left, right = 0, min(len(A), len(B)) + 1\n while left < right:\n mid = left + (right-left)/2\n if not check(mid): # find the min idx such that check(idx) == false\n right = mid\n else:\n left = mid+1\n return left-1\n\n"}} diff --git a/cp/cp-10195.jsonl b/cp/cp-10195.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fad0e0435719c79d6689f82253793e1fb37bda3c --- /dev/null +++ b/cp/cp-10195.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10195", "name": "LeetCode 0719: Find K Th Smallest Pair Distance"} +{"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-th Smallest Pair Distance (Difficulty: Hard)\nTags: Array, Two Pointers, Binary Search, Sorting\n\nThe distance of a pair of integers a and b is defined as the absolute difference between a and b.\nGiven an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.\n\nExample 1:\nInput: nums = [1,3,1], k = 1\nOutput: 0\nExplanation: Here are all the pairs:\n(1,3) -> 2\n(1,1) -> 0\n(3,1) -> 2\nThen the 1st smallest distance pair is (1,1), and its distance is 0.\n\nExample 2:\nInput: nums = [1,1,1], k = 2\nOutput: 0\n\nExample 3:\nInput: nums = [1,6,1], k = 3\nOutput: 5\n\nConstraints:\n- n == nums.length\n- 2 <= n <= 10^4\n- 0 <= nums[i] <= 10^6\n- 1 <= k <= n * (n - 1) / 2"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn + nlogw), n = len(nums), w = max(nums)-min(nums)\n# Space: O(1)\n\nclass Solution(object):\n def smallestDistancePair(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n # Sliding window solution\n def possible(guess, nums, k):\n count, left = 0, 0\n for right, num in enumerate(nums):\n while num-nums[left] > guess:\n left += 1\n count += right-left\n return count >= k\n\n nums.sort()\n left, right = 0, nums[-1]-nums[0]+1\n while left < right:\n mid = left + (right-left)/2\n if possible(mid, nums, k):\n right = mid\n else:\n left = mid+1\n return left\n\n"}} diff --git a/cp/cp-10196.jsonl b/cp/cp-10196.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1787419e6f1508b951b26f595bcb40b981715c3a --- /dev/null +++ b/cp/cp-10196.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10196", "name": "LeetCode 0720: Longest Word In 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: Longest Word in Dictionary (Difficulty: Medium)\nTags: Array, Hash Table, String, Trie, Sorting\n\nGiven an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.\nIf there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.\nNote that the word should be built from left to right with each additional character being added to the end of a previous word.\n\nExample 1:\nInput: words = [\"w\",\"wo\",\"wor\",\"worl\",\"world\"]\nOutput: \"world\"\nExplanation: The word \"world\" can be built one character at a time by \"w\", \"wo\", \"wor\", and \"worl\".\n\nExample 2:\nInput: words = [\"a\",\"banana\",\"app\",\"appl\",\"ap\",\"apply\",\"apple\"]\nOutput: \"apple\"\nExplanation: Both \"apply\" and \"apple\" can be built from other words in the dictionary. However, \"apple\" is lexicographically smaller than \"apply\".\n\nConstraints:\n- 1 <= words.length <= 1000\n- 1 <= words[i].length <= 30\n- words[i] consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n), n is the total sum of the lengths of words\n# Space: O(t), t is the number of nodes in trie\n\nfrom collections import defaultdict\nfrom operator import getitem\n\n\nclass Solution(object):\n def longestWord(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: str\n \"\"\"\n _trie = lambda: defaultdict(_trie)\n trie = _trie()\n for i, word in enumerate(words):\n reduce(getitem, word, trie)[\"_end\"] = i\n\n # DFS\n stack = trie.values()\n result = \"\"\n while stack:\n curr = stack.pop()\n if \"_end\" in curr:\n word = words[curr[\"_end\"]]\n if len(word) > len(result) or (len(word) == len(result) and word < result):\n result = word\n stack += [curr[letter] for letter in curr if letter != \"_end\"]\n return result\n\n"}} diff --git a/cp/cp-10197.jsonl b/cp/cp-10197.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ce74fc8b49a4cf9a4d51b0224fe6b02fda159154 --- /dev/null +++ b/cp/cp-10197.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10197", "name": "LeetCode 0721: Accounts Merge"} +{"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: Accounts Merge (Difficulty: Medium)\nTags: Array, Hash Table, String, Depth-First Search, Breadth-First Search, Union Find, Sorting\n\nGiven a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.\nNow, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.\nAfter merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.\n\nExample 1:\nInput: accounts = [[\"John\",\"johnsmith@mail.com\",\"john_newyork@mail.com\"],[\"John\",\"johnsmith@mail.com\",\"john00@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\nOutput: [[\"John\",\"john00@mail.com\",\"john_newyork@mail.com\",\"johnsmith@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\nExplanation:\nThe first and second John's are the same person as they have the common email \"johnsmith@mail.com\".\nThe third John and Mary are different people as none of their email addresses are used by other accounts.\nWe could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], \n['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.\n\nExample 2:\nInput: accounts = [[\"Gabe\",\"Gabe0@m.co\",\"Gabe3@m.co\",\"Gabe1@m.co\"],[\"Kevin\",\"Kevin3@m.co\",\"Kevin5@m.co\",\"Kevin0@m.co\"],[\"Ethan\",\"Ethan5@m.co\",\"Ethan4@m.co\",\"Ethan0@m.co\"],[\"Hanzo\",\"Hanzo3@m.co\",\"Hanzo1@m.co\",\"Hanzo0@m.co\"],[\"Fern\",\"Fern5@m.co\",\"Fern1@m.co\",\"Fern0@m.co\"]]\nOutput: [[\"Ethan\",\"Ethan0@m.co\",\"Ethan4@m.co\",\"Ethan5@m.co\"],[\"Gabe\",\"Gabe0@m.co\",\"Gabe1@m.co\",\"Gabe3@m.co\"],[\"Hanzo\",\"Hanzo0@m.co\",\"Hanzo1@m.co\",\"Hanzo3@m.co\"],[\"Kevin\",\"Kevin0@m.co\",\"Kevin3@m.co\",\"Kevin5@m.co\"],[\"Fern\",\"Fern0@m.co\",\"Fern1@m.co\",\"Fern5@m.co\"]]\n\nConstraints:\n- 1 <= accounts.length <= 1000\n- 2 <= accounts[i].length <= 10\n- 1 <= accounts[i][j].length <= 30\n- accounts[i][0] consists of English letters.\n- accounts[i][j] (for j > 0) is a valid email."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn), n is the number of total emails,\n# and the max length ofemail is 320, p.s. {64}@{255}\n# Space: O(n)\n\nimport collections\n\n\nclass UnionFind(object):\n def __init__(self):\n self.set = []\n\n def get_id(self):\n self.set.append(len(self.set))\n return len(self.set)-1\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root != y_root:\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n\n\nclass Solution(object):\n def accountsMerge(self, accounts):\n \"\"\"\n :type accounts: List[List[str]]\n :rtype: List[List[str]]\n \"\"\"\n union_find = UnionFind()\n email_to_name = {}\n email_to_id = {}\n for account in accounts:\n name = account[0]\n for i in range(1, len(account)):\n if account[i] not in email_to_id:\n email_to_name[account[i]] = name\n email_to_id[account[i]] = union_find.get_id()\n union_find.union_set(email_to_id[account[1]],\n email_to_id[account[i]])\n\n result = collections.defaultdict(list)\n for email in email_to_name.keys():\n result[union_find.find_set(email_to_id[email])].append(email)\n for emails in result.values():\n emails.sort()\n return [[email_to_name[emails[0]]] + emails\n for emails in result.values()]\n\n"}} diff --git a/cp/cp-10198.jsonl b/cp/cp-10198.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..89a07ca7d4fccb3765a4e16903734e597ee718a1 --- /dev/null +++ b/cp/cp-10198.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10198", "name": "LeetCode 0722: Remove Comments"} +{"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: Remove Comments (Difficulty: Medium)\nTags: Array, String\n\nGiven a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith line of the source code. This represents the result of splitting the original source code string by the newline character '\\n'.\nIn C++, there are two types of comments, line comments, and block comments.\nThe first effective comment takes precedence over others.\nIf a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.\nThere will be no control characters, single quote, or double quote characters.\nAlso, nothing else such as defines or macros will interfere with the comments.\nIt is guaranteed that every open block comment will eventually be closed, so \"/*\" outside of a line or block comment always starts a new comment.\nFinally, implicit newline characters can be deleted by block comments. Please see the examples below for details.\nAfter removing the comments from the source code, return the source code in the same format.\n\nExample 1:\nInput: source = [\"/*Test program */\", \"int main()\", \"{ \", \" // variable declaration \", \"int a, b, c;\", \"/* This is a test\", \" multiline \", \" comment for \", \" testing */\", \"a = b + c;\", \"}\"]\nOutput: [\"int main()\",\"{ \",\" \",\"int a, b, c;\",\"a = b + c;\",\"}\"]\nExplanation: The line by line code is visualized as below:\n/*Test program */\nint main()\n{ \n // variable declaration \nint a, b, c;\n/* This is a test\n multiline \n comment for \n testing */\na = b + c;\n}\nThe string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.\nThe line by line output code is visualized as below:\nint main()\n{ \n \nint a, b, c;\na = b + c;\n}\n\nExample 2:\nInput: source = [\"a/*comment\", \"line\", \"more_comment*/b\"]\nOutput: [\"ab\"]\nExplanation: The original source string is \"a/*comment\\nline\\nmore_comment*/b\", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string \"ab\", which when delimited by newline characters becomes [\"ab\"].\n\nConstraints:\n- 1 <= source.length <= 100\n- 0 <= source[i].length <= 80\n- source[i] consists of printable ASCII characters.\n- Every open block comment is eventually closed.\n- There are no single-quote or double-quote in the input."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n), n is the length of the source\n# Space: O(k), k is the max length of a line\n\nclass Solution(object):\n def removeComments(self, source):\n \"\"\"\n :type source: List[str]\n :rtype: List[str]\n \"\"\"\n in_block = False\n result, newline = [], []\n for line in source:\n i = 0\n while i < len(line):\n if not in_block and i+1 < len(line) and line[i:i+2] == '/*':\n in_block = True\n i += 1\n elif in_block and i+1 < len(line) and line[i:i+2] == '*/':\n in_block = False\n i += 1\n elif not in_block and i+1 < len(line) and line[i:i+2] == '//':\n break\n elif not in_block:\n newline.append(line[i])\n i += 1\n if newline and not in_block:\n result.append(\"\".join(newline))\n newline = []\n return result\n\n"}} diff --git a/cp/cp-10200.jsonl b/cp/cp-10200.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..163e8b2142f659f8198e84fb81bb8acee7c37fc9 --- /dev/null +++ b/cp/cp-10200.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10200", "name": "LeetCode 0724: Find Pivot Index"} +{"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 Pivot Index (Difficulty: Easy)\nTags: Array, Prefix Sum\n\nGiven an array of integers nums, calculate the pivot index of this array.\nThe pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.\nIf the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.\nReturn the leftmost pivot index. If no such index exists, return -1.\nNote: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/\n\nExample 1:\nInput: nums = [1,7,3,6,5,6]\nOutput: 3\nExplanation:\nThe pivot index is 3.\nLeft sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\nRight sum = nums[4] + nums[5] = 5 + 6 = 11\n\nExample 2:\nInput: nums = [1,2,3]\nOutput: -1\nExplanation:\nThere is no index that satisfies the conditions in the problem statement.\n\nExample 3:\nInput: nums = [2,1,-1]\nOutput: 0\nExplanation:\nThe pivot index is 0.\nLeft sum = 0 (no elements to the left of index 0)\nRight sum = nums[1] + nums[2] = 1 + -1 = 0\n\nConstraints:\n- 1 <= 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 pivotIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n total = sum(nums)\n left_sum = 0\n for i, num in enumerate(nums):\n if left_sum == (total-left_sum-num):\n return i\n left_sum += num\n return -1\n\n\n"}} diff --git a/cp/cp-10201.jsonl b/cp/cp-10201.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9b3f95d846bfac05939990794396652ae14ec99b --- /dev/null +++ b/cp/cp-10201.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10201", "name": "LeetCode 0725: Split Linked List In Parts"} +{"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 Linked List in Parts (Difficulty: Medium)\nTags: Linked List\n\nGiven the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.\nThe length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.\nThe parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.\nReturn an array of the k parts.\n\nExample 1:\nInput: head = [1,2,3], k = 5\nOutput: [[1],[2],[3],[],[]]\nExplanation:\nThe first element output[0] has output[0].val = 1, output[0].next = null.\nThe last element output[4] is null, but its string representation as a ListNode is [].\n\nExample 2:\nInput: head = [1,2,3,4,5,6,7,8,9,10], k = 3\nOutput: [[1,2,3,4],[5,6,7],[8,9,10]]\nExplanation:\nThe input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.\n\nConstraints:\n- The number of nodes in the list is in the range [0, 1000].\n- 0 <= Node.val <= 1000\n- 1 <= k <= 50"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + k)\n# Space: O(1)\n\nclass Solution(object):\n def splitListToParts(self, root, k):\n \"\"\"\n :type root: ListNode\n :type k: int\n :rtype: List[ListNode]\n \"\"\"\n n = 0\n curr = root\n while curr:\n curr = curr.next\n n += 1\n width, remainder = divmod(n, k)\n\n result = []\n curr = root\n for i in range(k):\n head = curr\n for j in range(width-1+int(i < remainder)):\n if curr:\n curr = curr.next\n if curr:\n curr.next, curr = None, curr.next\n result.append(head)\n return result\n\n"}} diff --git a/cp/cp-10202.jsonl b/cp/cp-10202.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..804f29d64b1a3f1e8dbcea1737a0c19a93e4cc06 --- /dev/null +++ b/cp/cp-10202.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10202", "name": "LeetCode 0726: Number Of Atoms"} +{"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 Atoms (Difficulty: Hard)\nTags: Hash Table, String, Stack, Sorting\n\nGiven a string formula representing a chemical formula, return the count of each atom.\nThe atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.\nOne or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow.\nTwo formulas are concatenated together to produce another formula.\nA formula placed in parentheses, and a count (optionally added) is also a formula.\nReturn the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.\nThe test cases are generated so that all the values in the output fit in a 32-bit integer.\n\nExample 1:\nInput: formula = \"H2O\"\nOutput: \"H2O\"\nExplanation: The count of elements are {'H': 2, 'O': 1}.\n\nExample 2:\nInput: formula = \"Mg(OH)2\"\nOutput: \"H2MgO2\"\nExplanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.\n\nExample 3:\nInput: formula = \"K4(ON(SO3)2)2\"\nOutput: \"K4N2O14S4\"\nExplanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.\n\nConstraints:\n- 1 <= formula.length <= 1000\n- formula consists of English letters, digits, '(', and ')'.\n- formula is always valid."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\nimport re\n\n\nclass Solution(object):\n def countOfAtoms(self, formula):\n \"\"\"\n :type formula: str\n :rtype: str\n \"\"\"\n parse = re.findall(r\"([A-Z][a-z]*)(\\d*)|(\\()|(\\))(\\d*)\", formula)\n stk = [collections.Counter()]\n for name, m1, left_open, right_open, m2 in parse:\n if name:\n stk[-1][name] += int(m1 or 1)\n if left_open:\n stk.append(collections.Counter())\n if right_open:\n top = stk.pop()\n for k, v in top.iteritems():\n stk[-1][k] += v * int(m2 or 1)\n\n return \"\".join(name + (str(stk[-1][name]) if stk[-1][name] > 1 else '') \\\n for name in sorted(stk[-1]))\n\n"}} diff --git a/cp/cp-10204.jsonl b/cp/cp-10204.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a2f9ecfa3373bec702c9933bf4c3d0c0772a09c8 --- /dev/null +++ b/cp/cp-10204.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10204", "name": "LeetCode 0728: Self Dividing 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: Self Dividing Numbers (Difficulty: Easy)\nTags: Math\n\nA self-dividing number is a number that is divisible by every digit it contains.\nA self-dividing number is not allowed to contain the digit zero.\nGiven two integers left and right, return a list of all the self-dividing numbers in the range [left, right] (both inclusive).\n\nExample 1:\nInput: left = 1, right = 22\nOutput: [1,2,3,4,5,6,7,8,9,11,12,15,22]\n\nExample 2:\nInput: left = 47, right = 85\nOutput: [48,55,66,77]\n\nConstraints:\n- 1 <= left <= right <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogr) = O(n)\n# Space: O(logr) = O(1)\n\nclass Solution(object):\n def selfDividingNumbers(self, left, right):\n \"\"\"\n :type left: int\n :type right: int\n :rtype: List[int]\n \"\"\"\n def isDividingNumber(num):\n n = num\n while n > 0:\n n, r = divmod(n, 10)\n if r == 0 or (num%r) != 0:\n return False\n return True\n \n return [num for num in range(left, right+1) if isDividingNumber(num)]\n\n\n# Time: O(nlogr) = O(n)\n# Space: O(logr) = O(1)\nimport itertools\n\n\nclass Solution2(object):\n def selfDividingNumbers(self, left, right):\n \"\"\"\n :type left: int\n :type right: int\n :rtype: List[int]\n \"\"\"\n return [num for num in range(left, right+1) \\\n if not any(itertools.imap(lambda x: int(x) == 0 or num%int(x) != 0, str(num)))]\n"}} diff --git a/cp/cp-10205.jsonl b/cp/cp-10205.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..029efeb9e34fc6c0906ecc53f78f0298092af0e8 --- /dev/null +++ b/cp/cp-10205.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10205", "name": "LeetCode 0729: My Calendar 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: My Calendar I (Difficulty: Medium)\nTags: Array, Binary Search, Design, Segment Tree, Ordered Set\n\nYou are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking.\nA double booking happens when two events have some non-empty intersection (i.e., some moment is common to both events.).\nThe event can be represented as a pair of integers startTime and endTime that represents a booking on the half-open interval [startTime, endTime), the range of real numbers x such that startTime <= x < endTime.\nImplement the MyCalendar class:\n\nExample 1:\nInput\n[\"MyCalendar\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [15, 25], [20, 30]]\nOutput\n[null, true, false, true]\n\nExplanation\nMyCalendar myCalendar = new MyCalendar();\nmyCalendar.book(10, 20); // return True\nmyCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.\nmyCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.\n\nConstraints:\n- 0 <= start < end <= 10^9\n- At most 1000 calls will be made to book."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn) on average, O(n^2) on worst case\n# Space: O(n)\n\nclass Node(object):\n def __init__(self, start, end):\n self.__start = start\n self.__end = end\n self.__left = None\n self.__right = None\n\n\n def insert(self, node):\n if node.__start >= self.__end:\n if not self.__right:\n self.__right = node\n return True\n return self.__right.insert(node)\n elif node.__end <= self.__start:\n if not self.__left:\n self.__left = node\n return True\n return self.__left.insert(node)\n else:\n return False\n\n\nclass MyCalendar(object):\n def __init__(self):\n self.__root = None\n\n\n def book(self, start, end):\n \"\"\"\n :type start: int\n :type end: int\n :rtype: bool\n \"\"\"\n if self.__root is None:\n self.__root = Node(start, end)\n return True\n return self.root.insert(Node(start, end))\n\n\n# Time: O(n^2)\n# Space: O(n)\nclass MyCalendar2(object):\n\n def __init__(self):\n self.__calendar = []\n\n\n def book(self, start, end):\n \"\"\"\n :type start: int\n :type end: int\n :rtype: bool\n \"\"\"\n for i, j in self.__calendar:\n if start < j and end > i:\n return False\n self.__calendar.append((start, end))\n return True\n\n\n\n"}} diff --git a/cp/cp-10206.jsonl b/cp/cp-10206.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f510f8a3533895a1785942973ad0dcd9eab86b80 --- /dev/null +++ b/cp/cp-10206.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10206", "name": "LeetCode 0730: Count Different Palindromic 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: Count Different Palindromic Subsequences (Difficulty: Hard)\nTags: String, Dynamic Programming\n\nGiven a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 109 + 7.\nA subsequence of a string is obtained by deleting zero or more characters from the string.\nA sequence is palindromic if it is equal to the sequence reversed.\nTwo sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi.\n\nExample 1:\nInput: s = \"bccb\"\nOutput: 6\nExplanation: The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.\nNote that 'bcb' is counted only once, even though it occurs twice.\n\nExample 2:\nInput: s = \"abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba\"\nOutput: 104860361\nExplanation: There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7.\n\nConstraints:\n- 1 <= s.length <= 1000\n- s[i] is either 'a', 'b', 'c', or 'd'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2)\n\nclass Solution(object):\n def countPalindromicSubsequences(self, S):\n \"\"\"\n :type S: str\n :rtype: int\n \"\"\"\n def dp(i, j, prv, nxt, lookup):\n if lookup[i][j] is not None:\n return lookup[i][j]\n result = 1\n if i <= j:\n for x in range(4):\n i0 = nxt[i][x]\n j0 = prv[j][x]\n if i <= i0 <= j:\n result = (result + 1) % P\n if None < i0 < j0:\n result = (result + dp(i0+1, j0-1, prv, nxt, lookup)) % P\n result %= P\n lookup[i][j] = result\n return result\n\n prv = [None] * len(S)\n nxt = [None] * len(S)\n\n last = [None] * 4\n for i in range(len(S)):\n last[ord(S[i])-ord('a')] = i\n prv[i] = tuple(last)\n\n last = [None] * 4\n for i in reversed(range(len(S))):\n last[ord(S[i])-ord('a')] = i\n nxt[i] = tuple(last)\n\n P = 10**9 + 7\n lookup = [[None] * len(S) for _ in range(len(S))]\n return dp(0, len(S)-1, prv, nxt, lookup) - 1\n\n"}} diff --git a/cp/cp-10207.jsonl b/cp/cp-10207.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d7e18ea797cc9963a14ab8ca2176854eec64d028 --- /dev/null +++ b/cp/cp-10207.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10207", "name": "LeetCode 0731: My Calendar 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: My Calendar II (Difficulty: Medium)\nTags: Array, Binary Search, Design, Segment Tree, Prefix Sum, Ordered Set\n\nYou are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking.\nA triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).\nThe event can be represented as a pair of integers startTime and endTime that represents a booking on the half-open interval [startTime, endTime), the range of real numbers x such that startTime <= x < endTime.\nImplement the MyCalendarTwo class:\n\nExample 1:\nInput\n[\"MyCalendarTwo\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]\nOutput\n[null, true, true, true, false, true, true]\n\nExplanation\nMyCalendarTwo myCalendarTwo = new MyCalendarTwo();\nmyCalendarTwo.book(10, 20); // return True, The event can be booked. \nmyCalendarTwo.book(50, 60); // return True, The event can be booked. \nmyCalendarTwo.book(10, 40); // return True, The event can be double booked. \nmyCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.\nmyCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.\nmyCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.\n\nConstraints:\n- 0 <= start < end <= 10^9\n- At most 1000 calls will be made to book."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass MyCalendarTwo(object):\n\n def __init__(self):\n self.__overlaps = []\n self.__calendar = []\n\n\n def book(self, start, end):\n \"\"\"\n :type start: int\n :type end: int\n :rtype: bool\n \"\"\"\n for i, j in self.__overlaps:\n if start < j and end > i:\n return False\n for i, j in self.__calendar:\n if start < j and end > i:\n self.__overlaps.append((max(start, i), min(end, j)))\n self.__calendar.append((start, end))\n return True\n\n\n\n"}} diff --git a/cp/cp-10208.jsonl b/cp/cp-10208.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f9718c4b5531b2316f6ae612211498c6d7352a61 --- /dev/null +++ b/cp/cp-10208.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10208", "name": "LeetCode 0732: My Calendar 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: My Calendar III (Difficulty: Hard)\nTags: Binary Search, Design, Segment Tree, Prefix Sum, Ordered Set\n\nA k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)\nYou are given some events [startTime, endTime), after each given event, return an integer k representing the maximum k-booking between all the previous events.\nImplement the MyCalendarThree class:\n\nExample 1:\nInput\n[\"MyCalendarThree\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]\nOutput\n[null, 1, 1, 2, 3, 3, 3]\n\nExplanation\nMyCalendarThree myCalendarThree = new MyCalendarThree();\nmyCalendarThree.book(10, 20); // return 1\nmyCalendarThree.book(50, 60); // return 1\nmyCalendarThree.book(10, 40); // return 2\nmyCalendarThree.book(5, 15); // return 3\nmyCalendarThree.book(5, 10); // return 3\nmyCalendarThree.book(25, 55); // return 3\n\nConstraints:\n- 0 <= startTime < endTime <= 10^9\n- At most 400 calls will be made to book."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn) ~ O(n^2)\n# Space: O(n)\n\nimport bisect\n\n\nclass MyCalendarThree(object):\n\n def __init__(self):\n self.__books = [[-1, 0]]\n self.__count = 0\n\n def book(self, start, end):\n \"\"\"\n :type start: int\n :type end: int\n :rtype: int\n \"\"\"\n i = bisect.bisect_right(self.__books, [start, float(\"inf\")])\n if self.__books[i-1][0] == start:\n i -= 1\n else:\n self.__books.insert(i, [start, self.__books[i-1][1]])\n j = bisect.bisect_right(self.__books, [end, float(\"inf\")])\n if self.__books[j-1][0] == end:\n j -= 1\n else:\n self.__books.insert(j, [end, self.__books[j-1][1]]) \n for k in range(i, j):\n self.__books[k][1] += 1\n self.__count = max(self.__count, self.__books[k][1])\n return self.__count\n\n\n# Time: O(n^2)\n# Space: O(n)\nclass MyCalendarThree2(object):\n\n def __init__(self):\n self.__books = []\n\n\n def book(self, start, end):\n \"\"\"\n :type start: int\n :type end: int\n :rtype: int\n \"\"\"\n i = bisect.bisect_left(self.__books, (start, 1))\n if i < len(self.__books) and self.__books[i][0] == start:\n self.__books[i] = (self.__books[i][0], self.__books[i][1]+1)\n else:\n self.__books.insert(i, (start, 1))\n\n j = bisect.bisect_left(self.__books, (end, 1))\n if j < len(self.__books) and self.__books[j][0] == end:\n self.__books[j] = (self.__books[j][0], self.__books[j][1]-1)\n else:\n self.__books.insert(j, (end, -1))\n\n result, cnt = 0, 0\n for book in self.__books:\n cnt += book[1]\n result = max(result, cnt)\n return result\n\n"}} diff --git a/cp/cp-10209.jsonl b/cp/cp-10209.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3f037e4ed2c215cc3e59ecd70902990a5a7b4273 --- /dev/null +++ b/cp/cp-10209.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10209", "name": "LeetCode 0733: Flood Fill"} +{"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: Flood Fill (Difficulty: Easy)\nTags: Array, Depth-First Search, Breadth-First Search, Matrix\n\nYou are given an image represented by an m x n grid of integers image, where image[i][j] represents the pixel value of the image. You are also given three integers sr, sc, and color. Your task is to perform a flood fill on the image starting from the pixel image[sr][sc].\nTo perform a flood fill:\nReturn the modified image after performing the flood fill.\n\nExample 1:\nInput: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2\nOutput: [[2,2,2],[2,2,0],[2,0,1]]\nExplanation:\n\nFrom the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.\nNote the bottom corner is not colored 2, because it is not horizontally or vertically connected to the starting pixel.\n\nExample 2:\nInput: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0\nOutput: [[0,0,0],[0,0,0]]\nExplanation:\nThe starting pixel is already colored with 0, which is the same as the target color. Therefore, no changes are made to the image.\n\nConstraints:\n- m == image.length\n- n == image[i].length\n- 1 <= m, n <= 50\n- 0 <= image[i][j], color < 216\n- 0 <= sr < m\n- 0 <= sc < n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m * n)\n\nclass Solution(object):\n def floodFill(self, image, sr, sc, newColor):\n \"\"\"\n :type image: List[List[int]]\n :type sr: int\n :type sc: int\n :type newColor: int\n :rtype: List[List[int]]\n \"\"\"\n directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n\n def dfs(image, r, c, newColor, color):\n if not (0 <= r < len(image) and \\\n 0 <= c < len(image[0]) and \\\n image[r][c] == color):\n return\n\n image[r][c] = newColor\n for d in directions:\n dfs(image, r+d[0], c+d[1], newColor, color)\n\n color = image[sr][sc]\n if color == newColor: return image\n dfs(image, sr, sc, newColor, color)\n return image\n\n"}} diff --git a/cp/cp-10211.jsonl b/cp/cp-10211.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e9108a429c1381c00440ea3cfd55a68c11c95bd3 --- /dev/null +++ b/cp/cp-10211.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10211", "name": "LeetCode 0735: Asteroid Collision"} +{"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: Asteroid Collision (Difficulty: Medium)\nTags: Array, Stack, Simulation\n\nWe are given an array asteroids of integers representing asteroids in a row. The indices of the asteriod in the array represent their relative position in space.\nFor each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.\nFind out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.\n\nExample 1:\nInput: asteroids = [5,10,-5]\nOutput: [5,10]\nExplanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.\n\nExample 2:\nInput: asteroids = [8,-8]\nOutput: []\nExplanation: The 8 and -8 collide exploding each other.\n\nExample 3:\nInput: asteroids = [10,2,-5]\nOutput: [10]\nExplanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.\n\nConstraints:\n- 2 <= asteroids.length <= 10^4\n- -1000 <= asteroids[i] <= 1000\n- asteroids[i] != 0"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def asteroidCollision(self, asteroids):\n \"\"\"\n :type asteroids: List[int]\n :rtype: List[int]\n \"\"\"\n result = []\n for x in asteroids:\n if x > 0:\n result.append(x)\n continue\n while result and 0 < result[-1] < -x:\n result.pop()\n if result and 0 < result[-1]:\n if result[-1] == -x:\n result.pop()\n continue\n result.append(x)\n return result\n\n\n# Time: O(n)\n# Space: O(n)\nclass Solution2(object):\n def asteroidCollision(self, asteroids):\n \"\"\"\n :type asteroids: List[int]\n :rtype: List[int]\n \"\"\"\n result = []\n for x in asteroids:\n while result and x < 0 < result[-1]:\n if result[-1] < -x:\n result.pop()\n continue\n elif result[-1] == -x:\n result.pop()\n break\n else:\n result.append(x)\n return result\n"}} diff --git a/cp/cp-10212.jsonl b/cp/cp-10212.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..537e75105e1f7735e00237ccaf2f7c2f70db47a7 --- /dev/null +++ b/cp/cp-10212.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10212", "name": "LeetCode 0736: Parse Lisp Expression"} +{"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: Parse Lisp Expression (Difficulty: Hard)\nTags: Hash Table, String, Stack, Recursion\n\nYou are given a string expression representing a Lisp-like expression to return the integer value of.\nThe syntax for these expressions is given as follows.\n\nExample 1:\nInput: expression = \"(let x 2 (mult x (let x 3 y 4 (add x y))))\"\nOutput: 14\nExplanation: In the expression (add x y), when checking for the value of the variable x,\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\nSince x = 3 is found first, the value of x is 3.\n\nExample 2:\nInput: expression = \"(let x 3 x 2 x)\"\nOutput: 2\nExplanation: Assignment in let statements is processed sequentially.\n\nExample 3:\nInput: expression = \"(let x 1 y 2 x (add x y) (add x y))\"\nOutput: 5\nExplanation: The first (add x y) evaluates as 3, and is assigned to x.\nThe second (add x y) evaluates as 3+2 = 5.\n\nConstraints:\n- 1 <= expression.length <= 2000\n- There are no leading or trailing spaces in expression.\n- All tokens are separated by a single space in expression.\n- The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.\n- The expression is guaranteed to be legal and evaluate to an integer."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2)\n\nclass Solution(object):\n def evaluate(self, expression):\n \"\"\"\n :type expression: str\n :rtype: int\n \"\"\"\n def getval(lookup, x):\n return lookup.get(x, x)\n\n def evaluate(tokens, lookup):\n if tokens[0] in ('add', 'mult'):\n a, b = map(int, map(lambda x: getval(lookup, x), tokens[1:]))\n return str(a+b if tokens[0] == 'add' else a*b)\n for i in range(1, len(tokens)-1, 2):\n if tokens[i+1]:\n lookup[tokens[i]] = getval(lookup, tokens[i+1])\n return getval(lookup, tokens[-1])\n\n tokens, lookup, stk = [''], {}, []\n for c in expression:\n if c == '(':\n if tokens[0] == 'let':\n evaluate(tokens, lookup)\n stk.append((tokens, dict(lookup)))\n tokens = ['']\n elif c == ' ':\n tokens.append('')\n elif c == ')':\n val = evaluate(tokens, lookup)\n tokens, lookup = stk.pop()\n tokens[-1] += val\n else:\n tokens[-1] += c\n return int(tokens[0])\n\n"}} diff --git a/cp/cp-10214.jsonl b/cp/cp-10214.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d4d535b9ae0b6748eb217f2c71be7cfc55329c4d --- /dev/null +++ b/cp/cp-10214.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10214", "name": "LeetCode 0738: Monotone Increasing Digits"} +{"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: Monotone Increasing Digits (Difficulty: Medium)\nTags: Math, Greedy\n\nAn integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.\nGiven an integer n, return the largest number that is less than or equal to n with monotone increasing digits.\n\nExample 1:\nInput: n = 10\nOutput: 9\n\nExample 2:\nInput: n = 1234\nOutput: 1234\n\nExample 3:\nInput: n = 332\nOutput: 299\n\nConstraints:\n- 0 <= n <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn) = O(1)\n# Space: O(logn) = O(1)\n\nclass Solution(object):\n def monotoneIncreasingDigits(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n nums = map(int, list(str(N)))\n leftmost_inverted_idx = len(nums)\n for i in reversed(range(1, len(nums))):\n if nums[i-1] > nums[i]:\n leftmost_inverted_idx = i\n nums[i-1] -= 1\n for i in range(leftmost_inverted_idx, len(nums)):\n nums[i] = 9\n return int(\"\".join(map(str, nums)))\n\n"}} diff --git a/cp/cp-10215.jsonl b/cp/cp-10215.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..069d19148e9a37b229f45a2f985261a0f3d96c8c --- /dev/null +++ b/cp/cp-10215.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10215", "name": "LeetCode 0739: Daily Temperatures"} +{"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: Daily Temperatures (Difficulty: Medium)\nTags: Array, Stack, Monotonic Stack\n\nGiven an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.\n\nExample 1:\nInput: temperatures = [73,74,75,71,69,72,76,73]\nOutput: [1,1,4,2,1,1,0,0]\n\nExample 2:\nInput: temperatures = [30,40,50,60]\nOutput: [1,1,1,0]\n\nExample 3:\nInput: temperatures = [30,60,90]\nOutput: [1,1,0]\n\nConstraints:\n- 1 <= temperatures.length <= 10^5\n- 30 <= temperatures[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def dailyTemperatures(self, temperatures):\n \"\"\"\n :type temperatures: List[int]\n :rtype: List[int]\n \"\"\"\n result = [0] * len(temperatures)\n stk = []\n for i in range(len(temperatures)):\n while stk and \\\n temperatures[stk[-1]] < temperatures[i]:\n idx = stk.pop()\n result[idx] = i-idx\n stk.append(i)\n return result\n\n"}} diff --git a/cp/cp-10216.jsonl b/cp/cp-10216.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..06fa79a995cd7410c90d6df61d964063e128d533 --- /dev/null +++ b/cp/cp-10216.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10216", "name": "LeetCode 0740: Delete And Earn"} +{"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: Delete and Earn (Difficulty: Medium)\nTags: Array, Hash Table, Dynamic Programming\n\nYou are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:\nReturn the maximum number of points you can earn by applying the above operation some number of times.\n\nExample 1:\nInput: nums = [3,4,2]\nOutput: 6\nExplanation: You can perform the following operations:\n- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].\n- Delete 2 to earn 2 points. nums = [].\nYou earn a total of 6 points.\n\nExample 2:\nInput: nums = [2,2,3,3,3,4]\nOutput: 9\nExplanation: You can perform the following operations:\n- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].\n- Delete a 3 again to earn 3 points. nums = [3].\n- Delete a 3 once more to earn 3 points. nums = [].\nYou earn a total of 9 points.\n\nConstraints:\n- 1 <= nums.length <= 2 * 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 deleteAndEarn(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n vals = [0] * 10001\n for num in nums:\n vals[num] += num\n val_i, val_i_1 = vals[0], 0\n for i in range(1, len(vals)):\n val_i_1, val_i_2 = val_i, val_i_1\n val_i = max(vals[i] + val_i_2, val_i_1)\n return val_i\n\n"}} diff --git a/cp/cp-10217.jsonl b/cp/cp-10217.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3f868ce3f0f11a187367179fb6976eae13c168a2 --- /dev/null +++ b/cp/cp-10217.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10217", "name": "LeetCode 0741: Cherry Pickup"} +{"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: Cherry Pickup (Difficulty: Hard)\nTags: Array, Dynamic Programming, Matrix\n\nYou are given an n x n grid representing a field of cherries, each cell is one of three possible integers.\nReturn the maximum number of cherries you can collect by following the rules below:\n\nExample 1:\nInput: grid = [[0,1,-1],[1,0,-1],[1,1,1]]\nOutput: 5\nExplanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).\n4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].\nThen, the player went left, up, up, left to return home, picking up one more cherry.\nThe total number of cherries picked up is 5, and this is the maximum possible.\n\nExample 2:\nInput: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]\nOutput: 0\n\nConstraints:\n- n == grid.length\n- n == grid[i].length\n- 1 <= n <= 50\n- grid[i][j] is -1, 0, or 1.\n- grid[0][0] != -1\n- grid[n - 1][n - 1] != -1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(n^2)\n\nclass Solution(object):\n def cherryPickup(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n # dp holds the max # of cherries two k-length paths can pickup.\n # The two k-length paths arrive at (i, k - i) and (j, k - j),\n # respectively.\n n = len(grid)\n dp = [[-1 for _ in range(n)] for _ in range(n)]\n dp[0][0] = grid[0][0]\n max_len = 2 * (n-1)\n directions = [(0, 0), (-1, 0), (0, -1), (-1, -1)]\n for k in range(1, max_len+1):\n for i in reversed(range(max(0, k-n+1), min(k+1, n))): # 0 <= i < n, 0 <= k-i < n\n for j in reversed(range(i, min(k+1, n))): # i <= j < n, 0 <= k-j < n\n if grid[i][k-i] == -1 or grid[j][k-j] == -1:\n dp[i][j] = -1\n continue\n cnt = grid[i][k-i]\n if i != j:\n cnt += grid[j][k-j]\n max_cnt = -1\n for direction in directions:\n ii, jj = i+direction[0], j+direction[1]\n if ii >= 0 and jj >= 0 and dp[ii][jj] >= 0:\n max_cnt = max(max_cnt, dp[ii][jj]+cnt)\n dp[i][j] = max_cnt\n return max(dp[n-1][n-1], 0)\n\n"}} diff --git a/cp/cp-10219.jsonl b/cp/cp-10219.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..14c2aa698ef32c9c6d191c8278ab3d30e07e1339 --- /dev/null +++ b/cp/cp-10219.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10219", "name": "LeetCode 0743: Network Delay Time"} +{"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: Network Delay Time (Difficulty: Medium)\nTags: Depth-First Search, Breadth-First Search, Graph, Heap (Priority Queue), Shortest Path\n\nYou are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.\nWe will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.\n\nExample 1:\nInput: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2\nOutput: 2\n\nExample 2:\nInput: times = [[1,2,1]], n = 2, k = 1\nOutput: 1\n\nExample 3:\nInput: times = [[1,2,1]], n = 2, k = 2\nOutput: -1\n\nConstraints:\n- 1 <= k <= n <= 100\n- 1 <= times.length <= 6000\n- times[i].length == 3\n- 1 <= ui, vi <= n\n- ui != vi\n- 0 <= wi <= 100\n- All the pairs (ui, vi) are unique. (i.e., no multiple edges.)"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) by using binary heap,\n# if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|)\n# Space: O(|E| + |V|) = O(|E|)\n\nimport collections\nimport heapq\n\n# Dijkstra's algorithm\nclass Solution(object):\n def networkDelayTime(self, times, N, K):\n \"\"\"\n :type times: List[List[int]]\n :type N: int\n :type K: int\n :rtype: int\n \"\"\"\n adj = [[] for _ in range(N)]\n for u, v, w in times:\n adj[u-1].append((v-1, w))\n\n result = 0\n lookup = set()\n best = collections.defaultdict(lambda: float(\"inf\"))\n best[K-1] = 0\n min_heap = [(0, K-1)]\n while min_heap and len(lookup) != N:\n result, u = heapq.heappop(min_heap)\n lookup.add(u)\n if best[u] < result:\n continue\n for v, w in adj[u]:\n if v in lookup: continue\n if result+w < best[v]:\n best[v] = result+w\n heapq.heappush(min_heap, (result+w, v))\n return result if len(lookup) == N else -1\n\n"}} diff --git a/cp/cp-10220.jsonl b/cp/cp-10220.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0275ea3ef62134381450b64aa9d912da7b89400a --- /dev/null +++ b/cp/cp-10220.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10220", "name": "LeetCode 0744: Find Smallest Letter Greater Than Target"} +{"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 Smallest Letter Greater Than Target (Difficulty: Easy)\nTags: Array, Binary Search\n\nYou are given an array of characters letters that is sorted in non-decreasing order, and a character target. There are at least two different characters in letters.\nReturn the smallest character in letters that is lexicographically greater than target. If such a character does not exist, return the first character in letters.\n\nExample 1:\nInput: letters = [\"c\",\"f\",\"j\"], target = \"a\"\nOutput: \"c\"\nExplanation: The smallest character that is lexicographically greater than 'a' in letters is 'c'.\n\nExample 2:\nInput: letters = [\"c\",\"f\",\"j\"], target = \"c\"\nOutput: \"f\"\nExplanation: The smallest character that is lexicographically greater than 'c' in letters is 'f'.\n\nExample 3:\nInput: letters = [\"x\",\"x\",\"y\",\"y\"], target = \"z\"\nOutput: \"x\"\nExplanation: There are no characters in letters that is lexicographically greater than 'z' so we return letters[0].\n\nConstraints:\n- 2 <= letters.length <= 10^4\n- letters[i] is a lowercase English letter.\n- letters is sorted in non-decreasing order.\n- letters contains at least two different characters.\n- target is a lowercase English letter."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nimport bisect\n\n\nclass Solution(object):\n def nextGreatestLetter(self, letters, target):\n \"\"\"\n :type letters: List[str]\n :type target: str\n :rtype: str\n \"\"\"\n i = bisect.bisect_right(letters, target)\n return letters[0] if i == len(letters) else letters[i]\n\n"}} diff --git a/cp/cp-10221.jsonl b/cp/cp-10221.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..914e6841ef50ac70c3a3553993f18a62ea022160 --- /dev/null +++ b/cp/cp-10221.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10221", "name": "LeetCode 0745: Prefix And Suffix Search"} +{"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: Prefix and Suffix Search (Difficulty: Hard)\nTags: Array, Hash Table, String, Design, Trie\n\nDesign a special dictionary that searches the words in it by a prefix and a suffix.\nImplement the WordFilter class:\n\nExample 1:\nInput\n[\"WordFilter\", \"f\"]\n[[[\"apple\"]], [\"a\", \"e\"]]\nOutput\n[null, 0]\nExplanation\nWordFilter wordFilter = new WordFilter([\"apple\"]);\nwordFilter.f(\"a\", \"e\"); // return 0, because the word at index 0 has prefix = \"a\" and suffix = \"e\".\n\nConstraints:\n- 1 <= words.length <= 10^4\n- 1 <= words[i].length <= 7\n- 1 <= pref.length, suff.length <= 7\n- words[i], pref and suff consist of lowercase English letters only.\n- At most 104 calls will be made to the function f."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(w * l^2), w is the number of words, l is the word length on average\n# search: O(p + s) , p is the length of the prefix, s is the length of the suffix,\n# Space: O(t), t is the number of trie nodes\n\nimport collections\n\n\nclass WordFilter(object):\n\n def __init__(self, words):\n \"\"\"\n :type words: List[str]\n \"\"\"\n _trie = lambda: collections.defaultdict(_trie)\n self.__trie = _trie()\n\n for weight, word in enumerate(words):\n word += '#'\n for i in range(len(word)):\n cur = self.__trie\n cur[\"_weight\"] = weight\n for j in range(i, 2*len(word)-1):\n cur = cur[word[j%len(word)]]\n cur[\"_weight\"] = weight\n\n def f(self, prefix, suffix):\n \"\"\"\n :type prefix: str\n :type suffix: str\n :rtype: int\n \"\"\"\n cur = self.__trie\n for letter in suffix + '#' + prefix:\n if letter not in cur:\n return -1\n cur = cur[letter]\n return cur[\"_weight\"]\n\n\n# Time: ctor: O(w * l), w is the number of words, l is the word length on average\n# search: O(p + s + max(m, n)), p is the length of the prefix, s is the length of the suffix,\n# m is the number of the prefix match, n is the number of the suffix match\n# Space: O(w * l)\nclass Trie(object):\n\n def __init__(self):\n _trie = lambda: collections.defaultdict(_trie)\n self.__trie = _trie()\n\n def insert(self, word, i):\n def add_word(cur, i):\n if \"_words\" not in cur:\n cur[\"_words\"] = []\n cur[\"_words\"].append(i)\n\n cur = self.__trie\n add_word(cur, i)\n for c in word:\n cur = cur[c]\n add_word(cur, i)\n\n def find(self, word):\n cur = self.__trie\n for c in word:\n if c not in cur:\n return []\n cur = cur[c]\n return cur[\"_words\"]\n\n\nclass WordFilter2(object):\n\n def __init__(self, words):\n \"\"\"\n :type words: List[str]\n \"\"\"\n self.__prefix_trie = Trie()\n self.__suffix_trie = Trie()\n for i in reversed(range(len(words))):\n self.__prefix_trie.insert(words[i], i)\n self.__suffix_trie.insert(words[i][::-1], i)\n\n def f(self, prefix, suffix):\n \"\"\"\n :type prefix: str\n :type suffix: str\n :rtype: int\n \"\"\"\n prefix_match = self.__prefix_trie.find(prefix)\n suffix_match = self.__suffix_trie.find(suffix[::-1])\n i, j = 0, 0\n while i != len(prefix_match) and j != len(suffix_match):\n if prefix_match[i] == suffix_match[j]:\n return prefix_match[i]\n elif prefix_match[i] > suffix_match[j]:\n i += 1\n else:\n j += 1\n return -1\n\n\n\n"}} diff --git a/cp/cp-10222.jsonl b/cp/cp-10222.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c69fb40a8d8a4148273478023ae100ca0adfbad0 --- /dev/null +++ b/cp/cp-10222.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10222", "name": "LeetCode 0746: Min Cost Climbing Stairs"} +{"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: Min Cost Climbing Stairs (Difficulty: Easy)\nTags: Array, Dynamic Programming\n\nYou are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.\nYou can either start from the step with index 0, or the step with index 1.\nReturn the minimum cost to reach the top of the floor.\n\nExample 1:\nInput: cost = [10,15,20]\nOutput: 15\nExplanation: You will start at index 1.\n- Pay 15 and climb two steps to reach the top.\nThe total cost is 15.\n\nExample 2:\nInput: cost = [1,100,1,1,1,100,1,1,100,1]\nOutput: 6\nExplanation: You will start at index 0.\n- Pay 1 and climb two steps to reach index 2.\n- Pay 1 and climb two steps to reach index 4.\n- Pay 1 and climb two steps to reach index 6.\n- Pay 1 and climb one step to reach index 7.\n- Pay 1 and climb two steps to reach index 9.\n- Pay 1 and climb one step to reach the top.\nThe total cost is 6.\n\nConstraints:\n- 2 <= cost.length <= 1000\n- 0 <= cost[i] <= 999"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minCostClimbingStairs(self, cost):\n \"\"\"\n :type cost: List[int]\n :rtype: int\n \"\"\"\n dp = [0] * 3\n for i in reversed(range(len(cost))):\n dp[i%3] = cost[i] + min(dp[(i+1)%3], dp[(i+2)%3])\n return min(dp[0], dp[1])\n\n"}} diff --git a/cp/cp-10224.jsonl b/cp/cp-10224.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..62e40b4aa7740190bfac3b51d6493f1fda36360d --- /dev/null +++ b/cp/cp-10224.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10224", "name": "LeetCode 0748: Shortest Completing Word"} +{"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: Shortest Completing Word (Difficulty: Easy)\nTags: Array, Hash Table, String\n\nGiven a string licensePlate and an array of strings words, find the shortest completing word in words.\nA completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.\nFor example, if licensePlate = \"aBc 12c\", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are \"abccdef\", \"caaacab\", and \"cbca\".\nReturn the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.\n\nExample 1:\nInput: licensePlate = \"1s3 PSt\", words = [\"step\",\"steps\",\"stripe\",\"stepple\"]\nOutput: \"steps\"\nExplanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.\n\"step\" contains 't' and 'p', but only contains 1 's'.\n\"steps\" contains 't', 'p', and both 's' characters.\n\"stripe\" is missing an 's'.\n\"stepple\" is missing an 's'.\nSince \"steps\" is the only word containing all the letters, that is the answer.\n\nExample 2:\nInput: licensePlate = \"1s3 456\", words = [\"looks\",\"pest\",\"stew\",\"show\"]\nOutput: \"pest\"\nExplanation: licensePlate only contains the letter 's'. All the words contain 's', but among these \"pest\", \"stew\", and \"show\" are shortest. The answer is \"pest\" because it is the word that appears earliest of the 3.\n\nConstraints:\n- 1 <= licensePlate.length <= 7\n- licensePlate contains digits, letters (uppercase or lowercase), or space ' '.\n- 1 <= words.length <= 1000\n- 1 <= words[i].length <= 15\n- words[i] consists of lower case English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def shortestCompletingWord(self, licensePlate, words):\n \"\"\"\n :type licensePlate: str\n :type words: List[str]\n :rtype: str\n \"\"\"\n def contains(counter1, w2):\n c2 = collections.Counter(w2.lower())\n c2.subtract(counter1)\n return all(map(lambda x: x >= 0, c2.values()))\n\n result = None\n counter = collections.Counter(c.lower() for c in licensePlate if c.isalpha())\n for word in words:\n if (result is None or (len(word) < len(result))) and \\\n contains(counter, word):\n result = word\n return result\n\n"}} diff --git a/cp/cp-10225.jsonl b/cp/cp-10225.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6862f82905fb9b1a7c8c835808a6d4dab1ebe004 --- /dev/null +++ b/cp/cp-10225.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10225", "name": "LeetCode 0749: Contain Virus"} +{"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: Contain Virus (Difficulty: Hard)\nTags: Array, Depth-First Search, Breadth-First Search, Matrix, Simulation\n\nA virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.\nThe world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary.\nEvery night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie.\nReturn the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.\n\nExample 1:\nInput: isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]\nOutput: 10\nExplanation: There are 2 contaminated regions.\nOn the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:\n\nOn the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.\n\nExample 2:\nInput: isInfected = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: 4\nExplanation: Even though there is only one cell saved, there are 4 walls built.\nNotice that walls are only built on the shared boundary of two different cells.\n\nExample 3:\nInput: isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]\nOutput: 13\nExplanation: The region on the left only builds two new walls.\n\nConstraints:\n- m == isInfected.length\n- n == isInfected[i].length\n- 1 <= m, n <= 50\n- isInfected[i][j] is either 0 or 1.\n- There is always a contiguous viral region throughout the described process that will infect strictly more uncontaminated squares in the next round."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((m * n)^(4/3)), days = O((m * n)^(1/3))\n# Space: O(m * n)\n\nclass Solution(object):\n def containVirus(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]\n\n def dfs(grid, r, c, lookup, regions, frontiers, perimeters):\n if (r, c) in lookup:\n return\n lookup.add((r, c))\n regions[-1].add((r, c))\n for d in directions:\n nr, nc = r+d[0], c+d[1]\n if not (0 <= nr < len(grid) and \\\n 0 <= nc < len(grid[r])):\n continue\n if grid[nr][nc] == 1:\n dfs(grid, nr, nc, lookup, regions, frontiers, perimeters)\n elif grid[nr][nc] == 0:\n frontiers[-1].add((nr, nc))\n perimeters[-1] += 1\n\n result = 0\n while True:\n lookup, regions, frontiers, perimeters = set(), [], [], []\n for r, row in enumerate(grid):\n for c, val in enumerate(row):\n if val == 1 and (r, c) not in lookup:\n regions.append(set())\n frontiers.append(set())\n perimeters.append(0)\n dfs(grid, r, c, lookup, regions, frontiers, perimeters)\n\n if not regions: break\n\n triage_idx = frontiers.index(max(frontiers, key = len))\n for i, region in enumerate(regions):\n if i == triage_idx:\n result += perimeters[i]\n for r, c in region:\n grid[r][c] = -1\n continue\n for r, c in region:\n for d in directions:\n nr, nc = r+d[0], c+d[1]\n if not (0 <= nr < len(grid) and \\\n 0 <= nc < len(grid[r])):\n continue\n if grid[nr][nc] == 0:\n grid[nr][nc] = 1\n\n return result\n\n"}} diff --git a/cp/cp-10228.jsonl b/cp/cp-10228.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d19fdc23c0f5697d6a4e653676ecd2106ac8f4e2 --- /dev/null +++ b/cp/cp-10228.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10228", "name": "LeetCode 0752: Open The Lock"} +{"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: Open the Lock (Difficulty: Medium)\nTags: Array, Hash Table, String, Breadth-First Search\n\nYou have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.\nThe lock initially starts at '0000', a string representing the state of the 4 wheels.\nYou are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.\nGiven a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.\n\nExample 1:\nInput: deadends = [\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"], target = \"0202\"\nOutput: 6\nExplanation: \nA sequence of valid moves would be \"0000\" -> \"1000\" -> \"1100\" -> \"1200\" -> \"1201\" -> \"1202\" -> \"0202\".\nNote that a sequence like \"0000\" -> \"0001\" -> \"0002\" -> \"0102\" -> \"0202\" would be invalid,\nbecause the wheels of the lock become stuck after the display becomes the dead end \"0102\".\n\nExample 2:\nInput: deadends = [\"8888\"], target = \"0009\"\nOutput: 1\nExplanation: We can turn the last wheel in reverse to move from \"0000\" -> \"0009\".\n\nExample 3:\nInput: deadends = [\"8887\",\"8889\",\"8878\",\"8898\",\"8788\",\"8988\",\"7888\",\"9888\"], target = \"8888\"\nOutput: -1\nExplanation: We cannot reach the target without getting stuck.\n\nConstraints:\n- 1 <= deadends.length <= 500\n- deadends[i].length == 4\n- target.length == 4\n- target will not be in the list deadends.\n- target and deadends[i] consist of digits only."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(k * n^k + d), n is the number of alphabets,\n# k is the length of target,\n# d is the size of deadends\n# Space: O(k * n^k + d)\n\nclass Solution(object):\n def openLock(self, deadends, target):\n \"\"\"\n :type deadends: List[str]\n :type target: str\n :rtype: int\n \"\"\"\n dead = set(deadends)\n q = [\"0000\"]\n lookup = {\"0000\"}\n depth = 0\n while q:\n next_q = []\n for node in q:\n if node == target: return depth\n if node in dead: continue\n for i in range(4):\n n = int(node[i])\n for d in (-1, 1):\n nn = (n+d) % 10\n neighbor = node[:i] + str(nn) + node[i+1:]\n if neighbor not in lookup:\n lookup.add(neighbor)\n next_q.append(neighbor)\n q = next_q\n depth += 1\n return -1\n\n"}} diff --git a/cp/cp-10229.jsonl b/cp/cp-10229.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0e065f3529a2c5c7ea3bd8b150508c8782b20c42 --- /dev/null +++ b/cp/cp-10229.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10229", "name": "LeetCode 0753: Cracking The Safe"} +{"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: Cracking the Safe (Difficulty: Hard)\nTags: Depth-First Search, Graph, Eulerian Circuit\n\nThere is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1].\nThe safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit.\nReturn any string of minimum length that will unlock the safe at some point of entering it.\n\nExample 1:\nInput: n = 1, k = 2\nOutput: \"10\"\nExplanation: The password is a single digit, so enter each digit. \"01\" would also unlock the safe.\n\nExample 2:\nInput: n = 2, k = 2\nOutput: \"01100\"\nExplanation: For each possible password:\n- \"00\" is typed in starting from the 4th digit.\n- \"01\" is typed in starting from the 1st digit.\n- \"10\" is typed in starting from the 3rd digit.\n- \"11\" is typed in starting from the 2nd digit.\nThus \"01100\" will unlock the safe. \"10011\", and \"11001\" would also unlock the safe.\n\nConstraints:\n- 1 <= n <= 4\n- 1 <= k <= 10\n- 1 <= kn <= 4096"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(k^n)\n# Space: O(k^n)\n\nclass Solution(object):\n def crackSafe(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n M = k**(n-1)\n P = [q*k+i for i in range(k) for q in range(M)] # rotate: i*k^(n-1) + q => q*k + i\n result = [str(k-1)]*(n-1)\n for i in range(k**n):\n j = i\n # concatenation in lexicographic order of Lyndon words\n while P[j] >= 0:\n result.append(str(j//M))\n P[j], j = -1, P[j]\n return \"\".join(result)\n\n\n# Time: O(k^n)\n# Space: O(k^n)\nclass Solution2(object):\n def crackSafe(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n total = k**n\n M = total//k\n unique_rolling_hash = 0\n result = [str(0)]*(n-1)\n lookup = set()\n while len(lookup) < total:\n for i in reversed(range(k)): # preorder like traversal relative to initial result to avoid getting stuck, i.e. don't use 0 until there is no other choice\n new_unique_rolling_hash = unique_rolling_hash*k + i\n if new_unique_rolling_hash not in lookup:\n lookup.add(new_unique_rolling_hash)\n result.append(str(i))\n unique_rolling_hash = new_unique_rolling_hash%M\n break\n return \"\".join(result)\n\n\n# Time: O(k^n)\n# Space: O(k^n)\nclass Solution3(object):\n def crackSafe(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n M = k**(n-1)\n def dfs(k, unique_rolling_hash, lookup, result):\n for i in reversed(range(k)): # preorder like traversal relative to initial result to avoid getting stuck, i.e. don't use 0 until there is no other choice\n new_unique_rolling_hash = unique_rolling_hash*k + i\n if new_unique_rolling_hash not in lookup:\n lookup.add(new_unique_rolling_hash)\n result.append(str(i))\n dfs(k, new_unique_rolling_hash%M, lookup, result)\n break\n\n unique_rolling_hash = 0\n result = [str(0)]*(n-1)\n lookup = set()\n dfs(k, unique_rolling_hash, lookup, result)\n return \"\".join(result)\n\n\n# Time: O(n * k^n)\n# Space: O(n * k^n)\nclass Solution4(object):\n def crackSafe(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n result = [str(k-1)]*(n-1)\n lookup = set()\n total = k**n\n while len(lookup) < total:\n node = result[len(result)-n+1:]\n for i in range(k): # preorder like traversal relative to initial result to avoid getting stuck, i.e. don't use k-1 until there is no other choice\n neighbor = \"\".join(node) + str(i)\n if neighbor not in lookup:\n lookup.add(neighbor)\n result.append(str(i))\n break\n return \"\".join(result)\n\n\n# Time: O(n * k^n)\n# Space: O(n * k^n)\nclass Solution5(object):\n def crackSafe(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n def dfs(k, node, lookup, result):\n for i in range(k): # preorder like traversal relative to initial result to avoid getting stuck, i.e. don't use k-1 until there is no other choice\n neighbor = node + str(i)\n if neighbor not in lookup:\n lookup.add(neighbor)\n result.append(str(i))\n dfs(k, neighbor[1:], lookup, result)\n break\n\n result = [str(k-1)]*(n-1)\n lookup = set()\n dfs(k, \"\".join(result), lookup, result)\n return \"\".join(result)\n\n"}} diff --git a/cp/cp-10230.jsonl b/cp/cp-10230.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..23b106a3ab7f36544f8625a9d3468f55a62d96c7 --- /dev/null +++ b/cp/cp-10230.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10230", "name": "LeetCode 0754: Reach A 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: Reach a Number (Difficulty: Medium)\nTags: Math, Binary Search\n\nYou are standing at position 0 on an infinite number line. There is a destination at position target.\nYou can make some number of moves numMoves so that:\nGiven the integer target, return the minimum number of moves required (i.e., the minimum numMoves) to reach the destination.\n\nExample 1:\nInput: target = 2\nOutput: 3\nExplanation:\nOn the 1st move, we step from 0 to 1 (1 step).\nOn the 2nd move, we step from 1 to -1 (2 steps).\nOn the 3rd move, we step from -1 to 2 (3 steps).\n\nExample 2:\nInput: target = 3\nOutput: 2\nExplanation:\nOn the 1st move, we step from 0 to 1 (1 step).\nOn the 2nd move, we step from 1 to 3 (2 steps).\n\nConstraints:\n- -10^9 <= target <= 10^9\n- target != 0"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nimport math\n\n\nclass Solution(object):\n def reachNumber(self, target):\n \"\"\"\n :type target: int\n :rtype: int\n \"\"\"\n target = abs(target)\n k = int(math.ceil((-1+math.sqrt(1+8*target))/2))\n target -= k*(k+1)/2\n return k if target%2 == 0 else k+1+k%2\n\n\n# Time: O(sqrt(n))\n# Space: O(1)\nclass Solution2(object):\n def reachNumber(self, target):\n \"\"\"\n :type target: int\n :rtype: int\n \"\"\"\n target = abs(target)\n k = 0\n while target > 0:\n k += 1\n target -= k\n return k if target%2 == 0 else k+1+k%2\n\n"}} diff --git a/cp/cp-10232.jsonl b/cp/cp-10232.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..199d8053c22fcc3a1e5c94afb0ff4663b82c0cc4 --- /dev/null +++ b/cp/cp-10232.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10232", "name": "LeetCode 0756: Pyramid Transition Matrix"} +{"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: Pyramid Transition Matrix (Difficulty: Medium)\nTags: Bit Manipulation, Depth-First Search, Breadth-First Search\n\nYou are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top.\nTo make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given as a list of three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.\nYou start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid.\nGiven bottom and allowed, return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed, or false otherwise.\n\nExample 1:\nInput: bottom = \"BCD\", allowed = [\"BCC\",\"CDE\",\"CEA\",\"FFF\"]\nOutput: true\nExplanation: The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 3), we can build \"CE\" on level 2 and then build \"A\" on level 1.\nThere are three triangular patterns in the pyramid, which are \"BCC\", \"CDE\", and \"CEA\". All are allowed.\n\nExample 2:\nInput: bottom = \"AAAA\", allowed = [\"AAB\",\"AAC\",\"BCD\",\"BBE\",\"DEF\"]\nOutput: false\nExplanation: The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.\n\nConstraints:\n- 2 <= bottom.length <= 6\n- 0 <= allowed.length <= 216\n- allowed[i].length == 3\n- The letters in all input strings are from the set {'A', 'B', 'C', 'D', 'E', 'F'}.\n- All the values of allowed are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((a^(b+1)-a)/(a-1)) = O(a^b) , a is the size of allowed,\n# b is the length of bottom\n# Space: O((a^(b+1)-a)/(a-1)) = O(a^b)\n\nclass Solution(object):\n def pyramidTransition(self, bottom, allowed):\n \"\"\"\n :type bottom: str\n :type allowed: List[str]\n :rtype: bool\n \"\"\"\n def pyramidTransitionHelper(bottom, edges, lookup):\n def dfs(bottom, edges, new_bottom, idx, lookup):\n if idx == len(bottom)-1:\n return pyramidTransitionHelper(\"\".join(new_bottom), edges, lookup)\n for i in edges[ord(bottom[idx])-ord('A')][ord(bottom[idx+1])-ord('A')]:\n new_bottom[idx] = chr(i+ord('A'))\n if dfs(bottom, edges, new_bottom, idx+1, lookup):\n return True\n return False\n\n if len(bottom) == 1:\n return True\n if bottom in lookup:\n return False\n lookup.add(bottom)\n for i in range(len(bottom)-1):\n if not edges[ord(bottom[i])-ord('A')][ord(bottom[i+1])-ord('A')]:\n return False\n new_bottom = ['A']*(len(bottom)-1)\n return dfs(bottom, edges, new_bottom, 0, lookup)\n\n edges = [[[] for _ in range(7)] for _ in range(7)]\n for s in allowed:\n edges[ord(s[0])-ord('A')][ord(s[1])-ord('A')].append(ord(s[2])-ord('A'))\n return pyramidTransitionHelper(bottom, edges, set())\n\n"}} diff --git a/cp/cp-10233.jsonl b/cp/cp-10233.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6085acfb7f61c88f46a0dc44dc2530b510dfe643 --- /dev/null +++ b/cp/cp-10233.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10233", "name": "LeetCode 0757: Set Intersection Size At Least Two"} +{"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 Intersection Size At Least Two (Difficulty: Hard)\nTags: Array, Greedy, Sorting\n\nYou are given a 2D integer array intervals where intervals[i] = [starti, endi] represents all the integers from starti to endi inclusively.\nA containing set is an array nums where each interval from intervals has at least two integers in nums.\nReturn the minimum possible size of a containing set.\n\nExample 1:\nInput: intervals = [[1,3],[3,7],[8,9]]\nOutput: 5\nExplanation: let nums = [2, 3, 4, 8, 9].\nIt can be shown that there cannot be any containing array of size 4.\n\nExample 2:\nInput: intervals = [[1,3],[1,4],[2,5],[3,5]]\nOutput: 3\nExplanation: let nums = [2, 3, 4].\nIt can be shown that there cannot be any containing array of size 2.\n\nExample 3:\nInput: intervals = [[1,2],[2,3],[2,4],[4,5]]\nOutput: 5\nExplanation: let nums = [1, 2, 3, 4, 5].\nIt can be shown that there cannot be any containing array of size 4.\n\nConstraints:\n- 1 <= intervals.length <= 3000\n- intervals[i].length == 2\n- 0 <= starti < endi <= 10^8"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass Solution(object):\n def intersectionSizeTwo(self, intervals):\n \"\"\"\n :type intervals: List[List[int]]\n :rtype: int\n \"\"\"\n intervals.sort(key = lambda s_e: (s_e[0], -s_e[1]))\n cnts = [2] * len(intervals)\n result = 0\n while intervals:\n (start, _), cnt = intervals.pop(), cnts.pop()\n for s in range(start, start+cnt):\n for i in range(len(intervals)):\n if cnts[i] and s <= intervals[i][1]:\n cnts[i] -= 1\n result += cnt\n return result\n\n"}} diff --git a/cp/cp-10237.jsonl b/cp/cp-10237.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..72dd84da957c2ba4a54ef2cedd082f37d0d4eaf9 --- /dev/null +++ b/cp/cp-10237.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10237", "name": "LeetCode 0761: Special Binary 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: Special Binary String (Difficulty: Hard)\nTags: String, Recursion\n\nSpecial binary strings are binary strings with the following two properties:\nYou are given a special binary string s.\nA move consists of choosing two consecutive, non-empty, special substrings of s, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.\nReturn the lexicographically largest resulting string possible after applying the mentioned operations on the string.\n\nExample 1:\nInput: s = \"11011000\"\nOutput: \"11100100\"\nExplanation: The strings \"10\" [occuring at s[1]] and \"1100\" [at s[3]] are swapped.\nThis is the lexicographically largest string possible after some number of swaps.\n\nExample 2:\nInput: s = \"10\"\nOutput: \"10\"\n\nConstraints:\n- 1 <= s.length <= 50\n- s[i] is either '0' or '1'.\n- s is a special binary string."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: f(n) = k * f(n/k) + n/k * klogk <= O(logn * nlogk) <= O(n^2)\n# n is the length of S, k is the max number of special strings in each depth\n# Space: O(n)\n\nclass Solution(object):\n def makeLargestSpecial(self, S):\n \"\"\"\n :type S: str\n :rtype: str\n \"\"\"\n result = []\n anchor = count = 0\n for i, v in enumerate(S):\n count += 1 if v == '1' else -1\n if count == 0:\n result.append(\"1{}0\".format(self.makeLargestSpecial(S[anchor+1:i])))\n anchor = i+1\n result.sort(reverse = True)\n return \"\".join(result)\n\n"}} diff --git a/cp/cp-10238.jsonl b/cp/cp-10238.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6f2c50e11e6d8b999141cd5e20df05e8b28c43be --- /dev/null +++ b/cp/cp-10238.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10238", "name": "LeetCode 0762: Prime Number Of Set Bits In Binary Representation"} +{"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: Prime Number of Set Bits in Binary Representation (Difficulty: Easy)\nTags: Math, Bit Manipulation\n\nGiven two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation.\nRecall that the number of set bits an integer has is the number of 1's present when written in binary.\n\nExample 1:\nInput: left = 6, right = 10\nOutput: 4\nExplanation:\n6 -> 110 (2 set bits, 2 is prime)\n7 -> 111 (3 set bits, 3 is prime)\n8 -> 1000 (1 set bit, 1 is not prime)\n9 -> 1001 (2 set bits, 2 is prime)\n10 -> 1010 (2 set bits, 2 is prime)\n4 numbers have a prime number of set bits.\n\nExample 2:\nInput: left = 10, right = 15\nOutput: 5\nExplanation:\n10 -> 1010 (2 set bits, 2 is prime)\n11 -> 1011 (3 set bits, 3 is prime)\n12 -> 1100 (2 set bits, 2 is prime)\n13 -> 1101 (3 set bits, 3 is prime)\n14 -> 1110 (3 set bits, 3 is prime)\n15 -> 1111 (4 set bits, 4 is not prime)\n5 numbers have a prime number of set bits.\n\nConstraints:\n- 1 <= left <= right <= 10^6\n- 0 <= right - left <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(log(R - L)) = O(1)\n# Space: O(1)\n\nclass Solution(object):\n def countPrimeSetBits(self, L, R):\n \"\"\"\n :type L: int\n :type R: int\n :rtype: int\n \"\"\"\n def bitCount(n):\n result = 0\n while n:\n n &= n-1\n result += 1\n return result\n\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n return sum(bitCount(i) in primes\n for i in range(L, R+1))\n\n"}} diff --git a/cp/cp-10239.jsonl b/cp/cp-10239.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..de3a50b6e6ea509c26588aa83eeabcff48e48fd3 --- /dev/null +++ b/cp/cp-10239.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10239", "name": "LeetCode 0763: Partition Labels"} +{"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: Partition Labels (Difficulty: Medium)\nTags: Hash Table, Two Pointers, String, Greedy\n\nYou are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. For example, the string \"ababcc\" can be partitioned into [\"abab\", \"cc\"], but partitions such as [\"aba\", \"bcc\"] or [\"ab\", \"ab\", \"cc\"] are invalid.\nNote that the partition is done so that after concatenating all the parts in order, the resultant string should be s.\nReturn a list of integers representing the size of these parts.\n\nExample 1:\nInput: s = \"ababcbacadefegdehijhklij\"\nOutput: [9,7,8]\nExplanation:\nThe partition is \"ababcbaca\", \"defegde\", \"hijhklij\".\nThis is a partition so that each letter appears in at most one part.\nA partition like \"ababcbacadefegde\", \"hijhklij\" is incorrect, because it splits s into less parts.\n\nExample 2:\nInput: s = \"eccbbbbdec\"\nOutput: [10]\n\nConstraints:\n- 1 <= s.length <= 500\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 partitionLabels(self, S):\n \"\"\"\n :type S: str\n :rtype: List[int]\n \"\"\"\n lookup = {c: i for i, c in enumerate(S)}\n first, last = 0, 0\n result = []\n for i, c in enumerate(S):\n last = max(last, lookup[c])\n if i == last:\n result.append(i-first+1)\n first = i+1\n return result\n\n"}} diff --git a/cp/cp-10240.jsonl b/cp/cp-10240.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0b293d94cdb89fb790fd395aa42b99aa43e22da9 --- /dev/null +++ b/cp/cp-10240.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10240", "name": "LeetCode 0764: Largest Plus Sign"} +{"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: Largest Plus Sign (Difficulty: Medium)\nTags: Array, Dynamic Programming\n\nYou are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0.\nReturn the order of the largest axis-aligned plus sign of 1's contained in grid. If there is none, return 0.\nAn axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1's.\n\nExample 1:\nInput: n = 5, mines = [[4,2]]\nOutput: 2\nExplanation: In the above grid, the largest plus sign can only be of order 2. One of them is shown.\n\nExample 2:\nInput: n = 1, mines = [[0,0]]\nOutput: 0\nExplanation: There is no plus sign, so return 0.\n\nConstraints:\n- 1 <= n <= 500\n- 1 <= mines.length <= 5000\n- 0 <= xi, yi < n\n- All the pairs (xi, yi) are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2)\n\nclass Solution(object):\n def orderOfLargestPlusSign(self, N, mines):\n \"\"\"\n :type N: int\n :type mines: List[List[int]]\n :rtype: int\n \"\"\"\n lookup = {tuple(mine) for mine in mines}\n dp = [[0] * N for _ in range(N)]\n result = 0\n for i in range(N):\n l = 0\n for j in range(N):\n l = 0 if (i, j) in lookup else l+1\n dp[i][j] = l\n l = 0\n for j in reversed(range(N)):\n l = 0 if (i, j) in lookup else l+1\n dp[i][j] = min(dp[i][j], l)\n\n for j in range(N):\n l = 0\n for i in range(N):\n l = 0 if (i, j) in lookup else l+1\n dp[i][j] = min(dp[i][j], l)\n l = 0\n for i in reversed(range(N)):\n l = 0 if (i, j) in lookup else l+1\n dp[i][j] = min(dp[i][j], l)\n result = max(result, dp[i][j])\n return result\n\n"}} diff --git a/cp/cp-10241.jsonl b/cp/cp-10241.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5d1d4d37ca0d3864be333e1a859b649d1d0cf2c6 --- /dev/null +++ b/cp/cp-10241.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10241", "name": "LeetCode 0765: Couples Holding Hands"} +{"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: Couples Holding Hands (Difficulty: Hard)\nTags: Greedy, Depth-First Search, Breadth-First Search, Union Find, Graph\n\nThere are n couples sitting in 2n seats arranged in a row and want to hold hands.\nThe people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1).\nReturn the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.\n\nExample 1:\nInput: row = [0,2,1,3]\nOutput: 1\nExplanation: We only need to swap the second (row[1]) and third (row[2]) person.\n\nExample 2:\nInput: row = [3,2,0,1]\nOutput: 0\nExplanation: All couples are already seated side by side.\n\nConstraints:\n- 2n == row.length\n- 2 <= n <= 30\n- n is even.\n- 0 <= row[i] < 2n\n- All the elements of row are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def minSwapsCouples(self, row):\n \"\"\"\n :type row: List[int]\n :rtype: int\n \"\"\"\n N = len(row)//2\n couples = [[] for _ in range(N)]\n for seat, num in enumerate(row):\n couples[num//2].append(seat//2)\n adj = [[] for _ in range(N)]\n for couch1, couch2 in couples:\n adj[couch1].append(couch2)\n adj[couch2].append(couch1)\n\n result = 0\n for couch in range(N):\n if not adj[couch]: continue\n couch1, couch2 = couch, adj[couch].pop()\n while couch2 != couch:\n result += 1\n adj[couch2].remove(couch1)\n couch1, couch2 = couch2, adj[couch2].pop()\n return result # also equals to N - (# of cycles)\n\n"}} diff --git a/cp/cp-10242.jsonl b/cp/cp-10242.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eea506ad5103474917c329111f28a0ddb0bc9fdf --- /dev/null +++ b/cp/cp-10242.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10242", "name": "LeetCode 0766: Toeplitz Matrix"} +{"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: Toeplitz Matrix (Difficulty: Easy)\nTags: Array, Matrix\n\nGiven an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.\nA matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.\nFollow up:\n\nExample 1:\nInput: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]\nOutput: true\nExplanation:\nIn the above grid, the diagonals are:\n\"[9]\", \"[5, 5]\", \"[1, 1, 1]\", \"[2, 2, 2]\", \"[3, 3]\", \"[4]\".\nIn each diagonal all elements are the same, so the answer is True.\n\nExample 2:\nInput: matrix = [[1,2],[2,2]]\nOutput: false\nExplanation:\nThe diagonal \"[1, 2]\" has different elements.\n\nConstraints:\n- m == matrix.length\n- n == matrix[i].length\n- 1 <= m, n <= 20\n- 0 <= matrix[i][j] <= 99"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def isToeplitzMatrix(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: bool\n \"\"\"\n return all(i == 0 or j == 0 or matrix[i-1][j-1] == val\n for i, row in enumerate(matrix)\n for j, val in enumerate(row))\n\n\nclass Solution2(object):\n def isToeplitzMatrix(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: bool\n \"\"\"\n for row_index, row in enumerate(matrix):\n for digit_index, digit in enumerate(row):\n if not row_index or not digit_index:\n continue\n if matrix[row_index - 1][digit_index - 1] != digit:\n return False\n return True\n\n"}} diff --git a/cp/cp-10243.jsonl b/cp/cp-10243.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1dc3442301756c4c835c6542b35ffab29ced5c09 --- /dev/null +++ b/cp/cp-10243.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10243", "name": "LeetCode 0767: Reorganize 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: Reorganize String (Difficulty: Medium)\nTags: Hash Table, String, Greedy, Sorting, Heap (Priority Queue), Counting\n\nGiven a string s, rearrange the characters of s so that any two adjacent characters are not the same.\nReturn any possible rearrangement of s or return \"\" if not possible.\n\nExample 1:\nInput: s = \"aab\"\nOutput: \"aba\"\n\nExample 2:\nInput: s = \"aaab\"\nOutput: \"\"\n\nConstraints:\n- 1 <= s.length <= 500\n- s consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nloga) = O(n), a is the size of alphabet\n# Space: O(a) = O(1)\n\nimport collections\nimport heapq\n\n\nclass Solution(object):\n def reorganizeString(self, S):\n \"\"\"\n :type S: str\n :rtype: str\n \"\"\"\n counts = collections.Counter(S)\n if any(v > (len(S)+1)/2 for k, v in counts.iteritems()):\n return \"\"\n\n result = []\n max_heap = []\n for k, v in counts.iteritems():\n heapq.heappush(max_heap, (-v, k))\n while len(max_heap) > 1:\n count1, c1 = heapq.heappop(max_heap)\n count2, c2 = heapq.heappop(max_heap)\n if not result or c1 != result[-1]:\n result.extend([c1, c2])\n if count1+1: heapq.heappush(max_heap, (count1+1, c1))\n if count2+1: heapq.heappush(max_heap, (count2+1, c2))\n return \"\".join(result) + (max_heap[0][1] if max_heap else '')\n\n"}} diff --git a/cp/cp-10244.jsonl b/cp/cp-10244.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7fe49a1a0211184e67e6086853445c66a00f0bc6 --- /dev/null +++ b/cp/cp-10244.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10244", "name": "LeetCode 0768: Max Chunks To Make Sorted 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: Max Chunks To Make Sorted II (Difficulty: Hard)\nTags: Array, Stack, Greedy, Sorting, Monotonic Stack\n\nYou are given an integer array arr.\nWe split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.\nReturn the largest number of chunks we can make to sort the array.\n\nExample 1:\nInput: arr = [5,4,3,2,1]\nOutput: 1\nExplanation:\nSplitting into two or more chunks will not return the required result.\nFor example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.\n\nExample 2:\nInput: arr = [2,1,3,4,4]\nOutput: 4\nExplanation:\nWe can split into two chunks, such as [2, 1], [3, 4, 4].\nHowever, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.\n\nConstraints:\n- 1 <= arr.length <= 2000\n- 0 <= arr[i] <= 10^8"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\n# mono stack solution\nclass Solution(object):\n def maxChunksToSorted(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n result, increasing_stk = 0, []\n for num in arr:\n max_num = num if not increasing_stk else max(increasing_stk[-1], num)\n while increasing_stk and increasing_stk[-1] > num:\n increasing_stk.pop()\n increasing_stk.append(max_num)\n return len(increasing_stk)\n\n\n# Time: O(nlogn)\n# Space: O(n)\nclass Solution2(object):\n def maxChunksToSorted(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n def compare(i1, i2):\n return arr[i1]-arr[i2] if arr[i1] != arr[i2] else i1-i2\n\n idxs = [i for i in range(len(arr))]\n result, max_i = 0, 0\n for i, v in enumerate(sorted(idxs, cmp=compare)):\n max_i = max(max_i, v)\n if max_i == i:\n result += 1\n return result\n\n"}} diff --git a/cp/cp-10245.jsonl b/cp/cp-10245.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a16bc7f34a49f65f921f9d906fd97268decabb2b --- /dev/null +++ b/cp/cp-10245.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10245", "name": "LeetCode 0769: Max Chunks To Make Sorted"} +{"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: Max Chunks To Make Sorted (Difficulty: Medium)\nTags: Array, Stack, Greedy, Sorting, Monotonic Stack\n\nYou are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].\nWe split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.\nReturn the largest number of chunks we can make to sort the array.\n\nExample 1:\nInput: arr = [4,3,2,1,0]\nOutput: 1\nExplanation:\nSplitting into two or more chunks will not return the required result.\nFor example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.\n\nExample 2:\nInput: arr = [1,0,2,3,4]\nOutput: 4\nExplanation:\nWe can split into two chunks, such as [1, 0], [2, 3, 4].\nHowever, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.\n\nConstraints:\n- n == arr.length\n- 1 <= n <= 10\n- 0 <= arr[i] < n\n- All the elements of arr are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxChunksToSorted(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n result, max_i = 0, 0\n for i, v in enumerate(arr):\n max_i = max(max_i, v)\n if max_i == i:\n result += 1\n return result\n\n \n# Time: O(n)\n# Space: O(n)\n# mono stack solution\nclass Solution2(object):\n def maxChunksToSorted(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n result, increasing_stk = 0, []\n for num in arr:\n max_num = num if not increasing_stk else max(increasing_stk[-1], num)\n while increasing_stk and increasing_stk[-1] > num:\n increasing_stk.pop()\n increasing_stk.append(max_num)\n return len(increasing_stk)\n"}} diff --git a/cp/cp-10246.jsonl b/cp/cp-10246.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5d0a5e831fbecac0822d2414d9b2c9680cc35066 --- /dev/null +++ b/cp/cp-10246.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10246", "name": "LeetCode 0770: Basic Calculator Iv"} +{"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: Basic Calculator IV (Difficulty: Hard)\nTags: Hash Table, Math, String, Stack, Recursion\n\nGiven an expression such as expression = \"e + 8 - a + 5\" and an evaluation map such as {\"e\": 1} (given in terms of evalvars = [\"e\"] and evalints = [1]), return a list of tokens representing the simplified expression, such as [\"-1*a\",\"14\"]\nExpressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction.\nThe format of the output is as follows:\nNote: You may assume that the given expression is always valid. All intermediate results will be in the range of [-2^31, 2^31 - 1].\n\nExample 1:\nInput: expression = \"e + 8 - a + 5\", evalvars = [\"e\"], evalints = [1]\nOutput: [\"-1*a\",\"14\"]\n\nExample 2:\nInput: expression = \"e - 8 + temperature - pressure\", evalvars = [\"e\", \"temperature\"], evalints = [1, 12]\nOutput: [\"-1*pressure\",\"5\"]\n\nExample 3:\nInput: expression = \"(e + 8) * (e - 8)\", evalvars = [], evalints = []\nOutput: [\"1*e*e\",\"-64\"]\n\nConstraints:\n- 1 <= expression.length <= 250\n- expression consists of lowercase English letters, digits, '+', '-', '*', '(', ')', ' '.\n- expression does not contain any leading or trailing spaces.\n- All the tokens in expression are separated by a single space.\n- 0 <= evalvars.length <= 100\n- 1 <= evalvars[i].length <= 20\n- evalvars[i] consists of lowercase English letters.\n- evalints.length == evalvars.length\n- -100 <= evalints[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: +: O(d * t), t is the number of terms,\n# d is the average degree of terms\n# -: O(d * t)\n# *: O(d * t^2)\n# eval: O(d * t)\n# to_list: O(d * tlogt)\n# Space: O(e + d * t), e is the number of evalvars\n\nimport collections\nimport itertools\nimport operator\n\n\ndef clear(result):\n to_remove = [k for k, v in result.iteritems() if v == 0]\n for k in to_remove:\n result.pop(k)\n\n\nclass Poly(collections.Counter):\n def __init__(self, expr=None):\n if expr is None:\n return\n if expr.isdigit():\n if int(expr):\n self.update({(): int(expr)})\n else:\n self[(expr,)] += 1\n\n def __add__(self, other):\n result = Poly()\n result.update(self)\n result.update(other)\n clear(result)\n return result\n\n def __sub__(self, other):\n result = Poly()\n result.update(self)\n result.update({k: -v for k, v in other.iteritems()})\n clear(result)\n return result\n\n def __mul__(self, other):\n def merge(k1, k2):\n result = []\n i, j = 0, 0\n while i != len(k1) or j != len(k2):\n if j == len(k2) or (i != len(k1) and k1[i] < k2[j]):\n result.append(k1[i])\n i += 1\n else:\n result.append(k2[j])\n j += 1\n return result\n\n result = Poly()\n for k1, v1 in self.iteritems():\n for k2, v2 in other.iteritems():\n result.update({tuple(merge(k1, k2)): v1*v2})\n clear(result)\n return result\n\n def eval(self, lookup):\n result = Poly()\n for polies, c in self.iteritems():\n key = []\n for var in polies:\n if var in lookup:\n c *= lookup[var]\n else:\n key.append(var)\n result[tuple(key)] += c\n clear(result)\n return result\n\n def to_list(self):\n return [\"*\".join((str(v),) + k)\n for k, v in sorted(self.iteritems(),\n key=lambda x: (-len(x[0]), x[0]))]\n\n\nclass Solution(object):\n def basicCalculatorIV(self, expression, evalvars, evalints):\n \"\"\"\n :type expression: str\n :type evalvars: List[str]\n :type evalints: List[int]\n :rtype: List[str]\n \"\"\"\n ops = {'+':operator.add, '-':operator.sub, '*':operator.mul}\n def compute(operands, operators):\n right, left = operands.pop(), operands.pop()\n operands.append(ops[operators.pop()](left, right))\n\n def parse(s):\n precedence = {'+':0, '-':0, '*':1}\n operands, operators, operand = [], [], []\n for i in range(len(s)):\n if s[i].isalnum():\n operand.append(s[i])\n if i == len(s)-1 or not s[i+1].isalnum():\n operands.append(Poly(\"\".join(operand)))\n operand = []\n elif s[i] == '(':\n operators.append(s[i])\n elif s[i] == ')':\n while operators[-1] != '(':\n compute(operands, operators)\n operators.pop()\n elif s[i] in precedence:\n while operators and operators[-1] in precedence and \\\n precedence[operators[-1]] >= precedence[s[i]]:\n compute(operands, operators)\n operators.append(s[i])\n while operators:\n compute(operands, operators)\n return operands[-1]\n\n lookup = dict(itertools.izip(evalvars, evalints))\n return parse(expression).eval(lookup).to_list()\n\n\nclass Solution2(object):\n def basicCalculatorIV(self, expression, evalvars, evalints):\n \"\"\"\n :type expression: str\n :type evalvars: List[str]\n :type evalints: List[int]\n :rtype: List[str]\n \"\"\"\n def compute(operands, operators):\n left, right = operands.pop(), operands.pop()\n op = operators.pop()\n if op == '+':\n operands.append(left + right)\n elif op == '-':\n operands.append(left - right)\n elif op == '*':\n operands.append(left * right)\n\n def parse(s):\n if not s:\n return Poly()\n operands, operators = [], []\n operand = \"\"\n for i in reversed(range(len(s))):\n if s[i].isalnum():\n operand += s[i]\n if i == 0 or not s[i-1].isalnum():\n operands.append(Poly(operand[::-1]))\n operand = \"\"\n elif s[i] == ')' or s[i] == '*':\n operators.append(s[i])\n elif s[i] == '+' or s[i] == '-':\n while operators and operators[-1] == '*':\n compute(operands, operators)\n operators.append(s[i])\n elif s[i] == '(':\n while operators[-1] != ')':\n compute(operands, operators)\n operators.pop()\n while operators:\n compute(operands, operators)\n return operands[-1]\n\n lookup = dict(itertools.izip(evalvars, evalints))\n return parse(expression).eval(lookup).to_list()\n\n"}} diff --git a/cp/cp-10249.jsonl b/cp/cp-10249.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3007a3a1ea3b92739b632b4931d76ce5ff75b33d --- /dev/null +++ b/cp/cp-10249.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10249", "name": "LeetCode 0773: Sliding Puzzle"} +{"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: Sliding Puzzle (Difficulty: Hard)\nTags: Array, Dynamic Programming, Backtracking, Breadth-First Search, Memoization, Matrix\n\nOn an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.\nThe state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].\nGiven the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.\n\nExample 1:\nInput: board = [[1,2,3],[4,0,5]]\nOutput: 1\nExplanation: Swap the 0 and the 5 in one move.\n\nExample 2:\nInput: board = [[1,2,3],[5,4,0]]\nOutput: -1\nExplanation: No number of moves will make the board solved.\n\nExample 3:\nInput: board = [[4,1,2],[5,0,3]]\nOutput: 5\nExplanation: 5 is the smallest number of moves that solves the board.\nAn example path:\nAfter move 0: [[4,1,2],[5,0,3]]\nAfter move 1: [[4,1,2],[0,5,3]]\nAfter move 2: [[0,1,2],[4,5,3]]\nAfter move 3: [[1,0,2],[4,5,3]]\nAfter move 4: [[1,2,0],[4,5,3]]\nAfter move 5: [[1,2,3],[4,5,0]]\n\nConstraints:\n- board.length == 2\n- board[i].length == 3\n- 0 <= board[i][j] <= 5\n- Each value board[i][j] is unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((m * n) * (m * n)!)\n# Space: O((m * n) * (m * n)!)\n\nimport heapq\nimport itertools\n\n\n# A* Search Algorithm\nclass Solution(object):\n def slidingPuzzle(self, board):\n \"\"\"\n :type board: 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 heuristic_estimate(board, R, C, expected):\n result = 0\n for i in range(R):\n for j in range(C):\n val = board[C*i + j]\n if val == 0: continue\n r, c = expected[val]\n result += abs(r-i) + abs(c-j)\n return result\n\n R, C = len(board), len(board[0])\n begin = tuple(itertools.chain(*board))\n end = tuple(range(1, R*C) + [0])\n expected = {(C*i+j+1) % (R*C) : (i, j)\n for i in range(R) for j in range(C)}\n\n min_steps = heuristic_estimate(begin, R, C, expected)\n closer, detour = [(begin.index(0), begin)], []\n lookup = set()\n while True:\n if not closer:\n if not detour:\n return -1\n min_steps += 2\n closer, detour = detour, closer\n zero, board = closer.pop()\n if board == end:\n return min_steps\n if board not in lookup:\n lookup.add(board)\n r, c = divmod(zero, C)\n for direction in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n i, j = r+direction[0], c+direction[1]\n if 0 <= i < R and 0 <= j < C:\n new_zero = i*C+j\n tmp = list(board)\n tmp[zero], tmp[new_zero] = tmp[new_zero], tmp[zero]\n new_board = tuple(tmp)\n r2, c2 = expected[board[new_zero]]\n r1, c1 = divmod(zero, C)\n r0, c0 = divmod(new_zero, C)\n is_closer = dot((r1-r0, c1-c0), (r2-r0, c2-c0)) > 0\n (closer if is_closer else detour).append((new_zero, new_board))\n return min_steps\n\n\n# Time: O((m * n) * (m * n)! * log((m * n)!))\n# Space: O((m * n) * (m * n)!)\n# A* Search Algorithm\nclass Solution2(object):\n def slidingPuzzle(self, board):\n \"\"\"\n :type board: List[List[int]]\n :rtype: int\n \"\"\"\n def heuristic_estimate(board, R, C, expected):\n result = 0\n for i in range(R):\n for j in range(C):\n val = board[C*i + j]\n if val == 0: continue\n r, c = expected[val]\n result += abs(r-i) + abs(c-j)\n return result\n\n R, C = len(board), len(board[0])\n begin = tuple(itertools.chain(*board))\n end = tuple(range(1, R*C) + [0])\n end_wrong = tuple(range(1, R*C-2) + [R*C-1, R*C-2, 0])\n expected = {(C*i+j+1) % (R*C) : (i, j)\n for i in range(R) for j in range(C)}\n\n min_heap = [(0, 0, begin.index(0), begin)]\n lookup = {begin: 0}\n while min_heap:\n f, g, zero, board = heapq.heappop(min_heap)\n if board == end: return g\n if board == end_wrong: return -1\n if f > lookup[board]: continue\n\n r, c = divmod(zero, C)\n for direction in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n i, j = r+direction[0], c+direction[1]\n if 0 <= i < R and 0 <= j < C:\n new_zero = C*i+j\n tmp = list(board)\n tmp[zero], tmp[new_zero] = tmp[new_zero], tmp[zero]\n new_board = tuple(tmp)\n f = g+1+heuristic_estimate(new_board, R, C, expected)\n if f < lookup.get(new_board, float(\"inf\")):\n lookup[new_board] = f\n heapq.heappush(min_heap, (f, g+1, new_zero, new_board))\n return -1\n\n"}} diff --git a/cp/cp-10253.jsonl b/cp/cp-10253.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0d07eb73428cf9a9f4b250aaaf7bb7fdd891c91f --- /dev/null +++ b/cp/cp-10253.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10253", "name": "LeetCode 0777: Swap Adjacent In Lr 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: Swap Adjacent in LR String (Difficulty: Medium)\nTags: Two Pointers, String\n\nIn a string composed of 'L', 'R', and 'X' characters, like \"RXXLRXRXL\", a move consists of either replacing one occurrence of \"XL\" with \"LX\", or replacing one occurrence of \"RX\" with \"XR\". Given the starting string start and the ending string result, return True if and only if there exists a sequence of moves to transform start to result.\n\nExample 1:\nInput: start = \"RXXLRXRXL\", result = \"XRLXXRRLX\"\nOutput: true\nExplanation: We can transform start to result following these steps:\nRXXLRXRXL ->\nXRXLRXRXL ->\nXRLXRXRXL ->\nXRLXXRRXL ->\nXRLXXRRLX\n\nExample 2:\nInput: start = \"X\", result = \"L\"\nOutput: false\n\nConstraints:\n- 1 <= start.length <= 10^4\n- start.length == result.length\n- Both start and result will only consist of characters in 'L', 'R', and 'X'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# the followings are invariant if the number of 'X' in both strings are the same\n# 1. the ordering of 'L', 'R' in both strings are the same\n# 2. for each position (i, j) of paired 'L' character in both strings, i >= j\n# 3. for each position (i, j) of paired 'R' character in both strings, i <= j\nclass Solution(object):\n def canTransform(self, start, end):\n \"\"\"\n :type start: str\n :type end: str\n :rtype: bool\n \"\"\"\n if start.count('X') != end.count('X'):\n return False\n i, j = 0, 0\n while i < len(start) and j < len(end):\n while i < len(start) and start[i] == 'X':\n i += 1\n while j < len(end) and end[j] == 'X':\n j += 1\n if (i < len(start)) != (j < len(end)):\n return False\n elif i < len(start) and j < len(end):\n if start[i] != end[j] or \\\n (start[i] == 'L' and i < j) or \\\n (start[i] == 'R' and i > j):\n return False\n i += 1\n j += 1\n return True\n\n"}} diff --git a/cp/cp-10254.jsonl b/cp/cp-10254.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c032149858c81cf69bb308e9b9ab6558361a49bf --- /dev/null +++ b/cp/cp-10254.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10254", "name": "LeetCode 0778: Swim In Rising Water"} +{"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: Swim in Rising Water (Difficulty: Hard)\nTags: Array, Binary Search, Depth-First Search, Breadth-First Search, Union Find, Heap (Priority Queue), Matrix\n\nYou are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).\nIt starts raining, and water gradually rises over time. At time t, the water level is t, meaning any cell with elevation less than equal to t is submerged or reachable.\nYou can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.\nReturn the minimum time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0).\n\nExample 1:\nInput: grid = [[0,2],[1,3]]\nOutput: 3\nExplanation:\nAt time 0, you are in grid location (0, 0).\nYou cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\nYou cannot reach point (1, 1) until time 3.\nWhen the depth of water is 3, we can swim anywhere inside the grid.\n\nExample 2:\nInput: grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]\nOutput: 16\nExplanation: The final route is shown.\nWe need to wait until time 16 so that (0, 0) and (4, 4) are connected.\n\nConstraints:\n- n == grid.length\n- n == grid[i].length\n- 1 <= n <= 50\n- 0 <= grid[i][j] < n2\n- Each value grid[i][j] is unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2)\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n return True\n\n\nclass Solution(object):\n def swimInWater(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n n = len(grid)\n positions = [None] * (n**2)\n for i in range(n):\n for j in range(n):\n positions[grid[i][j]] = (i, j)\n directions = ((-1, 0), (1, 0), (0, -1), (0, 1))\n\n union_find = UnionFind(n**2)\n for elevation in range(n**2):\n i, j = positions[elevation]\n for direction in directions:\n x, y = i+direction[0], j+direction[1]\n if 0 <= x < n and 0 <= y < n and grid[x][y] <= elevation:\n union_find.union_set(i*n+j, x*n+y)\n if union_find.find_set(0) == union_find.find_set(n**2-1):\n return elevation\n return n**2-1\n\n\n"}} diff --git a/cp/cp-10255.jsonl b/cp/cp-10255.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1ad95381fd5292f125ac1ed062c6f155328e9af8 --- /dev/null +++ b/cp/cp-10255.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10255", "name": "LeetCode 0779: K Th Symbol In Grammar"} +{"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-th Symbol in Grammar (Difficulty: Medium)\nTags: Math, Bit Manipulation, Recursion\n\nWe build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.\nGiven two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.\n\nExample 1:\nInput: n = 1, k = 1\nOutput: 0\nExplanation: row 1: 0\n\nExample 2:\nInput: n = 2, k = 1\nOutput: 0\nExplanation: \nrow 1: 0\nrow 2: 01\n\nExample 3:\nInput: n = 2, k = 2\nOutput: 1\nExplanation: \nrow 1: 0\nrow 2: 01\n\nConstraints:\n- 1 <= n <= 30\n- 1 <= k <= 2n - 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn) = O(1) because n is 32-bit integer\n# Space: O(1)\n\nclass Solution(object):\n def kthGrammar(self, N, K):\n \"\"\"\n :type N: int\n :type K: int\n :rtype: int\n \"\"\"\n def bitCount(n):\n result = 0\n while n:\n n &= n - 1\n result += 1\n return result\n\n return bitCount(K-1) % 2\n\n"}} diff --git a/cp/cp-10256.jsonl b/cp/cp-10256.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0201084ae01949f357c5298df1430ff004f3826c --- /dev/null +++ b/cp/cp-10256.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10256", "name": "LeetCode 0780: Reaching Points"} +{"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: Reaching Points (Difficulty: Hard)\nTags: Math\n\nGiven four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise.\nThe allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).\n\nExample 1:\nInput: sx = 1, sy = 1, tx = 3, ty = 5\nOutput: true\nExplanation:\nOne series of moves that transforms the starting point to the target is:\n(1, 1) -> (1, 2)\n(1, 2) -> (3, 2)\n(3, 2) -> (3, 5)\n\nExample 2:\nInput: sx = 1, sy = 1, tx = 2, ty = 2\nOutput: false\n\nExample 3:\nInput: sx = 1, sy = 1, tx = 1, ty = 1\nOutput: true\n\nConstraints:\n- 1 <= sx, sy, tx, ty <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(log(max(m, n)))\n# Space: O(1)\n\nclass Solution(object):\n def reachingPoints(self, sx, sy, tx, ty):\n \"\"\"\n :type sx: int\n :type sy: int\n :type tx: int\n :type ty: int\n :rtype: bool\n \"\"\"\n while tx >= sx and ty >= sy:\n if tx < ty:\n sx, sy = sy, sx\n tx, ty = ty, tx\n if ty > sy:\n tx %= ty\n else:\n return (tx - sx) % ty == 0\n\n return False\n\n"}} diff --git a/cp/cp-10257.jsonl b/cp/cp-10257.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..22d33b210267f1627832daa981921723c6f0a647 --- /dev/null +++ b/cp/cp-10257.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10257", "name": "LeetCode 0781: Rabbits In Forest"} +{"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: Rabbits in Forest (Difficulty: Medium)\nTags: Array, Hash Table, Math, Greedy\n\nThere is a forest with an unknown number of rabbits. We asked n rabbits \"How many rabbits have the same color as you?\" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.\nGiven the array answers, return the minimum number of rabbits that could be in the forest.\n\nExample 1:\nInput: answers = [1,1,2]\nOutput: 5\nExplanation:\nThe two rabbits that answered \"1\" could both be the same color, say red.\nThe rabbit that answered \"2\" can't be red or the answers would be inconsistent.\nSay the rabbit that answered \"2\" was blue.\nThen there should be 2 other blue rabbits in the forest that didn't answer into the array.\nThe smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.\n\nExample 2:\nInput: answers = [10,10,10]\nOutput: 11\n\nConstraints:\n- 1 <= answers.length <= 1000\n- 0 <= answers[i] < 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def numRabbits(self, answers):\n \"\"\"\n :type answers: List[int]\n :rtype: int\n \"\"\"\n count = collections.Counter(answers)\n return sum((((k+1)+v-1)//(k+1))*(k+1) for k, v in count.iteritems())\n\n"}} diff --git a/cp/cp-10258.jsonl b/cp/cp-10258.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6da0ad1fbe53dbba6d6b98ea0a73ce948e140486 --- /dev/null +++ b/cp/cp-10258.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10258", "name": "LeetCode 0782: Transform To Chessboard"} +{"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: Transform to Chessboard (Difficulty: Hard)\nTags: Array, Math, Bit Manipulation, Matrix\n\nYou are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.\nReturn the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.\nA chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.\n\nExample 1:\nInput: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]\nOutput: 2\nExplanation: One potential sequence of moves is shown.\nThe first move swaps the first and second column.\nThe second move swaps the second and third row.\n\nExample 2:\nInput: board = [[0,1],[1,0]]\nOutput: 0\nExplanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.\n\nExample 3:\nInput: board = [[1,0],[1,0]]\nOutput: -1\nExplanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.\n\nConstraints:\n- n == board.length\n- n == board[i].length\n- 2 <= n <= 30\n- board[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2), used by Counter, this could be reduced to O(n) by skipping invalid input\n\nimport collections\nimport itertools\n\n\nclass Solution(object):\n def movesToChessboard(self, board):\n \"\"\"\n :type board: List[List[int]]\n :rtype: int\n \"\"\"\n N = len(board)\n result = 0\n for count in (collections.Counter(map(tuple, board)), \\\n collections.Counter(itertools.izip(*board))):\n if len(count) != 2 or \\\n sorted(count.values()) != [N/2, (N+1)/2]:\n return -1\n\n seq1, seq2 = count\n if any(x == y for x, y in itertools.izip(seq1, seq2)):\n return -1\n begins = [int(seq1.count(1) * 2 > N)] if N%2 else [0, 1]\n result += min(sum(int(i%2 != v) for i, v in enumerate(seq1, begin)) \\\n for begin in begins) / 2\n return result\n\n"}} diff --git a/cp/cp-10259.jsonl b/cp/cp-10259.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bf6d5e1b2e6e422b852f9e25e6373150a8953f99 --- /dev/null +++ b/cp/cp-10259.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10259", "name": "LeetCode 0783: Minimum Distance Between Bst Nodes"} +{"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: Minimum Distance Between BST Nodes (Difficulty: Easy)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Search Tree, Binary Tree\n\nGiven the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.\nNote: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/\n\nExample 1:\nInput: root = [4,2,6,1,3]\nOutput: 1\n\nExample 2:\nInput: root = [1,0,48,null,null,12,49]\nOutput: 1\n\nConstraints:\n- The number of nodes in the tree is in the range [2, 100].\n- 0 <= Node.val <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nclass Solution(object):\n def minDiffInBST(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def dfs(node):\n if not node:\n return\n dfs(node.left)\n self.result = min(self.result, node.val-self.prev)\n self.prev = node.val\n dfs(node.right)\n\n self.prev = float('-inf')\n self.result = float('inf')\n dfs(root)\n return self.result\n\n\n"}} diff --git a/cp/cp-10260.jsonl b/cp/cp-10260.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ec56a2f501a4d3eac5a2c722d480a6d86aa963db --- /dev/null +++ b/cp/cp-10260.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10260", "name": "LeetCode 0784: Letter Case Permutation"} +{"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: Letter Case Permutation (Difficulty: Medium)\nTags: String, Backtracking, Bit Manipulation\n\nGiven a string s, you can transform every letter individually to be lowercase or uppercase to create another string.\nReturn a list of all possible strings we could create. Return the output in any order.\n\nExample 1:\nInput: s = \"a1b2\"\nOutput: [\"a1b2\",\"a1B2\",\"A1b2\",\"A1B2\"]\n\nExample 2:\nInput: s = \"3z4\"\nOutput: [\"3z4\",\"3Z4\"]\n\nConstraints:\n- 1 <= s.length <= 12\n- s consists of lowercase English letters, uppercase English letters, and digits."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * 2^n)\n# Space: O(n * 2^n)\n\nclass Solution(object):\n def letterCasePermutation(self, S):\n \"\"\"\n :type S: str\n :rtype: List[str]\n \"\"\"\n result = [[]]\n for c in S:\n if c.isalpha():\n for i in range(len(result)):\n result.append(result[i][:])\n result[i].append(c.lower())\n result[-1].append(c.upper())\n else:\n for s in result:\n s.append(c)\n return map(\"\".join, result)\n\n"}} diff --git a/cp/cp-10261.jsonl b/cp/cp-10261.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3f87e7f4b847eed1fd234a0d76f10ba87884b21e --- /dev/null +++ b/cp/cp-10261.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10261", "name": "LeetCode 0785: Is Graph Bipartite"} +{"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: Is Graph Bipartite? (Difficulty: Medium)\nTags: Depth-First Search, Breadth-First Search, Union Find, Graph\n\nThere is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:\nA graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.\nReturn true if and only if it is bipartite.\n\nExample 1:\nInput: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]\nOutput: false\nExplanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.\n\nExample 2:\nInput: graph = [[1,3],[0,2],[1,3],[0,2]]\nOutput: true\nExplanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.\n\nConstraints:\n- graph.length == n\n- 1 <= n <= 100\n- 0 <= graph[u].length < n\n- 0 <= graph[u][i] <= n - 1\n- graph[u] does not contain u.\n- All the values of graph[u] are unique.\n- If graph[u] contains v, then graph[v] contains u."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(|V| + |E|)\n# Space: O(|V|)\n\nclass Solution(object):\n def isBipartite(self, graph):\n \"\"\"\n :type graph: List[List[int]]\n :rtype: bool\n \"\"\"\n color = {}\n for node in range(len(graph)):\n if node in color:\n continue\n stack = [node]\n color[node] = 0\n while stack:\n curr = stack.pop()\n for neighbor in graph[curr]:\n if neighbor not in color:\n stack.append(neighbor)\n color[neighbor] = color[curr] ^ 1\n elif color[neighbor] == color[curr]:\n return False\n return True\n\n"}} diff --git a/cp/cp-10262.jsonl b/cp/cp-10262.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3eba907a44b8662f05c47432107c48fd33424561 --- /dev/null +++ b/cp/cp-10262.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10262", "name": "LeetCode 0786: K Th Smallest Prime Fraction"} +{"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-th Smallest Prime Fraction (Difficulty: Medium)\nTags: Array, Two Pointers, Binary Search, Sorting, Heap (Priority Queue)\n\nYou are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.\nFor every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].\nReturn the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].\n\nExample 1:\nInput: arr = [1,2,3,5], k = 3\nOutput: [2,5]\nExplanation: The fractions to be considered in sorted order are:\n1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.\nThe third fraction is 2/5.\n\nExample 2:\nInput: arr = [1,7], k = 1\nOutput: [1,7]\n\nConstraints:\n- 2 <= arr.length <= 1000\n- 1 <= arr[i] <= 3 * 10^4\n- arr[0] == 1\n- arr[i] is a prime number for i > 0.\n- All the numbers of arr are unique and sorted in strictly increasing order.\n- 1 <= k <= arr.length * (arr.length - 1) / 2"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogr)\n# Space: O(1)\n\nclass Solution(object):\n def kthSmallestPrimeFraction(self, A, K):\n \"\"\"\n :type A: List[int]\n :type K: int\n :rtype: List[int]\n \"\"\"\n def check(mid, A, K, result):\n tmp = [0]*2\n count = 0\n j = 0\n for i in range(len(A)):\n while j < len(A):\n if i < j and A[i] < A[j]*mid:\n if tmp[0] == 0 or \\\n tmp[0]*A[j] < tmp[1]*A[i]:\n tmp[0] = A[i]\n tmp[1] = A[j]\n break\n j += 1\n count += len(A)-j\n if count == K:\n result[:] = tmp\n return count >= K\n\n result = []\n left, right = 0.0, 1.0\n while right-left > 1e-8:\n mid = left + (right-left) / 2.0\n if check(mid, A, K, result):\n right = mid\n else:\n left = mid\n if result:\n break\n return result\n\n"}} diff --git a/cp/cp-10263.jsonl b/cp/cp-10263.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5acda640355b8a80e1791164cdb79481b796dfcb --- /dev/null +++ b/cp/cp-10263.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10263", "name": "LeetCode 0787: Cheapest Flights Within K Stops"} +{"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: Cheapest Flights Within K Stops (Difficulty: Medium)\nTags: Dynamic Programming, Depth-First Search, Breadth-First Search, Graph, Heap (Priority Queue), Shortest Path\n\nThere are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.\nYou are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.\n\nExample 1:\nInput: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1\nOutput: 700\nExplanation:\nThe graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.\nNote that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.\n\nExample 2:\nInput: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1\nOutput: 200\nExplanation:\nThe graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.\n\nExample 3:\nInput: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0\nOutput: 500\nExplanation:\nThe graph is shown above.\nThe optimal path with no stops from city 0 to 2 is marked in red and has cost 500.\n\nConstraints:\n- 1 <= n <= 100\n- 0 <= flights.length <= (n * (n - 1) / 2)\n- flights[i].length == 3\n- 0 <= fromi, toi < n\n- fromi != toi\n- 1 <= pricei <= 10^4\n- There will not be any multiple flights between two cities.\n- 0 <= src, dst, k < n\n- src != dst"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|),\n# if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|)\n# Space: O(|E| + |V|) = O(|E|)\n\nimport collections\nimport heapq\n\n\nclass Solution(object):\n def findCheapestPrice(self, n, flights, src, dst, K):\n \"\"\"\n :type n: int\n :type flights: List[List[int]]\n :type src: int\n :type dst: int\n :type K: int\n :rtype: int\n \"\"\"\n adj = collections.defaultdict(list)\n for u, v, w in flights:\n adj[u].append((v, w))\n best = collections.defaultdict(lambda: collections.defaultdict(lambda: float(\"inf\")))\n best[src][K+1] = 0\n min_heap = [(0, src, K+1)]\n while min_heap:\n result, u, k = heapq.heappop(min_heap)\n if k < 0 or best[u][k] < result:\n continue\n if u == dst:\n return result\n for v, w in adj[u]:\n if result+w < best[v][k-1]:\n best[v][k-1] = result+w \n heapq.heappush(min_heap, (result+w, v, k-1))\n return -1\n\n"}} diff --git a/cp/cp-10264.jsonl b/cp/cp-10264.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9cd8886cf109225326d4397e85bcc9e81bd11082 --- /dev/null +++ b/cp/cp-10264.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10264", "name": "LeetCode 0788: Rotated Digits"} +{"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: Rotated Digits (Difficulty: Medium)\nTags: Math, Dynamic Programming\n\nAn integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone.\nA number is valid if each digit remains a digit after rotation. For example:\nGiven an integer n, return the number of good integers in the range [1, n].\n\nExample 1:\nInput: n = 10\nOutput: 4\nExplanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9.\nNote that 1 and 10 are not good numbers, since they remain unchanged after rotating.\n\nExample 2:\nInput: n = 1\nOutput: 0\n\nExample 3:\nInput: n = 2\nOutput: 1\n\nConstraints:\n- 1 <= n <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(logn)\n\nclass Solution(object):\n def rotatedDigits(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n A = map(int, str(N))\n invalid, diff = set([3, 4, 7]), set([2, 5, 6, 9])\n def dp(A, i, is_prefix_equal, is_good, lookup):\n if i == len(A): return int(is_good)\n if (i, is_prefix_equal, is_good) not in lookup:\n result = 0\n for d in range(A[i]+1 if is_prefix_equal else 10):\n if d in invalid: continue\n result += dp(A, i+1,\n is_prefix_equal and d == A[i],\n is_good or d in diff,\n lookup)\n lookup[i, is_prefix_equal, is_good] = result\n return lookup[i, is_prefix_equal, is_good]\n\n lookup = {}\n return dp(A, 0, True, False, lookup)\n\n\n# Time: O(n)\n# Space: O(n)\nclass Solution2(object):\n def rotatedDigits(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n INVALID, SAME, DIFF = 0, 1, 2\n same, diff = [0, 1, 8], [2, 5, 6, 9]\n dp = [0] * (N+1)\n dp[0] = SAME\n for i in range(N//10+1):\n if dp[i] != INVALID:\n for j in same:\n if i*10+j <= N:\n dp[i*10+j] = max(SAME, dp[i])\n for j in diff:\n if i*10+j <= N:\n dp[i*10+j] = DIFF\n return dp.count(DIFF)\n\n\n# Time: O(nlogn) = O(n), because O(logn) = O(32) by this input\n# Space: O(logn) = O(1)\nclass Solution3(object):\n def rotatedDigits(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n invalid, diff = set(['3', '4', '7']), set(['2', '5', '6', '9'])\n result = 0\n for i in range(N+1):\n lookup = set(list(str(i)))\n if invalid & lookup:\n continue\n if diff & lookup:\n result += 1\n return result\n\n\n"}} diff --git a/cp/cp-10265.jsonl b/cp/cp-10265.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..14669646c67b63bbab6ef33a5c921f16f4c6be76 --- /dev/null +++ b/cp/cp-10265.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10265", "name": "LeetCode 0789: Escape The Ghosts"} +{"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: Escape The Ghosts (Difficulty: Medium)\nTags: Array, Math\n\nYou are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [xtarget, ytarget] that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array ghosts, where ghosts[i] = [xi, yi] represents the starting position of the ith ghost. All inputs are integral coordinates.\nEach turn, you and all the ghosts may independently choose to either move 1 unit in any of the four cardinal directions: north, east, south, or west, or stay still. All actions happen simultaneously.\nYou escape if and only if you can reach the target before any ghost reaches you. If you reach any square (including the target) at the same time as a ghost, it does not count as an escape.\nReturn true if it is possible to escape regardless of how the ghosts move, otherwise return false.\n\nExample 1:\nInput: ghosts = [[1,0],[0,3]], target = [0,1]\nOutput: true\nExplanation: You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you.\n\nExample 2:\nInput: ghosts = [[1,0]], target = [2,0]\nOutput: false\nExplanation: You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.\n\nExample 3:\nInput: ghosts = [[2,0]], target = [1,0]\nOutput: false\nExplanation: The ghost can reach the target at the same time as you.\n\nConstraints:\n- 1 <= ghosts.length <= 100\n- ghosts[i].length == 2\n- -10^4 <= xi, yi <= 10^4\n- There can be multiple ghosts in the same location.\n- target.length == 2\n- -10^4 <= xtarget, ytarget <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def escapeGhosts(self, ghosts, target):\n \"\"\"\n :type ghosts: List[List[int]]\n :type target: List[int]\n :rtype: bool\n \"\"\"\n total = abs(target[0])+abs(target[1])\n return all(total < abs(target[0]-i)+abs(target[1]-j) for i, j in ghosts)\n\n"}} diff --git a/cp/cp-10266.jsonl b/cp/cp-10266.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9ffbc555be6f26dfaeb049cf5e7f1d04cec4f094 --- /dev/null +++ b/cp/cp-10266.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10266", "name": "LeetCode 0790: Domino And Tromino Tiling"} +{"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: Domino and Tromino Tiling (Difficulty: Medium)\nTags: Dynamic Programming\n\nYou have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.\nGiven an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7.\nIn a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.\n\nExample 1:\nInput: n = 3\nOutput: 5\nExplanation: The five different ways are shown above.\n\nExample 2:\nInput: n = 1\nOutput: 1\n\nConstraints:\n- 1 <= n <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def numTilings(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n M = int(1e9+7)\n\n def matrix_expo(A, K):\n result = [[int(i==j) for j in range(len(A))] \\\n for i in range(len(A))]\n while K:\n if K % 2:\n result = matrix_mult(result, A)\n A = matrix_mult(A, A)\n K /= 2\n return result\n\n def matrix_mult(A, B):\n ZB = zip(*B)\n return [[sum(a*b for a, b in itertools.izip(row, col)) % M \\\n for col in ZB] for row in A]\n\n T = [[1, 0, 0, 1], # #(|) = #(|) + #(=)\n [1, 0, 1, 0], # #(「) = #(|) + #(L)\n [1, 1, 0, 0], # #(L) = #(|) + #(「)\n [1, 1, 1, 0]] # #(=) = #(|) + #(「) + #(L)\n\n return matrix_mult([[1, 0, 0, 0]], matrix_expo(T, N))[0][0] # [a0, a(-1), a(-2), a(-3)] * T^N\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def numTilings(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n # Prove:\n # dp[n] = dp[n-1](|) + dp[n-2](=) + 2*(dp[n-3](「」) + ... + d[0](「 = ... = 」))\n # = dp[n-1] + dp[n-2] + dp[n-3] + dp[n-3] + 2*(dp[n-4] + ... + d[0])\n # = dp[n-1] + dp[n-3] + (dp[n-2] + dp[n-3] + 2*(dp[n-4] + ... + d[0])\n # = dp[n-1] + dp[n-3] + dp[n-1]\n # = 2*dp[n-1] + dp[n-3]\n M = int(1e9+7)\n dp = [1, 1, 2]\n for i in range(3, N+1):\n dp[i%3] = (2*dp[(i-1)%3]%M + dp[(i-3)%3])%M\n return dp[N%3]\n"}} diff --git a/cp/cp-10267.jsonl b/cp/cp-10267.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b9c0f6f414b745bdc94a68b12ff8f0cdd25753b0 --- /dev/null +++ b/cp/cp-10267.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10267", "name": "LeetCode 0791: Custom Sort 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: Custom Sort String (Difficulty: Medium)\nTags: Hash Table, String, Sorting\n\nYou are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.\nPermute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.\nReturn any permutation of s that satisfies this property.\n\nExample 1:\nInput: order = \"cba\", s = \"abcd\"\nOutput: \"cbad\"\nExplanation: \"a\" , \"b\" , \"c\" appear in order, so the order of \"a\" , \"b\" , \"c\" should be \"c\" , \"b\" , and \"a\" .\nSince \"d\" does not appear in order , it can be at any position in the returned string. \"dcba\" , \"cdba\" , \"cbda\" are also valid outputs.\n\nExample 2:\nInput: order = \"bcafg\", s = \"abcd\"\nOutput: \"bcad\"\nExplanation: The characters \"b\" , \"c\" , and \"a\" from order dictate the order for the characters in s . The character \"d\" in s does not appear in order , so its position is flexible.\nFollowing the order of appearance in order , \"b\" , \"c\" , and \"a\" from s should be arranged as \"b\" , \"c\" , \"a\" . \"d\" can be placed at any position since it's not in order. The output \"bcad\" correctly follows this rule. Other arrangements like \"dbca\" or \"bcda\" would also be valid, as long as \"b\" , \"c\" , \"a\" maintain their order.\n\nConstraints:\n- 1 <= order.length <= 26\n- 1 <= s.length <= 200\n- order and s consist of lowercase English letters.\n- All the characters of order are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def customSortString(self, S, T):\n \"\"\"\n :type S: str\n :type T: str\n :rtype: str\n \"\"\"\n counter, s = collections.Counter(T), set(S)\n result = [c*counter[c] for c in S]\n result.extend([c*counter for c, counter in counter.iteritems() if c not in s])\n return \"\".join(result)\n\n"}} diff --git a/cp/cp-10268.jsonl b/cp/cp-10268.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..92e1be6b0a2becb38caeb4f6aad74f089bd2c3c2 --- /dev/null +++ b/cp/cp-10268.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10268", "name": "LeetCode 0792: Number Of Matching 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: Number of Matching Subsequences (Difficulty: Medium)\nTags: Array, Hash Table, String, Binary Search, Dynamic Programming, Trie, Sorting\n\nGiven a string s and an array of strings words, return the number of words[i] that is a subsequence of s.\nA subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.\n\nExample 1:\nInput: s = \"abcde\", words = [\"a\",\"bb\",\"acd\",\"ace\"]\nOutput: 3\nExplanation: There are three strings in words that are a subsequence of s: \"a\", \"acd\", \"ace\".\n\nExample 2:\nInput: s = \"dsahjpjauf\", words = [\"ahjpjau\",\"ja\",\"ahbwzgqnuk\",\"tnmlanowax\"]\nOutput: 2\n\nConstraints:\n- 1 <= s.length <= 5 * 10^4\n- 1 <= words.length <= 5000\n- 1 <= words[i].length <= 50\n- s and words[i] consist of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + w), n is the size of S, w is the size of words\n# Space: O(k), k is the number of words\n\nimport collections\n\n\nclass Solution(object):\n def numMatchingSubseq(self, S, words):\n \"\"\"\n :type S: str\n :type words: List[str]\n :rtype: int\n \"\"\"\n waiting = collections.defaultdict(list)\n for word in words:\n it = iter(word)\n waiting[next(it, None)].append(it)\n for c in S:\n for it in waiting.pop(c, ()):\n waiting[next(it, None)].append(it)\n return len(waiting[None])\n\n"}} diff --git a/cp/cp-10269.jsonl b/cp/cp-10269.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cfc2b4fa6b8cfa4613828a801656e452e4f4c0f0 --- /dev/null +++ b/cp/cp-10269.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10269", "name": "LeetCode 0793: Preimage Size Of Factorial Zeroes Function"} +{"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: Preimage Size of Factorial Zeroes Function (Difficulty: Hard)\nTags: Math, Binary Search\n\nLet f(x) be the number of zeroes at the end of x!. Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1.\nGiven an integer k, return the number of non-negative integers x have the property that f(x) = k.\n\nExample 1:\nInput: k = 0\nOutput: 5\nExplanation: 0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.\n\nExample 2:\nInput: k = 5\nOutput: 0\nExplanation: There is no x such that x! ends in k = 5 zeroes.\n\nExample 3:\nInput: k = 3\nOutput: 5\n\nConstraints:\n- 0 <= k <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((logn)^2)\n# Space: O(1)\n\nclass Solution(object):\n def preimageSizeFZF(self, K):\n \"\"\"\n :type K: int\n :rtype: int\n \"\"\"\n def count_of_factorial_primes(n, p):\n cnt = 0\n while n > 0:\n cnt += n//p\n n //= p\n return cnt\n\n p = 5\n left, right = 0, p*K\n while left <= right:\n mid = left + (right-left)//2\n if count_of_factorial_primes(mid, p) >= K:\n right = mid-1\n else:\n left = mid+1\n return p if count_of_factorial_primes(left, p) == K else 0\n\n"}} diff --git a/cp/cp-10270.jsonl b/cp/cp-10270.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e86d4632d333f1c47fff995bdb768a292689775b --- /dev/null +++ b/cp/cp-10270.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10270", "name": "LeetCode 0794: Valid Tic Tac Toe State"} +{"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 Tic-Tac-Toe State (Difficulty: Medium)\nTags: Array, Matrix\n\nGiven a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.\nThe board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square.\nHere are the rules of Tic-Tac-Toe:\n\nExample 1:\nInput: board = [\"O \",\" \",\" \"]\nOutput: false\nExplanation: The first player always plays \"X\".\n\nExample 2:\nInput: board = [\"XOX\",\" X \",\" \"]\nOutput: false\nExplanation: Players take turns making moves.\n\nExample 3:\nInput: board = [\"XOX\",\"O O\",\"XOX\"]\nOutput: true\n\nConstraints:\n- board.length == 3\n- board[i].length == 3\n- board[i][j] is either 'X', 'O', or ' '."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def validTicTacToe(self, board):\n \"\"\"\n :type board: List[str]\n :rtype: bool\n \"\"\"\n def win(board, player):\n for i in range(3):\n if all(board[i][j] == player for j in range(3)):\n return True\n if all(board[j][i] == player for j in range(3)):\n return True\n\n return (player == board[1][1] == board[0][0] == board[2][2] or \\\n player == board[1][1] == board[0][2] == board[2][0])\n\n FIRST, SECOND = ('X', 'O')\n x_count = sum(row.count(FIRST) for row in board)\n o_count = sum(row.count(SECOND) for row in board)\n if o_count not in {x_count-1, x_count}: return False\n if win(board, FIRST) and x_count-1 != o_count: return False\n if win(board, SECOND) and x_count != o_count: return False\n\n return True\n\n"}} diff --git a/cp/cp-10271.jsonl b/cp/cp-10271.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..02f7d3d006512683a5aec6372cdf173ed7375310 --- /dev/null +++ b/cp/cp-10271.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10271", "name": "LeetCode 0795: Number Of Subarrays With Bounded Maximum"} +{"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 Subarrays with Bounded Maximum (Difficulty: Medium)\nTags: Array, Two Pointers\n\nGiven an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].\nThe test cases are generated so that the answer will fit in a 32-bit integer.\n\nExample 1:\nInput: nums = [2,1,4,3], left = 2, right = 3\nOutput: 3\nExplanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].\n\nExample 2:\nInput: nums = [2,9,2,5,6], left = 2, right = 8\nOutput: 7\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 0 <= nums[i] <= 10^9\n- 0 <= left <= right <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def numSubarrayBoundedMax(self, A, L, R):\n \"\"\"\n :type A: List[int]\n :type L: int\n :type R: int\n :rtype: int\n \"\"\"\n def count(A, bound):\n result, curr = 0, 0\n for i in A :\n curr = curr + 1 if i <= bound else 0\n result += curr\n return result\n\n return count(A, R) - count(A, L-1)\n\n"}} diff --git a/cp/cp-10272.jsonl b/cp/cp-10272.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b34a3c9e2a8bde11c44607fe0c2b6a62cc48f926 --- /dev/null +++ b/cp/cp-10272.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10272", "name": "LeetCode 0796: Rotate 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: Rotate String (Difficulty: Easy)\nTags: String, String Matching\n\nGiven two strings s and goal, return true if and only if s can become goal after some number of shifts on s.\nA shift on s consists of moving the leftmost character of s to the rightmost position.\n\nExample 1:\nInput: s = \"abcde\", goal = \"cdeab\"\nOutput: true\n\nExample 2:\nInput: s = \"abcde\", goal = \"abced\"\nOutput: false\n\nConstraints:\n- 1 <= s.length, goal.length <= 100\n- s and goal consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def rotateString(self, A, B):\n \"\"\"\n :type A: str\n :type B: str\n :rtype: bool\n \"\"\"\n def check(index):\n return all(A[(i+index) % len(A)] == c\n for i, c in enumerate(B))\n\n if len(A) != len(B):\n return False\n\n M, p = 10**9+7, 113\n p_inv = pow(p, M-2, M)\n\n b_hash, power = 0, 1\n for c in B:\n b_hash += power * ord(c)\n b_hash %= M\n power = (power*p) % M\n\n a_hash, power = 0, 1\n for i in range(len(B)):\n a_hash += power * ord(A[i%len(A)])\n a_hash %= M\n power = (power*p) % M\n\n if a_hash == b_hash and check(0): return True\n\n power = (power*p_inv) % M\n for i in range(len(B), 2*len(A)):\n a_hash = (a_hash-ord(A[(i-len(B))%len(A)])) * p_inv\n a_hash += power * ord(A[i%len(A)])\n a_hash %= M\n if a_hash == b_hash and check(i-len(B)+1):\n return True\n\n return False\n\n\n# Time: O(n)\n# Space: O(n)\n# KMP algorithm\nclass Solution2(object):\n def rotateString(self, A, B):\n \"\"\"\n :type A: str\n :type B: str\n :rtype: bool\n \"\"\"\n def strStr(haystack, needle):\n def KMP(text, pattern):\n prefix = getPrefix(pattern)\n j = -1\n for i in range(len(text)):\n while j > -1 and pattern[j + 1] != text[i]:\n j = prefix[j]\n if pattern[j + 1] == text[i]:\n j += 1\n if j == len(pattern) - 1:\n return i - j\n return -1\n\n def getPrefix(pattern):\n prefix = [-1] * len(pattern)\n j = -1\n for i in range(1, len(pattern)):\n while j > -1 and pattern[j + 1] != pattern[i]:\n j = prefix[j]\n if pattern[j + 1] == pattern[i]:\n j += 1\n prefix[i] = j\n return prefix\n\n if not needle:\n return 0\n return KMP(haystack, needle)\n\n if len(A) != len(B):\n return False\n return strStr(A*2, B) != -1\n\n\n# Time: O(n^2)\n# Space: O(n)\nclass Solution3(object):\n def rotateString(self, A, B):\n \"\"\"\n :type A: str\n :type B: str\n :rtype: bool\n \"\"\"\n return len(A) == len(B) and B in A*2\n\n"}} diff --git a/cp/cp-10273.jsonl b/cp/cp-10273.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..13b4dc938cd7f34a4464016ab2271d5d12954aa1 --- /dev/null +++ b/cp/cp-10273.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10273", "name": "LeetCode 0797: All Paths From Source To Target"} +{"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: All Paths From Source to Target (Difficulty: Medium)\nTags: Backtracking, Depth-First Search, Breadth-First Search, Graph\n\nGiven a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.\nThe graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).\n\nExample 1:\nInput: graph = [[1,2],[3],[3],[]]\nOutput: [[0,1,3],[0,2,3]]\nExplanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.\n\nExample 2:\nInput: graph = [[4,3,1],[3,2,4],[3],[4],[]]\nOutput: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]\n\nConstraints:\n- n == graph.length\n- 2 <= n <= 15\n- 0 <= graph[i][j] < n\n- graph[i][j] != i (i.e., there will be no self-loops).\n- All the elements of graph[i] are unique.\n- The input graph is guaranteed to be a DAG."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(p + r * n), p is the count of all the possible paths in graph,\n# r is the count of the result.\n# Space: O(n)\n\nclass Solution(object):\n def allPathsSourceTarget(self, graph):\n \"\"\"\n :type graph: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n def dfs(graph, curr, path, result):\n if curr == len(graph)-1:\n result.append(path[:])\n return\n for node in graph[curr]:\n path.append(node)\n dfs(graph, node, path, result)\n path.pop()\n\n result = []\n dfs(graph, 0, [0], result)\n return result\n\n"}} diff --git a/cp/cp-10274.jsonl b/cp/cp-10274.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..76a3252b88004729f0ff3ceaa1481e56e65ea2d2 --- /dev/null +++ b/cp/cp-10274.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10274", "name": "LeetCode 0798: Smallest Rotation With Highest Score"} +{"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: Smallest Rotation with Highest Score (Difficulty: Hard)\nTags: Array, Prefix Sum\n\nYou are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. Afterward, any entries that are less than or equal to their index are worth one point.\nReturn the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it. If there are multiple answers, return the smallest such index k.\n\nExample 1:\nInput: nums = [2,3,1,4,0]\nOutput: 3\nExplanation: Scores for each k are listed below: \nk = 0, nums = [2,3,1,4,0], score 2\nk = 1, nums = [3,1,4,0,2], score 3\nk = 2, nums = [1,4,0,2,3], score 3\nk = 3, nums = [4,0,2,3,1], score 4\nk = 4, nums = [0,2,3,1,4], score 3\nSo we should choose k = 3, which has the highest score.\n\nExample 2:\nInput: nums = [1,3,0,2,4]\nOutput: 0\nExplanation: nums will always have 3 points no matter how it shifts.\nSo we will choose the smallest k, which is 0.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 0 <= nums[i] < nums.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def bestRotation(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n N = len(A)\n change = [1] * N\n for i in range(N):\n change[(i-A[i]+1)%N] -= 1\n for i in range(1, N):\n change[i] += change[i-1]\n return change.index(max(change))\n\n\n"}} diff --git a/cp/cp-10275.jsonl b/cp/cp-10275.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b41e2115d39e663f5735cb6019e90b7ac05259ed --- /dev/null +++ b/cp/cp-10275.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10275", "name": "LeetCode 0799: Champagne Tower"} +{"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: Champagne Tower (Difficulty: Medium)\nTags: Dynamic Programming\n\nWe stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.  Each glass holds one cup of champagne.\nThen, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.)\nFor example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.\nNow after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.)\n\nExample 1:\nInput: poured = 1, query_row = 1, query_glass = 1\r\nOutput: 0.00000\r\nExplanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.\n\nExample 2:\nInput: poured = 2, query_row = 1, query_glass = 1\r\nOutput: 0.50000\r\nExplanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.\n\nExample 3:\nInput: poured = 100000009, query_row = 33, query_glass = 17\r\nOutput: 1.00000\n\nConstraints:\n- 0 <= poured <= 10^9\n- 0 <= query_glass <= query_row < 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2) = O(1), since n is at most 99\n# Space: O(n) = O(1)\n\nclass Solution(object):\n def champagneTower(self, poured, query_row, query_glass):\n \"\"\"\n :type poured: int\n :type query_row: int\n :type query_glass: int\n :rtype: float\n \"\"\"\n result = [poured] + [0] * query_row\n for i in range(1, query_row+1):\n for j in reversed(range(i+1)):\n result[j] = max(result[j]-1, 0)/2.0 + \\\n max(result[j-1]-1, 0)/2.0\n return min(result[query_glass], 1)\n\n"}} diff --git a/cp/cp-10277.jsonl b/cp/cp-10277.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9c06c060d78980387d4722f68e744af03ff35b47 --- /dev/null +++ b/cp/cp-10277.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10277", "name": "LeetCode 0801: Minimum Swaps To Make Sequences Increasing"} +{"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: Minimum Swaps To Make Sequences Increasing (Difficulty: Hard)\nTags: Array, Dynamic Programming\n\nYou are given two integer arrays of the same length nums1 and nums2. In one operation, you are allowed to swap nums1[i] with nums2[i].\nReturn the minimum number of needed operations to make nums1 and nums2 strictly increasing. The test cases are generated so that the given input always makes it possible.\nAn array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1].\n\nExample 1:\nInput: nums1 = [1,3,5,4], nums2 = [1,2,3,7]\nOutput: 1\nExplanation: \nSwap nums1[3] and nums2[3]. Then the sequences are:\nnums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]\nwhich are both strictly increasing.\n\nExample 2:\nInput: nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]\nOutput: 1\n\nConstraints:\n- 2 <= nums1.length <= 10^5\n- nums2.length == nums1.length\n- 0 <= nums1[i], nums2[i] <= 2 * 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minSwap(self, A, B):\n \"\"\"\n :type A: List[int]\n :type B: List[int]\n :rtype: int\n \"\"\"\n dp_no_swap, dp_swap = [0]*2, [1]*2\n for i in range(1, len(A)):\n dp_no_swap[i%2], dp_swap[i%2] = float(\"inf\"), float(\"inf\")\n if A[i-1] < A[i] and B[i-1] < B[i]:\n dp_no_swap[i%2] = min(dp_no_swap[i%2], dp_no_swap[(i-1)%2])\n dp_swap[i%2] = min(dp_swap[i%2], dp_swap[(i-1)%2]+1)\n if A[i-1] < B[i] and B[i-1] < A[i]:\n dp_no_swap[i%2] = min(dp_no_swap[i%2], dp_swap[(i-1)%2])\n dp_swap[i%2] = min(dp_swap[i%2], dp_no_swap[(i-1)%2]+1)\n return min(dp_no_swap[(len(A)-1)%2], dp_swap[(len(A)-1)%2])\n\n"}} diff --git a/cp/cp-10278.jsonl b/cp/cp-10278.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..852d24968313f73f8764a227948c51d82a68217f --- /dev/null +++ b/cp/cp-10278.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10278", "name": "LeetCode 0802: Find Eventual Safe States"} +{"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 Eventual Safe States (Difficulty: Medium)\nTags: Depth-First Search, Breadth-First Search, Graph, Topological Sort\n\nThere is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].\nA node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node).\nReturn an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.\n\nExample 1:\nInput: graph = [[1,2],[2,3],[5],[0],[5],[],[]]\nOutput: [2,4,5,6]\nExplanation: The given graph is shown above.\nNodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.\nEvery path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.\n\nExample 2:\nInput: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]\nOutput: [4]\nExplanation:\nOnly node 4 is a terminal node, and every path starting at node 4 leads to node 4.\n\nConstraints:\n- n == graph.length\n- 1 <= n <= 10^4\n- 0 <= graph[i].length <= n\n- 0 <= graph[i][j] <= n - 1\n- graph[i] is sorted in a strictly increasing order.\n- The graph may contain self-loops.\n- The number of edges in the graph will be in the range [1, 4 * 10^4]."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(|V| + |E|)\n# Space: O(|V|)\n\nclass Solution(object):\n def eventualSafeNodes(self, graph):\n \"\"\"\n :type graph: List[List[int]]\n :rtype: List[int]\n \"\"\"\n WHITE, GRAY, BLACK = range(3)\n\n def dfs(graph, node, lookup):\n if lookup[node] != WHITE:\n return lookup[node] == BLACK\n lookup[node] = GRAY\n if any(not dfs(graph, child, lookup) for child in graph[node]):\n return False\n lookup[node] = BLACK\n return True\n\n lookup = [WHITE]*len(graph)\n return filter(lambda node: dfs(graph, node, lookup), range(len(graph)))\n"}} diff --git a/cp/cp-10279.jsonl b/cp/cp-10279.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd09e5dc17043fa6a7190f0c04e48a341bea40ff --- /dev/null +++ b/cp/cp-10279.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10279", "name": "LeetCode 0803: Bricks Falling When Hit"} +{"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: Bricks Falling When Hit (Difficulty: Hard)\nTags: Array, Union Find, Matrix\n\nYou are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if:\nYou are also given an array hits, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks).\nReturn an array result, where each result[i] is the number of bricks that will fall after the ith erasure is applied.\nNote that an erasure may refer to a location with no brick, and if it does, no bricks drop.\n\nExample 1:\nInput: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]\nOutput: [2]\nExplanation: Starting with the grid:\n[[1,0,0,0],\n [1,1,1,0]]\nWe erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,1,1,0]]\nThe two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:\n[[1,0,0,0],\n [0,0,0,0]]\nHence the result is [2].\n\nExample 2:\nInput: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]\nOutput: [0,0]\nExplanation: Starting with the grid:\n[[1,0,0,0],\n [1,1,0,0]]\nWe erase the underlined brick at (1,1), resulting in the grid:\n[[1,0,0,0],\n [1,0,0,0]]\nAll remaining bricks are still stable, so no bricks fall. The grid remains the same:\n[[1,0,0,0],\n [1,0,0,0]]\nNext, we erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,0,0,0]]\nOnce again, all remaining bricks are still stable, so no bricks fall.\nHence the result is [0,0].\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 200\n- grid[i][j] is 0 or 1.\n- 1 <= hits.length <= 4 * 10^4\n- hits[i].length == 2\n- 0 <= xi <= m - 1\n- 0 <= yi <= n - 1\n- All (xi, yi) are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(r * c)\n# Space: O(r * c)\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n+1)\n self.size = [1]*(n+1)\n self.size[-1] = 0\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n self.size[max(x_root, y_root)] += self.size[min(x_root, y_root)]\n return True\n\n def top(self):\n return self.size[self.find_set(len(self.size)-1)]\n\n\nclass Solution(object):\n def hitBricks(self, grid, hits):\n \"\"\"\n :type grid: List[List[int]]\n :type hits: List[List[int]]\n :rtype: List[int]\n \"\"\"\n def index(C, r, c):\n return r*C+c\n\n directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n R, C = len(grid), len(grid[0])\n\n hit_grid = [row[:] for row in grid]\n for i, j in hits:\n hit_grid[i][j] = 0\n\n union_find = UnionFind(R*C)\n for r, row in enumerate(hit_grid):\n for c, val in enumerate(row):\n if not val:\n continue\n if r == 0:\n union_find.union_set(index(C, r, c), R*C)\n if r and hit_grid[r-1][c]:\n union_find.union_set(index(C, r, c), index(C, r-1, c))\n if c and hit_grid[r][c-1]:\n union_find.union_set(index(C, r, c), index(C, r, c-1))\n\n result = []\n for r, c in reversed(hits):\n prev_roof = union_find.top()\n if grid[r][c] == 0:\n result.append(0)\n continue\n for d in directions:\n nr, nc = (r+d[0], c+d[1])\n if 0 <= nr < R and 0 <= nc < C and hit_grid[nr][nc]:\n union_find.union_set(index(C, r, c), index(C, nr, nc))\n if r == 0:\n union_find.union_set(index(C, r, c), R*C)\n hit_grid[r][c] = 1\n result.append(max(0, union_find.top()-prev_roof-1))\n return result[::-1]\n\n"}} diff --git a/cp/cp-10280.jsonl b/cp/cp-10280.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4f018454e56dca64dbac67951f109d579447535d --- /dev/null +++ b/cp/cp-10280.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10280", "name": "LeetCode 0804: Unique Morse Code 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: Unique Morse Code Words (Difficulty: Easy)\nTags: Array, Hash Table, String\n\nInternational Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:\nFor convenience, the full table for the 26 letters of the English alphabet is given below:\nGiven an array of strings words where each word can be written as a concatenation of the Morse code of each letter.\nReturn the number of different transformations among all words we have.\n\nExample 1:\n[\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]\n\nExample 2:\nInput: words = [\"gin\",\"zen\",\"gig\",\"msg\"]\nOutput: 2\nExplanation: The transformation of each word is:\n\"gin\" -> \"--...-.\"\n\"zen\" -> \"--...-.\"\n\"gig\" -> \"--...--.\"\n\"msg\" -> \"--...--.\"\nThere are 2 different transformations: \"--...-.\" and \"--...--.\".\n\nExample 3:\nInput: words = [\"a\"]\nOutput: 1\n\nConstraints:\n- 1 <= words.length <= 100\n- 1 <= words[i].length <= 12\n- words[i] consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n), n is the sume of all word lengths\n# Space: O(n)\n\nclass Solution(object):\n def uniqueMorseRepresentations(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: int\n \"\"\"\n MORSE = [\".-\", \"-...\", \"-.-.\", \"-..\", \".\", \"..-.\", \"--.\",\n \"....\", \"..\", \".---\", \"-.-\", \".-..\", \"--\", \"-.\",\n \"---\", \".--.\", \"--.-\", \".-.\", \"...\", \"-\", \"..-\",\n \"...-\", \".--\", \"-..-\", \"-.--\", \"--..\"]\n\n lookup = {\"\".join(MORSE[ord(c) - ord('a')] for c in word) \\\n for word in words}\n return len(lookup)\n\n"}} diff --git a/cp/cp-10281.jsonl b/cp/cp-10281.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8e95f24139032d1e6c64372632b6eccaa672bcea --- /dev/null +++ b/cp/cp-10281.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10281", "name": "LeetCode 0805: Split Array With Same Average"} +{"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 With Same Average (Difficulty: Hard)\nTags: Array, Math, Dynamic Programming, Bit Manipulation, Bitmask\n\nYou are given an integer array nums.\nYou should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B).\nReturn true if it is possible to achieve that and false otherwise.\nNote that for an array arr, average(arr) is the sum of all the elements of arr over the length of arr.\n\nExample 1:\nInput: nums = [1,2,3,4,5,6,7,8]\nOutput: true\nExplanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.\n\nExample 2:\nInput: nums = [3,1]\nOutput: false\n\nConstraints:\n- 1 <= nums.length <= 30\n- 0 <= nums[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^4)\n# Space: O(n^3)\n\nclass Solution(object):\n def splitArraySameAverage(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: bool\n \"\"\"\n def possible(total, n):\n for i in range(1, n//2+1):\n if total*i%n == 0:\n return True\n return False\n n, s = len(A), sum(A)\n if not possible(n, s):\n return False\n\n sums = [set() for _ in range(n//2+1)]\n sums[0].add(0)\n for num in A: # O(n) times\n for i in reversed(range(1, n//2+1)): # O(n) times\n for prev in sums[i-1]: # O(1) + O(2) + ... O(n/2) = O(n^2) times\n sums[i].add(prev+num)\n for i in range(1, n//2+1):\n if s*i%n == 0 and s*i//n in sums[i]:\n return True\n return False\n\n"}} diff --git a/cp/cp-10282.jsonl b/cp/cp-10282.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1f09c3519c41df088275f05df1ed51b9e92abcf7 --- /dev/null +++ b/cp/cp-10282.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10282", "name": "LeetCode 0806: Number Of Lines To Write 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: Number of Lines To Write String (Difficulty: Easy)\nTags: Array, String\n\nYou are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on.\nYou are trying to write s across several lines, where each line is no longer than 100 pixels. Starting at the beginning of s, write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s, continue writing as many letters as you can on the second line. Continue this process until you have written all of s.\nReturn an array result of length 2 where:\n\nExample 1:\nInput: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"abcdefghijklmnopqrstuvwxyz\"\nOutput: [3,60]\nExplanation: You can write s as follows:\nabcdefghij // 100 pixels wide\nklmnopqrst // 100 pixels wide\nuvwxyz // 60 pixels wide\nThere are a total of 3 lines, and the last line is 60 pixels wide.\n\nExample 2:\nInput: widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"bbbcccdddaaa\"\nOutput: [2,4]\nExplanation: You can write s as follows:\nbbbcccdddaa // 98 pixels wide\na // 4 pixels wide\nThere are a total of 2 lines, and the last line is 4 pixels wide.\n\nConstraints:\n- widths.length == 26\n- 2 <= widths[i] <= 10\n- 1 <= s.length <= 1000\n- s contains only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def numberOfLines(self, widths, S):\n \"\"\"\n :type widths: List[int]\n :type S: str\n :rtype: List[int]\n \"\"\"\n result = [1, 0]\n for c in S:\n w = widths[ord(c)-ord('a')]\n result[1] += w\n if result[1] > 100:\n result[0] += 1\n result[1] = w\n return result\n\n"}} diff --git a/cp/cp-10283.jsonl b/cp/cp-10283.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0e86ae876864f2a52f80594aaa97db292a418ec7 --- /dev/null +++ b/cp/cp-10283.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10283", "name": "LeetCode 0807: Max Increase To Keep City Skyline"} +{"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: Max Increase to Keep City Skyline (Difficulty: Medium)\nTags: Array, Greedy, Matrix\n\nThere is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c.\nA city's skyline is the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different.\nWe are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction.\nReturn the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction.\n\nExample 1:\nInput: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]\nOutput: 35\nExplanation: The building heights are shown in the center of the above image.\nThe skylines when viewed from each cardinal direction are drawn in red.\nThe grid after increasing the height of buildings without affecting skylines is:\ngridNew = [ [8, 4, 8, 7],\n [7, 4, 7, 7],\n [9, 4, 8, 7],\n [3, 3, 3, 3] ]\n\nExample 2:\nInput: grid = [[0,0,0],[0,0,0],[0,0,0]]\nOutput: 0\nExplanation: Increasing the height of any building will result in the skyline changing.\n\nConstraints:\n- n == grid.length\n- n == grid[r].length\n- 2 <= n <= 50\n- 0 <= grid[r][c] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nimport itertools\n\n\nclass Solution(object):\n def maxIncreaseKeepingSkyline(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n row_maxes = [max(row) for row in grid]\n col_maxes = [max(col) for col in itertools.izip(*grid)]\n\n return sum(min(row_maxes[r], col_maxes[c])-val \\\n for r, row in enumerate(grid) \\\n for c, val in enumerate(row))\n\n"}} diff --git a/cp/cp-10284.jsonl b/cp/cp-10284.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4dd3f444bc67903bc1c8c7df88d9b32f71c8ea6d --- /dev/null +++ b/cp/cp-10284.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10284", "name": "LeetCode 0808: Soup Servings"} +{"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: Soup Servings (Difficulty: Medium)\nTags: Math, Dynamic Programming, Probability and Statistics\n\nYou have two soups, A and B, each starting with n mL. On every turn, one of the following four serving operations is chosen at random, each with probability 0.25 independent of all previous turns:\nNote:\nThe process stops immediately after any turn in which one of the soups is used up.\nReturn the probability that A is used up before B, plus half the probability that both soups are used up in the same turn. Answers within 10-5 of the actual answer will be accepted.\n\nExample 1:\nInput: n = 50\nOutput: 0.62500\nExplanation: \nIf we perform either of the first two serving operations, soup A will become empty first.\nIf we perform the third operation, A and B will become empty at the same time.\nIf we perform the fourth operation, B will become empty first.\nSo the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.\n\nExample 2:\nInput: n = 100\nOutput: 0.71875\nExplanation: \nIf we perform the first serving operation, soup A will become empty first.\nIf we perform the second serving operations, A will become empty on performing operation [1, 2, 3], and both A and B become empty on performing operation 4.\nIf we perform the third operation, A will become empty on performing operation [1, 2], and both A and B become empty on performing operation 3.\nIf we perform the fourth operation, A will become empty on performing operation 1, and both A and B become empty on performing operation 2.\nSo the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.71875.\n\nConstraints:\n- 0 <= n <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def soupServings(self, N):\n \"\"\"\n :type N: int\n :rtype: float\n \"\"\"\n def dp(a, b, lookup):\n if (a, b) in lookup:\n return lookup[a, b]\n if a <= 0 and b <= 0:\n return 0.5\n if a <= 0:\n return 1.0\n if b <= 0:\n return 0.0\n lookup[a, b] = 0.25 * (dp(a-4, b, lookup) +\n dp(a-3, b-1, lookup) +\n dp(a-2, b-2, lookup) +\n dp(a-1, b-3, lookup))\n return lookup[a, b]\n\n if N >= 4800:\n return 1.0\n lookup = {}\n N = (N+24)//25\n return dp(N, N, lookup)\n\n"}} diff --git a/cp/cp-10285.jsonl b/cp/cp-10285.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b0e8a16a6f99999eccd21e71da1c4f4486c485d8 --- /dev/null +++ b/cp/cp-10285.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10285", "name": "LeetCode 0809: Expressive 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: Expressive Words (Difficulty: Medium)\nTags: Array, Two Pointers, String\n\nSometimes people repeat letters to represent extra feeling. For example:\nIn these strings like \"heeellooo\", we have groups of adjacent letters that are all the same: \"h\", \"eee\", \"ll\", \"ooo\".\nYou are given a string s and an array of query strings words. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is three or more.\nReturn the number of query strings that are stretchy.\n\nExample 1:\nInput: s = \"heeellooo\", words = [\"hello\", \"hi\", \"helo\"]\nOutput: 1\nExplanation: \nWe can extend \"e\" and \"o\" in the word \"hello\" to get \"heeellooo\".\nWe can't extend \"helo\" to get \"heeellooo\" because the group \"ll\" is not size 3 or more.\n\nExample 2:\nInput: s = \"zzzzzyyyyy\", words = [\"zzyy\",\"zy\",\"zyy\"]\nOutput: 3\n\nConstraints:\n- 1 <= s.length, words.length <= 100\n- 1 <= words[i].length <= 100\n- s and words[i] consist of lowercase letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + s), n is the sum of all word lengths, s is the length of S\n# Space: O(l + s), l is the max word length\n\nimport itertools\n\n\nclass Solution(object):\n def expressiveWords(self, S, words):\n \"\"\"\n :type S: str\n :type words: List[str]\n :rtype: int\n \"\"\"\n # Run length encoding\n def RLE(S):\n return itertools.izip(*[(k, len(list(grp)))\n for k, grp in itertools.groupby(S)])\n\n R, count = RLE(S)\n result = 0\n for word in words:\n R2, count2 = RLE(word)\n if R2 != R:\n continue\n result += all(c1 >= max(c2, 3) or c1 == c2\n for c1, c2 in itertools.izip(count, count2))\n return result\n\n"}} diff --git a/cp/cp-10287.jsonl b/cp/cp-10287.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e9904ebfa344a65cd8703d44b101b0092cd362ed --- /dev/null +++ b/cp/cp-10287.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10287", "name": "LeetCode 0811: Subdomain Visit Count"} +{"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: Subdomain Visit Count (Difficulty: Medium)\nTags: Array, Hash Table, String, Counting\n\nA website domain \"discuss.leetcode.com\" consists of various subdomains. At the top level, we have \"com\", at the next level, we have \"leetcode.com\" and at the lowest level, \"discuss.leetcode.com\". When we visit a domain like \"discuss.leetcode.com\", we will also visit the parent domains \"leetcode.com\" and \"com\" implicitly.\nA count-paired domain is a domain that has one of the two formats \"rep d1.d2.d3\" or \"rep d1.d2\" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself.\nGiven an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order.\n\nExample 1:\nInput: cpdomains = [\"9001 discuss.leetcode.com\"]\nOutput: [\"9001 leetcode.com\",\"9001 discuss.leetcode.com\",\"9001 com\"]\nExplanation: We only have one website domain: \"discuss.leetcode.com\".\nAs discussed above, the subdomain \"leetcode.com\" and \"com\" will also be visited. So they will all be visited 9001 times.\n\nExample 2:\nInput: cpdomains = [\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]\nOutput: [\"901 mail.com\",\"50 yahoo.com\",\"900 google.mail.com\",\"5 wiki.org\",\"5 org\",\"1 intel.mail.com\",\"951 com\"]\nExplanation: We will visit \"google.mail.com\" 900 times, \"yahoo.com\" 50 times, \"intel.mail.com\" once and \"wiki.org\" 5 times.\nFor the subdomains, we will visit \"mail.com\" 900 + 1 = 901 times, \"com\" 900 + 50 + 1 = 951 times, and \"org\" 5 times.\n\nConstraints:\n- 1 <= cpdomain.length <= 100\n- 1 <= cpdomain[i].length <= 100\n- cpdomain[i] follows either the \"repi d1i.d2i.d3i\" format or the \"repi d1i.d2i\" format.\n- repi is an integer in the range [1, 104].\n- d1i, d2i, and d3i consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n), is the length of cpdomains (assuming the length of cpdomains[i] is fixed)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def subdomainVisits(self, cpdomains):\n \"\"\"\n :type cpdomains: List[str]\n :rtype: List[str]\n \"\"\"\n result = collections.defaultdict(int)\n for domain in cpdomains:\n count, domain = domain.split()\n count = int(count)\n frags = domain.split('.')\n curr = []\n for i in reversed(range(len(frags))):\n curr.append(frags[i])\n result[\".\".join(reversed(curr))] += count\n\n return [\"{} {}\".format(count, domain) \\\n for domain, count in result.iteritems()]\n\n"}} diff --git a/cp/cp-10288.jsonl b/cp/cp-10288.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d726b4b6d755fd6d88eae555bceef579560dda3b --- /dev/null +++ b/cp/cp-10288.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10288", "name": "LeetCode 0812: Largest Triangle Area"} +{"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: Largest Triangle Area (Difficulty: Easy)\nTags: Array, Math, Geometry\n\nGiven an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted.\n\nExample 1:\nInput: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]\nOutput: 2.00000\nExplanation: The five points are shown in the above figure. The red triangle is the largest.\n\nExample 2:\nInput: points = [[1,0],[0,0],[0,1]]\nOutput: 0.50000\n\nConstraints:\n- 3 <= points.length <= 50\n- -50 <= xi, yi <= 50\n- All the given points are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(1)\n\n\nclass Solution(object):\n def largestTriangleArea(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: float\n \"\"\"\n result = 0\n for i in range(len(points)-2):\n for j in range(i+1, len(points)-1):\n for k in range(j+1, len(points)):\n result = max(result,\n 0.5 * abs(points[i][0] * points[j][1] +\n points[j][0] * points[k][1] +\n points[k][0] * points[i][1] -\n points[j][0] * points[i][1] -\n points[k][0] * points[j][1] -\n points[i][0] * points[k][1]))\n return result\n\n"}} diff --git a/cp/cp-10289.jsonl b/cp/cp-10289.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0ed5a93d2f832b064cfcb2006a7b8efaadc94122 --- /dev/null +++ b/cp/cp-10289.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10289", "name": "LeetCode 0813: Largest Sum Of Averages"} +{"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: Largest Sum of Averages (Difficulty: Medium)\nTags: Array, Dynamic Programming, Prefix Sum\n\nYou are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray.\nNote that the partition must use every integer in nums, and that the score is not necessarily an integer.\nReturn the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted.\n\nExample 1:\nInput: nums = [9,1,2,3,9], k = 3\nOutput: 20.00000\nExplanation: \nThe best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\nWe could have also partitioned nums into [9, 1], [2], [3, 9], for example.\nThat partition would lead to a score of 5 + 2 + 6 = 13, which is worse.\n\nExample 2:\nInput: nums = [1,2,3,4,5,6,7], k = 4\nOutput: 20.50000\n\nConstraints:\n- 1 <= nums.length <= 100\n- 1 <= nums[i] <= 10^4\n- 1 <= k <= nums.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(k * n^2)\n# Space: O(n)\n\n\nclass Solution(object):\n def largestSumOfAverages(self, A, K):\n \"\"\"\n :type A: List[int]\n :type K: int\n :rtype: float\n \"\"\"\n accum_sum = [A[0]]\n for i in range(1, len(A)):\n accum_sum.append(A[i]+accum_sum[-1])\n\n dp = [[0]*len(A) for _ in range(2)]\n for k in range(1, K+1):\n for i in range(k-1, len(A)):\n if k == 1:\n dp[k % 2][i] = float(accum_sum[i])/(i+1)\n else:\n for j in range(k-2, i):\n dp[k % 2][i] = \\\n max(dp[k % 2][i],\n dp[(k-1) % 2][j] +\n float(accum_sum[i]-accum_sum[j])/(i-j))\n return dp[K % 2][-1]\n\n"}} diff --git a/cp/cp-10290.jsonl b/cp/cp-10290.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b6161024286355906f974756b8b9a8ecdcb83a51 --- /dev/null +++ b/cp/cp-10290.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10290", "name": "LeetCode 0814: Binary Tree Pruning"} +{"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: Binary Tree Pruning (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Tree\n\nGiven the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.\nA subtree of a node node is node plus every node that is a descendant of node.\n\nExample 1:\nInput: root = [1,null,0,0,1]\nOutput: [1,null,0,null,1]\nExplanation: \nOnly the red nodes satisfy the property \"every subtree not containing a 1\".\nThe diagram on the right represents the answer.\n\nExample 2:\nInput: root = [1,0,1,0,0,0,1]\nOutput: [1,null,1,null,1]\n\nExample 3:\nInput: root = [1,1,0,1,1,0,1,0]\nOutput: [1,1,0,1,1,null,1]\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 200].\n- Node.val is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nclass Solution(object):\n def pruneTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n if not root:\n return None\n root.left = self.pruneTree(root.left)\n root.right = self.pruneTree(root.right)\n if not root.left and not root.right and root.val == 0:\n return None\n return root\n\n"}} diff --git a/cp/cp-10291.jsonl b/cp/cp-10291.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f51cfa64810c6ceeb73291609b9f8fced7d79916 --- /dev/null +++ b/cp/cp-10291.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10291", "name": "LeetCode 0815: Bus Routes"} +{"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: Bus Routes (Difficulty: Hard)\nTags: Array, Hash Table, Breadth-First Search\n\nYou are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.\nYou will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only.\nReturn the least number of buses you must take to travel from source to target. Return -1 if it is not possible.\n\nExample 1:\nInput: routes = [[1,2,7],[3,6,7]], source = 1, target = 6\nOutput: 2\nExplanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.\n\nExample 2:\nInput: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12\nOutput: -1\n\nConstraints:\n- 1 <= routes.length <= 500.\n- 1 <= routes[i].length <= 10^5\n- All the values of routes[i] are unique.\n- sum(routes[i].length) <= 10^5\n- 0 <= routes[i][j] < 10^6\n- 0 <= source, target < 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(|V| + |E|)\n# Space: O(|V| + |E|)\n\nimport collections\n\n\nclass Solution(object):\n def numBusesToDestination(self, routes, S, T):\n \"\"\"\n :type routes: List[List[int]]\n :type S: int\n :type T: int\n :rtype: int\n \"\"\"\n if S == T:\n return 0\n\n to_route = collections.defaultdict(set)\n for i, route in enumerate(routes):\n for stop in route:\n to_route[stop].add(i)\n\n result = 1\n q = [S]\n lookup = set([S])\n while q:\n next_q = []\n for stop in q:\n for i in to_route[stop]:\n for next_stop in routes[i]:\n if next_stop in lookup:\n continue\n if next_stop == T:\n return result\n next_q.append(next_stop)\n to_route[next_stop].remove(i)\n lookup.add(next_stop)\n q = next_q\n result += 1\n\n return -1\n\n"}} diff --git a/cp/cp-10292.jsonl b/cp/cp-10292.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6ba243c020df2cea277a5583041db3ed92bad60d --- /dev/null +++ b/cp/cp-10292.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10292", "name": "LeetCode 0816: Ambiguous Coordinates"} +{"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: Ambiguous Coordinates (Difficulty: Medium)\nTags: String, Backtracking, Enumeration\n\nWe had some 2-dimensional coordinates, like \"(1, 3)\" or \"(2, 0.5)\". Then, we removed all commas, decimal points, and spaces and ended up with the string s.\nReturn a list of strings representing all possibilities for what our original coordinates could have been.\nOur original representation never had extraneous zeroes, so we never started with numbers like \"00\", \"0.0\", \"0.00\", \"1.0\", \"001\", \"00.01\", or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like \".1\".\nThe final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)\n\nExample 1:\nInput: s = \"(123)\"\nOutput: [\"(1, 2.3)\",\"(1, 23)\",\"(1.2, 3)\",\"(12, 3)\"]\n\nExample 2:\nInput: s = \"(0123)\"\nOutput: [\"(0, 1.23)\",\"(0, 12.3)\",\"(0, 123)\",\"(0.1, 2.3)\",\"(0.1, 23)\",\"(0.12, 3)\"]\nExplanation: 0.0, 00, 0001 or 00.01 are not allowed.\n\nExample 3:\nInput: s = \"(00011)\"\nOutput: [\"(0, 0.011)\",\"(0.001, 1)\"]\n\nConstraints:\n- 4 <= s.length <= 12\n- s[0] == '(' and s[s.length - 1] == ')'.\n- The rest of s are digits."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^4)\n# Space: O(n)\n\nimport itertools\n\n\nclass Solution(object):\n def ambiguousCoordinates(self, S):\n \"\"\"\n :type S: str\n :rtype: List[str]\n \"\"\"\n def make(S, i, n):\n for d in range(1, n+1):\n left = S[i:i+d]\n right = S[i+d:i+n]\n if ((not left.startswith('0') or left == '0')\n and (not right.endswith('0'))):\n yield \"\".join([left, '.' if right else '', right])\n\n return [\"({}, {})\".format(*cand)\n for i in range(1, len(S)-2)\n for cand in itertools.product(make(S, 1, i),\n make(S, i+1, len(S)-2-i))]\n\n"}} diff --git a/cp/cp-10293.jsonl b/cp/cp-10293.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6189fe11e11dc56714fb79429b326c19763e2b4d --- /dev/null +++ b/cp/cp-10293.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10293", "name": "LeetCode 0817: Linked List Components"} +{"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: Linked List Components (Difficulty: Medium)\nTags: Array, Hash Table, Linked List\n\nYou are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values.\nReturn the number of connected components in nums where two values are connected if they appear consecutively in the linked list.\n\nExample 1:\nInput: head = [0,1,2,3], nums = [0,1,3]\nOutput: 2\nExplanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components.\n\nExample 2:\nInput: head = [0,1,2,3,4], nums = [0,3,1,4]\nOutput: 2\nExplanation: 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.\n\nConstraints:\n- The number of nodes in the linked list is n.\n- 1 <= n <= 10^4\n- 0 <= Node.val < n\n- All the values Node.val are unique.\n- 1 <= nums.length <= n\n- 0 <= nums[i] < n\n- All the values of nums are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n), m is the number of G, n is the number of nodes\n# Space: O(m)\n\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def numComponents(self, head, G):\n \"\"\"\n :type head: ListNode\n :type G: List[int]\n :rtype: int\n \"\"\"\n lookup = set(G)\n dummy = ListNode(-1)\n dummy.next = head\n curr = dummy\n result = 0\n while curr and curr.next:\n if curr.val not in lookup and curr.next.val in lookup:\n result += 1\n curr = curr.next\n return result\n\n"}} diff --git a/cp/cp-10294.jsonl b/cp/cp-10294.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f79eead57d96b2609c82ecfea3ebd0658b9d469c --- /dev/null +++ b/cp/cp-10294.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10294", "name": "LeetCode 0818: Race Car"} +{"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: Race Car (Difficulty: Hard)\nTags: Dynamic Programming\n\nYour car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse):\nFor example, after commands \"AAR\", your car goes to positions 0 --> 1 --> 3 --> 3, and your speed goes to 1 --> 2 --> 4 --> -1.\nGiven a target position target, return the length of the shortest sequence of instructions to get there.\n\nExample 1:\nInput: target = 3\nOutput: 2\nExplanation: \nThe shortest instruction sequence is \"AA\".\nYour position goes from 0 --> 1 --> 3.\n\nExample 2:\nInput: target = 6\nOutput: 5\nExplanation: \nThe shortest instruction sequence is \"AAARA\".\nYour position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.\n\nConstraints:\n- 1 <= target <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time : O(nlogn), n is the value of the target\n# Space: O(n)\n\n\nclass Solution(object):\n def racecar(self, target):\n dp = [0] * (target+1)\n for i in range(1, target+1):\n # 2^(k-1) <= i < 2^k\n k = i.bit_length()\n\n # case 1. drive exactly i at best\n # seq(i) = A^k\n if i == 2**k-1:\n dp[i] = k\n continue\n\n # case 2. drive cross i at 2^k-1, and turn back to i\n # seq(i) = A^k -> R -> seq(2^k-1 - i)\n dp[i] = k+1 + dp[2**k-1 - i]\n\n # case 3. drive less then 2^k-1, and turn back some distance,\n # and turn back again to make the direction is the same\n # seq(i) = shortest(seq(i), A^(k-1) -> R -> A^j -> R ->\n # seq(i - (2^(k-1)-1) + (2^j-1)),\n # where 0 <= j < k-1)\n # => dp[i] = min(dp[i], (k-1) + 1 + j + 1 +\n # dp[i - (2**(k-1)-1) + (2**j-1)])\n for j in range(k-1):\n dp[i] = min(dp[i], k+j+1 + dp[i - 2**(k-1) + 2**j])\n\n return dp[-1]\n\n"}} diff --git a/cp/cp-10295.jsonl b/cp/cp-10295.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3c408df84893b223de93df37bd87e0e5dc782114 --- /dev/null +++ b/cp/cp-10295.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10295", "name": "LeetCode 0819: Most Common Word"} +{"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: Most Common Word (Difficulty: Easy)\nTags: Array, Hash Table, String, Counting\n\nGiven a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.\nThe words in paragraph are case-insensitive and the answer should be returned in lowercase.\nNote that words can not contain punctuation symbols.\n\nExample 1:\nInput: paragraph = \"Bob hit a ball, the hit BALL flew far after it was hit.\", banned = [\"hit\"]\nOutput: \"ball\"\nExplanation: \n\"hit\" occurs 3 times, but it is a banned word.\n\"ball\" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. \nNote that words in the paragraph are not case sensitive,\nthat punctuation is ignored (even if adjacent to words, such as \"ball,\"), \nand that \"hit\" isn't the answer even though it occurs more because it is banned.\n\nExample 2:\nInput: paragraph = \"a.\", banned = []\nOutput: \"a\"\n\nConstraints:\n- 1 <= paragraph.length <= 1000\n- paragraph consists of English letters, space ' ', or one of the symbols: \"!?',;.\".\n- 0 <= banned.length <= 100\n- 1 <= banned[i].length <= 10\n- banned[i] consists of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n), m is the size of banned, n is the size of paragraph\n# Space: O(m + n)\n\nimport collections\n\n\nclass Solution(object):\n def mostCommonWord(self, paragraph, banned):\n \"\"\"\n :type paragraph: str\n :type banned: List[str]\n :rtype: str\n \"\"\"\n lookup = set(banned)\n counts = collections.Counter(word.strip(\"!?',.\")\n for word in paragraph.lower().split())\n\n result = ''\n for word in counts:\n if (not result or counts[word] > counts[result]) and \\\n word not in lookup:\n result = word\n return result\n\n"}} diff --git a/cp/cp-10296.jsonl b/cp/cp-10296.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..723d1e68d7a232061c38d2fdc58937bead050769 --- /dev/null +++ b/cp/cp-10296.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10296", "name": "LeetCode 0820: Short Encoding Of 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: Short Encoding of Words (Difficulty: Medium)\nTags: Array, Hash Table, String, Trie\n\nA valid encoding of an array of words is any reference string s and array of indices indices such that:\nGiven an array of words, return the length of the shortest reference string s possible of any valid encoding of words.\n\nExample 1:\nInput: words = [\"time\", \"me\", \"bell\"]\nOutput: 10\nExplanation: A valid encoding would be s = \"time#bell#\" and indices = [0, 2, 5].\nwords[0] = \"time\", the substring of s starting from indices[0] = 0 to the next '#' is underlined in \"time#bell#\"\nwords[1] = \"me\", the substring of s starting from indices[1] = 2 to the next '#' is underlined in \"time#bell#\"\nwords[2] = \"bell\", the substring of s starting from indices[2] = 5 to the next '#' is underlined in \"time#bell#\"\n\nExample 2:\nInput: words = [\"t\"]\nOutput: 2\nExplanation: A valid encoding would be s = \"t#\" and indices = [0].\n\nConstraints:\n- 1 <= words.length <= 2000\n- 1 <= words[i].length <= 7\n- words[i] consists of only lowercase letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n), n is the total sum of the lengths of words\n# Space: O(t), t is the number of nodes in trie\n\nimport collections\nimport functools\n\n\nclass Solution(object):\n def minimumLengthEncoding(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: int\n \"\"\"\n words = list(set(words))\n _trie = lambda: collections.defaultdict(_trie)\n trie = _trie()\n\n nodes = [functools.reduce(dict.__getitem__, word[::-1], trie)\n for word in words]\n\n return sum(len(word) + 1\n for i, word in enumerate(words)\n if len(nodes[i]) == 0)\n\n"}} diff --git a/cp/cp-10297.jsonl b/cp/cp-10297.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9ec04d49ac78434e7a4c109713b3c103e968e756 --- /dev/null +++ b/cp/cp-10297.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10297", "name": "LeetCode 0821: Shortest Distance To A Character"} +{"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: Shortest Distance to a Character (Difficulty: Easy)\nTags: Array, Two Pointers, String\n\nGiven a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.\nThe distance between two indices i and j is abs(i - j), where abs is the absolute value function.\n\nExample 1:\nInput: s = \"loveleetcode\", c = \"e\"\nOutput: [3,2,1,0,1,0,0,1,2,2,1,0]\nExplanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).\nThe closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.\nThe closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.\nFor index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.\nThe closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.\n\nExample 2:\nInput: s = \"aaab\", c = \"b\"\nOutput: [3,2,1,0]\n\nConstraints:\n- 1 <= s.length <= 10^4\n- s[i] and c are lowercase English letters.\n- It is guaranteed that c occurs at least once in s."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def shortestToChar(self, S, C):\n \"\"\"\n :type S: str\n :type C: str\n :rtype: List[int]\n \"\"\"\n result = [len(S)] * len(S)\n prev = -len(S)\n for i in itertools.chain(range(len(S)),\n reversed(range(len(S)))):\n if S[i] == C:\n prev = i\n result[i] = min(result[i], abs(i-prev))\n return result\n\n"}} diff --git a/cp/cp-10298.jsonl b/cp/cp-10298.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..42c2d138fc9bcee9ffbedb80c7a78371a7365f23 --- /dev/null +++ b/cp/cp-10298.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10298", "name": "LeetCode 0822: Card Flipping Game"} +{"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: Card Flipping Game (Difficulty: Medium)\nTags: Array, Hash Table\n\nYou are given two 0-indexed integer arrays fronts and backs of length n, where the ith card has the positive integer fronts[i] printed on the front and backs[i] printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may flip over any number of cards (possibly zero).\nAfter flipping the cards, an integer is considered good if it is facing down on some card and not facing up on any card.\nReturn the minimum possible good integer after flipping the cards. If there are no good integers, return 0.\n\nExample 1:\nInput: fronts = [1,2,4,4,7], backs = [1,3,4,1,3]\nOutput: 2\nExplanation:\nIf we flip the second card, the face up numbers are [1,3,4,4,7] and the face down are [1,2,4,1,3].\n2 is the minimum good integer as it appears facing down but not facing up.\nIt can be shown that 2 is the minimum possible good integer obtainable after flipping some cards.\n\nExample 2:\nInput: fronts = [1], backs = [1]\nOutput: 0\nExplanation:\nThere are no good integers no matter how we flip the cards, so we return 0.\n\nConstraints:\n- n == fronts.length == backs.length\n- 1 <= n <= 1000\n- 1 <= fronts[i], backs[i] <= 2000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport itertools\n\n\nclass Solution(object):\n def flipgame(self, fronts, backs):\n \"\"\"\n :type fronts: List[int]\n :type backs: List[int]\n :rtype: int\n \"\"\"\n same = {n for i, n in enumerate(fronts) if n == backs[i]}\n result = float(\"inf\")\n for n in itertools.chain(fronts, backs):\n if n not in same:\n result = min(result, n)\n return result if result < float(\"inf\") else 0\n\n"}} diff --git a/cp/cp-10299.jsonl b/cp/cp-10299.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4d6010611a01ec85f7e01a985106f46ba97b0637 --- /dev/null +++ b/cp/cp-10299.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10299", "name": "LeetCode 0823: Binary Trees With Factors"} +{"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: Binary Trees With Factors (Difficulty: Medium)\nTags: Array, Hash Table, Dynamic Programming, Sorting\n\nGiven an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.\nWe make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.\nReturn the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7.\n\nExample 1:\nInput: arr = [2,4]\nOutput: 3\nExplanation: We can make these trees: [2], [4], [4, 2, 2]\n\nExample 2:\nInput: arr = [2,4,5,10]\nOutput: 7\nExplanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].\n\nConstraints:\n- 1 <= arr.length <= 1000\n- 2 <= arr[i] <= 10^9\n- All the values of arr are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\n\nclass Solution(object):\n def numFactoredBinaryTrees(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n M = 10**9 + 7\n A.sort()\n dp = {}\n for i in range(len(A)):\n dp[A[i]] = 1\n for j in range(i):\n if A[i] % A[j] == 0 and A[i] // A[j] in dp:\n dp[A[i]] += dp[A[j]] * dp[A[i] // A[j]]\n dp[A[i]] %= M\n return sum(dp.values()) % M\n\n"}} diff --git a/cp/cp-10300.jsonl b/cp/cp-10300.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..85664865050ee1b8a7331e314bcc93ef1917621b --- /dev/null +++ b/cp/cp-10300.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10300", "name": "LeetCode 0824: Goat Latin"} +{"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: Goat Latin (Difficulty: Easy)\nTags: String\n\nYou are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.\nWe would like to convert the sentence to \"Goat Latin\" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:\nReturn the final sentence representing the conversion from sentence to Goat Latin.\n\nExample 1:\nInput: sentence = \"I speak Goat Latin\"\nOutput: \"Imaa peaksmaaa oatGmaaaa atinLmaaaaa\"\n\nExample 2:\nInput: sentence = \"The quick brown fox jumped over the lazy dog\"\nOutput: \"heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa\"\n\nConstraints:\n- 1 <= sentence.length <= 150\n- sentence consists of English letters and spaces.\n- sentence has no leading or trailing spaces.\n- All the words in sentence are separated by a single space."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + w^2), n = w * l,\n# n is the length of S,\n# w is the number of word,\n# l is the average length of word\n# Space: O(n)\n\nclass Solution(object):\n def toGoatLatin(self, S):\n \"\"\"\n :type S: str\n :rtype: str\n \"\"\"\n def convert(S):\n vowel = set('aeiouAEIOU')\n for i, word in enumerate(S.split(), 1):\n if word[0] not in vowel:\n word = word[1:] + word[:1]\n yield word + 'ma' + 'a'*i\n return \" \".join(convert(S))\n\n"}} diff --git a/cp/cp-10301.jsonl b/cp/cp-10301.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..709c470764a86ec9dd8020d75b20bbdb19fc96fd --- /dev/null +++ b/cp/cp-10301.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10301", "name": "LeetCode 0825: Friends Of Appropriate Ages"} +{"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: Friends Of Appropriate Ages (Difficulty: Medium)\nTags: Array, Two Pointers, Binary Search, Sorting\n\nThere are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person.\nA Person x will not send a friend request to a person y (x != y) if any of the following conditions is true:\nOtherwise, x will send a friend request to y.\nNote that if x sends a request to y, y will not necessarily send a request to x. Also, a person will not send a friend request to themself.\nReturn the total number of friend requests made.\n\nExample 1:\nInput: ages = [16,16]\nOutput: 2\nExplanation: 2 people friend request each other.\n\nExample 2:\nInput: ages = [16,17,18]\nOutput: 2\nExplanation: Friend requests are made 17 -> 16, 18 -> 17.\n\nExample 3:\nInput: ages = [20,30,100,110,120]\nOutput: 3\nExplanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.\n\nConstraints:\n- n == ages.length\n- 1 <= n <= 2 * 10^4\n- 1 <= ages[i] <= 120"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(a^2 + n), a is the number of ages,\n# n is the number of people\n# Space: O(a)\n\nimport collections\n\n\nclass Solution(object):\n def numFriendRequests(self, ages):\n \"\"\"\n :type ages: List[int]\n :rtype: int\n \"\"\"\n def request(a, b):\n return 0.5*a+7 < b <= a\n\n c = collections.Counter(ages)\n return sum(int(request(a, b)) * c[a]*(c[b]-int(a == b))\n for a in c\n for b in c)\n\n"}} diff --git a/cp/cp-10302.jsonl b/cp/cp-10302.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3084faf646686d8851c49784c71b204640d97766 --- /dev/null +++ b/cp/cp-10302.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10302", "name": "LeetCode 0826: Most Profit Assigning Work"} +{"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: Most Profit Assigning Work (Difficulty: Medium)\nTags: Array, Two Pointers, Binary Search, Greedy, Sorting\n\nYou have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:\nEvery worker can be assigned at most one job, but one job can be completed multiple times.\nReturn the maximum profit we can achieve after assigning the workers to the jobs.\n\nExample 1:\nInput: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]\nOutput: 100\nExplanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.\n\nExample 2:\nInput: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]\nOutput: 0\n\nConstraints:\n- n == difficulty.length\n- n == profit.length\n- m == worker.length\n- 1 <= n, m <= 10^4\n- 1 <= difficulty[i], profit[i], worker[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(mlogm + nlogn), m is the number of workers,\n# , n is the number of jobs\n# Space: O(n)\n\nclass Solution(object):\n def maxProfitAssignment(self, difficulty, profit, worker):\n \"\"\"\n :type difficulty: List[int]\n :type profit: List[int]\n :type worker: List[int]\n :rtype: int\n \"\"\"\n jobs = zip(difficulty, profit)\n jobs.sort()\n worker.sort()\n result, i, max_profit = 0, 0, 0\n for ability in worker:\n while i < len(jobs) and jobs[i][0] <= ability:\n max_profit = max(max_profit, jobs[i][1])\n i += 1\n result += max_profit\n return result\n\n"}} diff --git a/cp/cp-10303.jsonl b/cp/cp-10303.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4dc22dc5193d4522d859692b0c2e88568fd034bd --- /dev/null +++ b/cp/cp-10303.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10303", "name": "LeetCode 0827: Making A Large Island"} +{"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: Making A Large Island (Difficulty: Hard)\nTags: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix\n\nYou are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.\nReturn the size of the largest island in grid after applying this operation.\nAn island is a 4-directionally connected group of 1s.\n\nExample 1:\nInput: grid = [[1,0],[0,1]]\nOutput: 3\nExplanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.\n\nExample 2:\nInput: grid = [[1,1],[1,0]]\nOutput: 4\nExplanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.\n\nExample 3:\nInput: grid = [[1,1],[1,1]]\nOutput: 4\nExplanation: Can't change any 0 to 1, only one island with area = 4.\n\nConstraints:\n- n == grid.length\n- n == grid[i].length\n- 1 <= n <= 500\n- grid[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2)\n\n\nclass Solution(object):\n def largestIsland(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n\n def dfs(r, c, index, grid):\n if not (0 <= r < len(grid) and\n 0 <= c < len(grid[0]) and\n grid[r][c] == 1):\n return 0\n result = 1\n grid[r][c] = index\n for d in directions:\n result += dfs(r+d[0], c+d[1], index, grid)\n return result\n\n area = {}\n index = 2\n for r in range(len(grid)):\n for c in range(len(grid[r])):\n if grid[r][c] == 1:\n area[index] = dfs(r, c, index, grid)\n index += 1\n\n result = max(area.values() or [0])\n for r in range(len(grid)):\n for c in range(len(grid[r])):\n if grid[r][c] == 0:\n seen = set()\n for d in directions:\n nr, nc = r+d[0], c+d[1]\n if not (0 <= nr < len(grid) and\n 0 <= nc < len(grid[0]) and\n grid[nr][nc] > 1):\n continue\n seen.add(grid[nr][nc])\n result = max(result, 1 + sum(area[i] for i in seen))\n return result\n\n"}} diff --git a/cp/cp-10304.jsonl b/cp/cp-10304.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..417a398d288e05df9c5f3ef8ac2cba440db83cc6 --- /dev/null +++ b/cp/cp-10304.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10304", "name": "LeetCode 0828: Count Unique Characters Of All Substrings Of A Given 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: Count Unique Characters of All Substrings of a Given String (Difficulty: Hard)\nTags: Hash Table, String, Dynamic Programming\n\nLet's define a function countUniqueChars(s) that returns the number of unique characters in s.\nGiven a string s, return the sum of countUniqueChars(t) where t is a substring of s. The test cases are generated such that the answer fits in a 32-bit integer.\nNotice that some substrings can be repeated so in this case you have to count the repeated ones too.\n\nExample 1:\nInput: s = \"ABC\"\nOutput: 10\nExplanation: All possible substrings are: \"A\",\"B\",\"C\",\"AB\",\"BC\" and \"ABC\".\nEvery substring is composed with only unique letters.\nSum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10\n\nExample 2:\nInput: s = \"ABA\"\nOutput: 8\nExplanation: The same as example 1, except countUniqueChars(\"ABA\") = 1.\n\nExample 3:\nInput: s = \"LEETCODE\"\nOutput: 92\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s consists of uppercase English letters only."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport string\n\n\nclass Solution(object):\n def uniqueLetterString(self, S):\n \"\"\"\n :type S: str\n :rtype: int\n \"\"\"\n M = 10**9 + 7\n index = {c: [-1, -1] for c in string.ascii_uppercase}\n result = 0\n for i, c in enumerate(S):\n k, j = index[c]\n result = (result + (i-j) * (j-k)) % M\n index[c] = [j, i]\n for c in index:\n k, j = index[c]\n result = (result + (len(S)-j) * (j-k)) % M\n return result\n\n"}} diff --git a/cp/cp-10305.jsonl b/cp/cp-10305.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5be7d8ea408028adeb2f11f40afb56621d20dcbb --- /dev/null +++ b/cp/cp-10305.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10305", "name": "LeetCode 0829: Consecutive Numbers Sum"} +{"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: Consecutive Numbers Sum (Difficulty: Hard)\nTags: Math, Enumeration\n\nGiven an integer n, return the number of ways you can write n as the sum of consecutive positive integers.\n\nExample 1:\nInput: n = 5\nOutput: 2\nExplanation: 5 = 2 + 3\n\nExample 2:\nInput: n = 9\nOutput: 3\nExplanation: 9 = 4 + 5 = 2 + 3 + 4\n\nExample 3:\nInput: n = 15\nOutput: 4\nExplanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5\n\nConstraints:\n- 1 <= n <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(sqrt(n))\n# Space: O(1)\n\nclass Solution(object):\n def consecutiveNumbersSum(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n # x + x+1 + x+2 + ... + x+l-1 = N = 2^k * M, where k >= 0 and M is odd\n # => l*x + (l-1)*l/2 = 2^k * M\n # => x = (2^k * M - (l-1)*l/2) / l = 2^k * M/l - (l-1)/2 is a positive integer\n # => l is either 2^(k+1)*M/f or f (f is factors of M)\n # => the answer is the number of all odd factors of M\n # if prime factorization of N is 2^k * p1^a * p2^b * ...\n # => answer is the number of all odd factors = (a+1) * (b+1) * ...\n result = 1\n while N % 2 == 0:\n N /= 2\n i = 3\n while i*i <= N:\n count = 0\n while N % i == 0:\n N /= i\n count += 1\n result *= count+1\n i += 2\n if N != 1: # N is the last prime if N != 1\n result *= 1+1\n return result\n\n"}} diff --git a/cp/cp-10306.jsonl b/cp/cp-10306.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..590ee85b997962a09bfb6ab94df4c97f87c1acb6 --- /dev/null +++ b/cp/cp-10306.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10306", "name": "LeetCode 0830: Positions Of Large Groups"} +{"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: Positions of Large Groups (Difficulty: Easy)\nTags: String\n\nIn a string s of lowercase letters, these letters form consecutive groups of the same character.\nFor example, a string like s = \"abbxxxxzyy\" has the groups \"a\", \"bb\", \"xxxx\", \"z\", and \"yy\".\nA group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In the above example, \"xxxx\" has the interval [3,6].\nA group is considered large if it has 3 or more characters.\nReturn the intervals of every large group sorted in increasing order by start index.\n\nExample 1:\nInput: s = \"abbxxxxzzy\"\nOutput: [[3,6]]\nExplanation: \"xxxx\" is the only large group with start index 3 and end index 6.\n\nExample 2:\nInput: s = \"abc\"\nOutput: []\nExplanation: We have groups \"a\", \"b\", and \"c\", none of which are large groups.\n\nExample 3:\nInput: s = \"abcdddeeeeaabbbcd\"\nOutput: [[3,5],[6,9],[12,14]]\nExplanation: The large groups are \"ddd\", \"eeee\", and \"bbb\".\n\nConstraints:\n- 1 <= s.length <= 1000\n- s contains lowercase English letters only."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n\nclass Solution(object):\n def largeGroupPositions(self, S):\n \"\"\"\n :type S: str\n :rtype: List[List[int]]\n \"\"\"\n result = []\n i = 0\n for j in range(len(S)):\n if j == len(S)-1 or S[j] != S[j+1]:\n if j-i+1 >= 3:\n result.append([i, j])\n i = j+1\n return result\n\n"}} diff --git a/cp/cp-10307.jsonl b/cp/cp-10307.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..246d92ddfd4866ac4a54457ba65b84b6db249e4b --- /dev/null +++ b/cp/cp-10307.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10307", "name": "LeetCode 0831: Masking Personal Information"} +{"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: Masking Personal Information (Difficulty: Medium)\nTags: String\n\nYou are given a personal information string s, representing either an email address or a phone number. Return the masked personal information using the below rules.\nEmail address:\nAn email address is:\nTo mask an email:\nPhone number:\nA phone number is formatted as follows:\nTo mask a phone number:\n\nExample 1:\nInput: s = \"LeetCode@LeetCode.com\"\nOutput: \"l*****e@leetcode.com\"\nExplanation: s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\n\nExample 2:\nInput: s = \"AB@qq.com\"\nOutput: \"a*****b@qq.com\"\nExplanation: s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\nNote that even though \"ab\" is 2 characters, it still must have 5 asterisks in the middle.\n\nExample 3:\nInput: s = \"1(234)567-890\"\nOutput: \"***-***-7890\"\nExplanation: s is a phone number.\nThere are 10 digits, so the local number is 10 digits and the country code is 0 digits.\nThus, the resulting masked number is \"***-***-7890\".\n\nConstraints:\n- s is either a valid email or a phone number.\n- If s is an email:\n\t\n8 <= s.length <= 40\ns consists of uppercase and lowercase English letters and exactly one '@' symbol and '.' symbol.\n- 8 <= s.length <= 40\n- s consists of uppercase and lowercase English letters and exactly one '@' symbol and '.' symbol.\n- If s is a phone number:\n\t\n10 <= s.length <= 20\ns consists of digits, spaces, and the symbols '(', ')', '-', and '+'.\n- 10 <= s.length <= 20\n- s consists of digits, spaces, and the symbols '(', ')', '-', and '+'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def maskPII(self, S):\n \"\"\"\n :type S: str\n :rtype: str\n \"\"\"\n if '@' in S:\n first, after = S.split('@')\n return \"{}*****{}@{}\".format(first[0], first[-1], after).lower()\n\n digits = filter(lambda x: x.isdigit(), S)\n local = \"***-***-{}\".format(digits[-4:])\n if len(digits) == 10:\n return local\n return \"+{}-{}\".format('*' * (len(digits) - 10), local)\n\n"}} diff --git a/cp/cp-10308.jsonl b/cp/cp-10308.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f6d152fa920c94b70565ffbea94bcec6472ff006 --- /dev/null +++ b/cp/cp-10308.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10308", "name": "LeetCode 0832: Flipping An Image"} +{"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: Flipping an Image (Difficulty: Easy)\nTags: Array, Two Pointers, Bit Manipulation, Matrix, Simulation\n\nGiven an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.\nTo flip an image horizontally means that each row of the image is reversed.\nTo invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.\n\nExample 1:\nInput: image = [[1,1,0],[1,0,1],[0,0,0]]\nOutput: [[1,0,0],[0,1,0],[1,1,1]]\nExplanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\nThen, invert the image: [[1,0,0],[0,1,0],[1,1,1]]\n\nExample 2:\nInput: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]\nOutput: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\nExplanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].\nThen invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\n\nConstraints:\n- n == image.length\n- n == image[i].length\n- 1 <= n <= 20\n- images[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(1)\n\n\nclass Solution(object):\n def flipAndInvertImage(self, A):\n \"\"\"\n :type A: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n for row in A:\n for i in range((len(row)+1) // 2):\n row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1\n return A\n\n"}} diff --git a/cp/cp-10309.jsonl b/cp/cp-10309.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8a53c0bc1e85bf688b8d5130b7469bd8608a72de --- /dev/null +++ b/cp/cp-10309.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10309", "name": "LeetCode 0833: Find And Replace In 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: Find And Replace in String (Difficulty: Medium)\nTags: Array, Hash Table, String, Sorting\n\nYou are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k.\nTo complete the ith replacement operation:\nFor example, if s = \"abcd\", indices[i] = 0, sources[i] = \"ab\", and targets[i] = \"eee\", then the result of this replacement will be \"eeecd\".\nAll replacement operations must occur simultaneously, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap.\nReturn the resulting string after performing all replacement operations on s.\nA substring is a contiguous sequence of characters in a string.\n\nExample 1:\nInput: s = \"abcd\", indices = [0, 2], sources = [\"a\", \"cd\"], targets = [\"eee\", \"ffff\"]\nOutput: \"eeebffff\"\nExplanation:\n\"a\" occurs at index 0 in s, so we replace it with \"eee\".\n\"cd\" occurs at index 2 in s, so we replace it with \"ffff\".\n\nExample 2:\nInput: s = \"abcd\", indices = [0, 2], sources = [\"ab\",\"ec\"], targets = [\"eee\",\"ffff\"]\nOutput: \"eeecd\"\nExplanation:\n\"ab\" occurs at index 0 in s, so we replace it with \"eee\".\n\"ec\" does not occur at index 2 in s, so we do nothing.\n\nConstraints:\n- 1 <= s.length <= 1000\n- k == indices.length == sources.length == targets.length\n- 1 <= k <= 100\n- 0 <= indexes[i] < s.length\n- 1 <= sources[i].length, targets[i].length <= 50\n- s consists of only lowercase English letters.\n- sources[i] and targets[i] consist of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + m), m is the number of targets\n# Space: O(n)\n\nclass Solution(object):\n def findReplaceString(self, S, indexes, sources, targets):\n \"\"\"\n :type S: str\n :type indexes: List[int]\n :type sources: List[str]\n :type targets: List[str]\n :rtype: str\n \"\"\"\n bucket = [None] * len(S)\n for i in range(len(indexes)):\n if all(indexes[i]+k < len(S) and S[indexes[i]+k] == sources[i][k]\n for k in range(len(sources[i]))):\n bucket[indexes[i]] = (len(sources[i]), list(targets[i]))\n result = []\n i = 0\n while i < len(S):\n if bucket[i]:\n result.extend(bucket[i][1])\n i += bucket[i][0]\n else:\n result.append(S[i])\n i += 1\n return \"\".join(result)\n\n\n# Time: O(mlogm + m * n)\n# Space: O(n + m)\nclass Solution2(object):\n def findReplaceString(self, S, indexes, sources, targets):\n \"\"\"\n :type S: str\n :type indexes: List[int]\n :type sources: List[str]\n :type targets: List[str]\n :rtype: str\n \"\"\"\n for i, s, t in sorted(zip(indexes, sources, targets), reverse=True):\n if S[i:i+len(s)] == s:\n S = S[:i] + t + S[i+len(s):]\n\n return S\n"}} diff --git a/cp/cp-10310.jsonl b/cp/cp-10310.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0886a6f2109c3048dac75e52ba5c08775d418bc7 --- /dev/null +++ b/cp/cp-10310.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10310", "name": "LeetCode 0834: Sum Of Distances In 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: Sum of Distances in Tree (Difficulty: Hard)\nTags: Dynamic Programming, Tree, Depth-First Search, Graph\n\nThere is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.\nYou are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.\nReturn an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.\n\nExample 1:\nInput: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]\nOutput: [8,12,6,10,10,10]\nExplanation: The tree is shown above.\nWe can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\nequals 1 + 1 + 2 + 2 + 2 = 8.\nHence, answer[0] = 8, and so on.\n\nExample 2:\nInput: n = 1, edges = []\nOutput: [0]\n\nExample 3:\nInput: n = 2, edges = [[1,0]]\nOutput: [1,1]\n\nConstraints:\n- 1 <= n <= 3 * 10^4\n- edges.length == n - 1\n- edges[i].length == 2\n- 0 <= ai, bi < n\n- ai != bi\n- The given input represents a valid tree."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def sumOfDistancesInTree(self, N, edges):\n \"\"\"\n :type N: int\n :type edges: List[List[int]]\n :rtype: List[int]\n \"\"\"\n def dfs(graph, node, parent, count, result):\n for nei in graph[node]:\n if nei != parent:\n dfs(graph, nei, node, count, result)\n count[node] += count[nei]\n result[node] += result[nei]+count[nei]\n\n def dfs2(graph, node, parent, count, result):\n for nei in graph[node]:\n if nei != parent:\n result[nei] = result[node]-count[nei] + \\\n len(count)-count[nei]\n dfs2(graph, nei, node, count, result)\n\n graph = collections.defaultdict(list)\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n\n count = [1] * N\n result = [0] * N\n\n dfs(graph, 0, None, count, result)\n dfs2(graph, 0, None, count, result)\n return result\n\n"}} diff --git a/cp/cp-10311.jsonl b/cp/cp-10311.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f97636fc2e3c6ba16289840f0d905e2eb45d94b8 --- /dev/null +++ b/cp/cp-10311.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10311", "name": "LeetCode 0835: Image Overlap"} +{"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 Overlap (Difficulty: Medium)\nTags: Array, Matrix\n\nYou are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values.\nWe translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images.\nNote also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased.\nReturn the largest possible overlap.\n\nExample 1:\nInput: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]\nOutput: 3\nExplanation: We translate img1 to right by 1 unit and down by 1 unit.\n\nThe number of positions that have a 1 in both images is 3 (shown in red).\n\nExample 2:\nInput: img1 = [[1]], img2 = [[1]]\nOutput: 1\n\nExample 3:\nInput: img1 = [[0]], img2 = [[0]]\nOutput: 0\n\nConstraints:\n- n == img1.length == img1[i].length\n- n == img2.length == img2[i].length\n- 1 <= n <= 30\n- img1[i][j] is either 0 or 1.\n- img2[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^4)\n# Space: O(n^2)\n\nclass Solution(object):\n def largestOverlap(self, A, B):\n \"\"\"\n :type A: List[List[int]]\n :type B: List[List[int]]\n :rtype: int\n \"\"\"\n count = [0] * (2*len(A)-1)**2\n for i, row in enumerate(A):\n for j, v in enumerate(row):\n if not v:\n continue\n for i2, row2 in enumerate(B):\n for j2, v2 in enumerate(row2):\n if not v2:\n continue\n count[(len(A)-1+i-i2)*(2*len(A)-1) +\n len(A)-1+j-j2] += 1\n return max(count)\n\n"}} diff --git a/cp/cp-10312.jsonl b/cp/cp-10312.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4320d4499b47d6b8e6ed6baeb9ae9576301dd57c --- /dev/null +++ b/cp/cp-10312.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10312", "name": "LeetCode 0836: Rectangle Overlap"} +{"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: Rectangle Overlap (Difficulty: Easy)\nTags: Math, Geometry\n\nAn axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.\nTwo rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.\nGiven two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.\n\nExample 1:\nInput: rec1 = [0,0,2,2], rec2 = [1,1,3,3]\nOutput: true\n\nExample 2:\nInput: rec1 = [0,0,1,1], rec2 = [1,0,2,1]\nOutput: false\n\nExample 3:\nInput: rec1 = [0,0,1,1], rec2 = [2,2,3,3]\nOutput: false\n\nConstraints:\n- rec1.length == 4\n- rec2.length == 4\n- -10^9 <= rec1[i], rec2[i] <= 10^9\n- rec1 and rec2 represent a valid rectangle with a non-zero area."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def isRectangleOverlap(self, rec1, rec2):\n \"\"\"\n :type rec1: List[int]\n :type rec2: List[int]\n :rtype: bool\n \"\"\"\n def intersect(p_left, p_right, q_left, q_right):\n return max(p_left, q_left) < min(p_right, q_right)\n\n return (intersect(rec1[0], rec1[2], rec2[0], rec2[2]) and\n intersect(rec1[1], rec1[3], rec2[1], rec2[3]))\n\n"}} diff --git a/cp/cp-10313.jsonl b/cp/cp-10313.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..96c71adddd8b7090b3db07623eee0494938abd16 --- /dev/null +++ b/cp/cp-10313.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10313", "name": "LeetCode 0838: Push Dominoes"} +{"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: Push Dominoes (Difficulty: Medium)\nTags: Two Pointers, String, Dynamic Programming\n\nThere are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.\nAfter each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.\nWhen a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.\nFor the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.\nYou are given a string dominoes representing the initial state where:\nReturn a string representing the final state.\n\nExample 1:\nInput: dominoes = \"RR.L\"\nOutput: \"RR.L\"\nExplanation: The first domino expends no additional force on the second domino.\n\nExample 2:\nInput: dominoes = \".L.R...LR..L..\"\nOutput: \"LL.RR.LLRRLL..\"\n\nConstraints:\n- n == dominoes.length\n- 1 <= n <= 10^5\n- dominoes[i] is either 'L', 'R', or '.'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\n\nclass Solution(object):\n def pushDominoes(self, dominoes):\n \"\"\"\n :type dominoes: str\n :rtype: str\n \"\"\"\n force = [0]*len(dominoes)\n\n f = 0\n for i in range(len(dominoes)):\n if dominoes[i] == 'R':\n f = len(dominoes)\n elif dominoes[i] == 'L':\n f = 0\n else:\n f = max(f-1, 0)\n force[i] += f\n\n f = 0\n for i in reversed(range(len(dominoes))):\n if dominoes[i] == 'L':\n f = len(dominoes)\n elif dominoes[i] == 'R':\n f = 0\n else:\n f = max(f-1, 0)\n force[i] -= f\n\n return \"\".join('.' if f == 0 else 'R' if f > 0 else 'L'\n for f in force)\n\n"}} diff --git a/cp/cp-10314.jsonl b/cp/cp-10314.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..55590c19f608f20b36d5e14b75a0b78e68527302 --- /dev/null +++ b/cp/cp-10314.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10314", "name": "LeetCode 0839: Similar String Groups"} +{"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: Similar String Groups (Difficulty: Hard)\nTags: Array, Hash Table, String, Depth-First Search, Breadth-First Search, Union Find\n\nTwo strings, X and Y, are considered similar if either they are identical or we can make them equivalent by swapping at most two letters (in distinct positions) within the string X.\nFor example, \"tars\" and \"rats\" are similar (swapping at positions 0 and 2), and \"rats\" and \"arts\" are similar, but \"star\" is not similar to \"tars\", \"rats\", or \"arts\".\nTogether, these form two connected groups by similarity: {\"tars\", \"rats\", \"arts\"} and {\"star\"}.  Notice that \"tars\" and \"arts\" are in the same group even though they are not similar.  Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.\nWe are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?\n\nExample 1:\nInput: strs = [\"tars\",\"rats\",\"arts\",\"star\"]\nOutput: 2\n\nExample 2:\nInput: strs = [\"omv\",\"ovm\"]\nOutput: 1\n\nConstraints:\n- 1 <= strs.length <= 300\n- 1 <= strs[i].length <= 300\n- strs[i] consists of lowercase letters only.\n- All words in strs have the same length and are anagrams of each other."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2 * l) ~ O(n * l^4)\n# Space: O(n) ~ O(n * l^3)\n\nimport collections\nimport itertools\n\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n self.__size = n\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n self.__size -= 1\n return True\n\n def size(self):\n return self.__size\n\n\nclass Solution(object):\n def numSimilarGroups(self, A):\n def isSimilar(a, b):\n diff = 0\n for x, y in itertools.izip(a, b):\n if x != y:\n diff += 1\n if diff > 2:\n return False\n return diff == 2\n\n N, L = len(A), len(A[0])\n union_find = UnionFind(N)\n if N < L*L:\n for (i1, word1), (i2, word2) in \\\n itertools.combinations(enumerate(A), 2):\n if isSimilar(word1, word2):\n union_find.union_set(i1, i2)\n else:\n buckets = collections.defaultdict(list)\n lookup = set()\n for i in range(len(A)):\n word = list(A[i])\n if A[i] not in lookup:\n buckets[A[i]].append(i)\n lookup.add(A[i])\n for j1, j2 in itertools.combinations(range(L), 2):\n word[j1], word[j2] = word[j2], word[j1]\n buckets[\"\".join(word)].append(i)\n word[j1], word[j2] = word[j2], word[j1]\n for word in A: # Time: O(n * l^4)\n for i1, i2 in itertools.combinations(buckets[word], 2):\n union_find.union_set(i1, i2)\n return union_find.size()\n\n"}} diff --git a/cp/cp-10315.jsonl b/cp/cp-10315.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ac9498de871fcbef953833f30bc6989ea26c5fd7 --- /dev/null +++ b/cp/cp-10315.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10315", "name": "LeetCode 0840: Magic Squares In Grid"} +{"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: Magic Squares In Grid (Difficulty: Medium)\nTags: Array, Hash Table, Math, Matrix\n\nA 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.\nGiven a row x col grid of integers, how many 3 x 3 magic square subgrids are there?\nNote: while a magic square can only contain numbers from 1 to 9, grid may contain numbers up to 15.\n\nExample 1:\nInput: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]\nOutput: 1\nExplanation: \nThe following subgrid is a 3 x 3 magic square:\n\nwhile this one is not:\n\nIn total, there is only one magic square inside the given grid.\n\nExample 2:\nInput: grid = [[8]]\nOutput: 0\n\nConstraints:\n- row == grid.length\n- col == grid[i].length\n- 1 <= row, col <= 10\n- 0 <= grid[i][j] <= 15"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\n\nclass Solution(object):\n def numMagicSquaresInside(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n def magic(grid, r, c):\n expect = k * (k**2+1) // 2\n nums = set()\n min_num = float(\"inf\")\n sum_diag, sum_anti = 0, 0\n for i in range(k):\n sum_diag += grid[r+i][c+i]\n sum_anti += grid[r+i][c+k-1-i]\n sum_r, sum_c = 0, 0\n for j in range(k):\n min_num = min(min_num, grid[r+i][c+j])\n nums.add(grid[r+i][c+j])\n sum_r += grid[r+i][c+j]\n sum_c += grid[r+j][c+i]\n if not (sum_r == sum_c == expect):\n return False\n return sum_diag == sum_anti == expect and \\\n len(nums) == k**2 and \\\n min_num == 1\n\n k = 3\n result = 0\n for r in range(len(grid)-k+1):\n for c in range(len(grid[r])-k+1):\n if magic(grid, r, c):\n result += 1\n return result\n\n"}} diff --git a/cp/cp-10316.jsonl b/cp/cp-10316.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..58b5b665e64e2043db3c9d3a8e89e59a2c095ef1 --- /dev/null +++ b/cp/cp-10316.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10316", "name": "LeetCode 0841: Keys And Rooms"} +{"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: Keys and Rooms (Difficulty: Medium)\nTags: Depth-First Search, Breadth-First Search, Graph\n\nThere are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.\nWhen you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.\nGiven an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.\n\nExample 1:\nInput: rooms = [[1],[2],[3],[]]\nOutput: true\nExplanation: \nWe visit room 0 and pick up key 1.\nWe then visit room 1 and pick up key 2.\nWe then visit room 2 and pick up key 3.\nWe then visit room 3.\nSince we were able to visit every room, we return true.\n\nExample 2:\nInput: rooms = [[1,3],[3,0,1],[2],[0]]\nOutput: false\nExplanation: We can not enter room number 2 since the only key that unlocks it is in that room.\n\nConstraints:\n- n == rooms.length\n- 2 <= n <= 1000\n- 0 <= rooms[i].length <= 1000\n- 1 <= sum(rooms[i].length) <= 3000\n- 0 <= rooms[i][j] < n\n- All the values of rooms[i] are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n!)\n# Space: O(n)\n\nclass Solution(object):\n def canVisitAllRooms(self, rooms):\n \"\"\"\n :type rooms: List[List[int]]\n :rtype: bool\n \"\"\"\n lookup = set([0])\n stack = [0]\n while stack:\n node = stack.pop()\n for nei in rooms[node]:\n if nei not in lookup:\n lookup.add(nei)\n if len(lookup) == len(rooms):\n return True\n stack.append(nei)\n return len(lookup) == len(rooms)\n\n"}} diff --git a/cp/cp-10317.jsonl b/cp/cp-10317.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..12df532c689ed3e61ecd635450fd0aa59c19d82e --- /dev/null +++ b/cp/cp-10317.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10317", "name": "LeetCode 0842: Split Array Into Fibonacci Sequence"} +{"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 Fibonacci Sequence (Difficulty: Medium)\nTags: String, Backtracking\n\nYou are given a string of digits num, such as \"123456579\". We can split it into a Fibonacci-like sequence [123, 456, 579].\nFormally, a Fibonacci-like sequence is a list f of non-negative integers such that:\nNote that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself.\nReturn any Fibonacci-like sequence split from num, or return [] if it cannot be done.\n\nExample 1:\nInput: num = \"1101111\"\nOutput: [11,0,11,11]\nExplanation: The output [110, 1, 111] would also be accepted.\n\nExample 2:\nInput: num = \"112358130\"\nOutput: []\nExplanation: The task is impossible.\n\nExample 3:\nInput: num = \"0123\"\nOutput: []\nExplanation: Leading zeroes are not allowed, so \"01\", \"2\", \"3\" is not valid.\n\nConstraints:\n- 1 <= num.length <= 200\n- num contains only digits."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(n)\n\n\nclass Solution(object):\n def splitIntoFibonacci(self, S):\n \"\"\"\n :type S: str\n :rtype: List[int]\n \"\"\"\n def startswith(S, k, x):\n y = 0\n for i in range(k, len(S)):\n y = 10*y + int(S[i])\n if y == x:\n return i-k+1\n elif y > x:\n break\n return 0\n\n MAX_INT = 2**31-1\n a = 0\n for i in range(len(S)-2):\n a = 10*a + int(S[i])\n b = 0\n for j in range(i+1, len(S)-1):\n b = 10*b + int(S[j])\n fib = [a, b]\n k = j+1\n while k < len(S):\n if fib[-2] > MAX_INT-fib[-1]:\n break\n c = fib[-2]+fib[-1]\n length = startswith(S, k, c)\n if length == 0:\n break\n fib.append(c)\n k += length\n else:\n return fib\n if b == 0:\n break\n if a == 0:\n break\n return []\n\n"}} diff --git a/cp/cp-10318.jsonl b/cp/cp-10318.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9207395cc1ea6e596fb330261eb328f721af2706 --- /dev/null +++ b/cp/cp-10318.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10318", "name": "LeetCode 0843: Guess The Word"} +{"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: Guess the Word (Difficulty: Hard)\nTags: Array, Math, String, Interactive, Game Theory\n\nYou are given an array of unique strings words where words[i] is six letters long. One word of words was chosen as a secret word.\nYou are also given the helper object Master. You may call Master.guess(word) where word is a six-letter-long string, and it must be from words. Master.guess(word) returns:\nThere is a parameter allowedGuesses for each test case where allowedGuesses is the maximum number of times you can call Master.guess(word).\nFor each test case, you should call Master.guess with the secret word without exceeding the maximum number of allowed guesses. You will get:\nThe test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method).\n\nExample 1:\nInput: secret = \"acckzz\", words = [\"acckzz\",\"ccbazz\",\"eiowzz\",\"abcczz\"], allowedGuesses = 10\nOutput: You guessed the secret word correctly.\nExplanation:\nmaster.guess(\"aaaaaa\") returns -1, because \"aaaaaa\" is not in wordlist.\nmaster.guess(\"acckzz\") returns 6, because \"acckzz\" is secret and has all 6 matches.\nmaster.guess(\"ccbazz\") returns 3, because \"ccbazz\" has 3 matches.\nmaster.guess(\"eiowzz\") returns 2, because \"eiowzz\" has 2 matches.\nmaster.guess(\"abcczz\") returns 4, because \"abcczz\" has 4 matches.\nWe made 5 calls to master.guess, and one of them was the secret, so we pass the test case.\n\nExample 2:\nInput: secret = \"hamada\", words = [\"hamada\",\"khaled\"], allowedGuesses = 10\nOutput: You guessed the secret word correctly.\nExplanation: Since there are two words, you can guess both.\n\nConstraints:\n- 1 <= words.length <= 100\n- words[i].length == 6\n- words[i] consist of lowercase English letters.\n- All the strings of wordlist are unique.\n- secret exists in words.\n- 10 <= allowedGuesses <= 30"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\nimport itertools\n\n\nclass Solution(object):\n def findSecretWord(self, wordlist, master):\n \"\"\"\n :type wordlist: List[Str]\n :type master: Master\n :rtype: None\n \"\"\"\n possible = range(len(wordlist))\n n = 0\n while n < 6:\n count = [collections.Counter(w[i] for w in wordlist) for i in range(6)]\n guess = max(possible, key=lambda x: sum(count[i][c] for i, c in enumerate(wordlist[x])))\n n = master.guess(wordlist[guess])\n possible = [j for j in possible if sum(a == b for a, b in itertools.izip(wordlist[guess], wordlist[j])) == n]\n\n\n# Time: O(n^2)\n# Space: O(n)\nclass Solution2(object):\n def findSecretWord(self, wordlist, master):\n \"\"\"\n :type wordlist: List[Str]\n :type master: Master\n :rtype: None\n \"\"\"\n def solve(H, possible):\n min_max_group, best_guess = possible, None\n for guess in possible:\n groups = [[] for _ in range(7)]\n for j in possible:\n if j != guess:\n groups[H[guess][j]].append(j)\n max_group = max(groups, key=len)\n if len(max_group) < len(min_max_group):\n min_max_group, best_guess = max_group, guess\n return best_guess\n\n H = [[sum(a == b for a, b in itertools.izip(wordlist[i], wordlist[j]))\n for j in range(len(wordlist))]\n for i in range(len(wordlist))]\n possible = range(len(wordlist))\n n = 0\n while n < 6:\n guess = solve(H, possible)\n n = master.guess(wordlist[guess])\n possible = [j for j in possible if H[guess][j] == n]\n\n\n# Time: O(n^2)\n# Space: O(n)\nclass Solution3(object):\n def findSecretWord(self, wordlist, master):\n \"\"\"\n :type wordlist: List[Str]\n :type master: Master\n :rtype: None\n \"\"\"\n def solve(H, possible):\n min_max_group, best_guess = possible, None\n for guess in possible:\n groups = [[] for _ in range(7)]\n for j in possible:\n if j != guess:\n groups[H[guess][j]].append(j)\n max_group = groups[0]\n if len(max_group) < len(min_max_group):\n min_max_group, best_guess = max_group, guess\n return best_guess\n\n H = [[sum(a == b for a, b in itertools.izip(wordlist[i], wordlist[j]))\n for j in range(len(wordlist))]\n for i in range(len(wordlist))]\n possible = range(len(wordlist))\n n = 0\n while n < 6:\n guess = solve(H, possible)\n n = master.guess(wordlist[guess])\n possible = [j for j in possible if H[guess][j] == n]\n\n"}} diff --git a/cp/cp-10319.jsonl b/cp/cp-10319.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5e2acaf9203405d0c9ba819b45f036fa090d67c6 --- /dev/null +++ b/cp/cp-10319.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10319", "name": "LeetCode 0844: Backspace String Compare"} +{"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: Backspace String Compare (Difficulty: Easy)\nTags: Two Pointers, String, Stack, Simulation\n\nGiven two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.\nNote that after backspacing an empty text, the text will continue empty.\nFollow up: Can you solve it in O(n) time and O(1) space?\n\nExample 1:\nInput: s = \"ab#c\", t = \"ad#c\"\nOutput: true\nExplanation: Both s and t become \"ac\".\n\nExample 2:\nInput: s = \"ab##\", t = \"c#d#\"\nOutput: true\nExplanation: Both s and t become \"\".\n\nExample 3:\nInput: s = \"a#c\", t = \"b\"\nOutput: false\nExplanation: s becomes \"c\" while t becomes \"b\".\n\nConstraints:\n- 1 <= s.length, t.length <= 200\n- s and t only contain lowercase letters and '#' characters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def backspaceCompare(self, S, T):\n \"\"\"\n :type S: str\n :type T: str\n :rtype: bool\n \"\"\"\n def findNextChar(S):\n skip = 0\n for i in reversed(range(len(S))):\n if S[i] == '#':\n skip += 1\n elif skip:\n skip -= 1\n else:\n yield S[i]\n\n return all(x == y for x, y in\n itertools.izip_longest(findNextChar(S), findNextChar(T)))\n\n"}} diff --git a/cp/cp-10320.jsonl b/cp/cp-10320.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8cf9f6e818cfeca7ca9135b1b53be3b221350087 --- /dev/null +++ b/cp/cp-10320.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10320", "name": "LeetCode 0845: Longest Mountain In 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: Longest Mountain in Array (Difficulty: Medium)\nTags: Array, Two Pointers, Dynamic Programming, Enumeration\n\nYou may recall that an array arr is a mountain array if and only if:\nGiven an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray.\nFollow up:\n\nExample 1:\nInput: arr = [2,1,4,7,3,2,5]\nOutput: 5\nExplanation: The largest mountain is [1,4,7,3,2] which has length 5.\n\nExample 2:\nInput: arr = [2,2,2]\nOutput: 0\nExplanation: There is no mountain.\n\nConstraints:\n- 1 <= arr.length <= 10^4\n- 0 <= arr[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n\nclass Solution(object):\n def longestMountain(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n result, up_len, down_len = 0, 0, 0\n for i in range(1, len(A)):\n if (down_len and A[i-1] < A[i]) or A[i-1] == A[i]:\n up_len, down_len = 0, 0\n up_len += A[i-1] < A[i]\n down_len += A[i-1] > A[i]\n if up_len and down_len:\n result = max(result, up_len+down_len+1)\n return result\n\n"}} diff --git a/cp/cp-10321.jsonl b/cp/cp-10321.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f005b4ea803250b113d02a3ef9cf88711a0c9a48 --- /dev/null +++ b/cp/cp-10321.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10321", "name": "LeetCode 0846: Hand Of Straights"} +{"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: Hand of Straights (Difficulty: Medium)\nTags: Array, Hash Table, Greedy, Sorting\n\nAlice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.\nGiven an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.\nNote: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/\n\nExample 1:\nInput: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3\nOutput: true\nExplanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]\n\nExample 2:\nInput: hand = [1,2,3,4,5], groupSize = 4\nOutput: false\nExplanation: Alice's hand can not be rearranged into groups of 4.\n\nConstraints:\n- 1 <= hand.length <= 10^4\n- 0 <= hand[i] <= 10^9\n- 1 <= groupSize <= hand.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nfrom collections import Counter\nfrom heapq import heapify, heappop\n\n\nclass Solution(object):\n def isNStraightHand(self, hand, W):\n \"\"\"\n :type hand: List[int]\n :type W: int\n :rtype: bool\n \"\"\"\n if len(hand) % W:\n return False\n\n counts = Counter(hand)\n min_heap = list(hand)\n heapify(min_heap)\n for _ in range(len(min_heap)//W):\n while counts[min_heap[0]] == 0:\n heappop(min_heap)\n start = heappop(min_heap)\n for _ in range(W):\n counts[start] -= 1\n if counts[start] < 0:\n return False\n start += 1\n return True\n"}} diff --git a/cp/cp-10322.jsonl b/cp/cp-10322.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8d6d5fa8f9a81428cde04f6085e844c68a428e8b --- /dev/null +++ b/cp/cp-10322.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10322", "name": "LeetCode 0847: Shortest Path Visiting All Nodes"} +{"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: Shortest Path Visiting All Nodes (Difficulty: Hard)\nTags: Dynamic Programming, Bit Manipulation, Breadth-First Search, Graph, Bitmask\n\nYou have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge.\nReturn the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.\n\nExample 1:\nInput: graph = [[1,2,3],[0],[0],[0]]\nOutput: 4\nExplanation: One possible path is [1,0,2,0,3]\n\nExample 2:\nInput: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]\nOutput: 4\nExplanation: One possible path is [0,1,4,2,3]\n\nConstraints:\n- n == graph.length\n- 1 <= n <= 12\n- 0 <= graph[i].length < n\n- graph[i] does not contain i.\n- If graph[a] contains b, then graph[b] contains a.\n- The input graph is always connected."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * 2^n)\n# Space: O(n * 2^n)\n\nimport collections\n\n\nclass Solution(object):\n def shortestPathLength(self, graph):\n \"\"\"\n :type graph: List[List[int]]\n :rtype: int\n \"\"\"\n dp = [[float(\"inf\")]*(len(graph))\n for _ in range(1 << len(graph))]\n q = collections.deque()\n for i in range(len(graph)):\n dp[1 << i][i] = 0\n q.append((1 << i, i))\n while q:\n state, node = q.popleft()\n steps = dp[state][node]\n for nei in graph[node]:\n new_state = state | (1 << nei)\n if dp[new_state][nei] == float(\"inf\"):\n dp[new_state][nei] = steps+1\n q.append((new_state, nei))\n return min(dp[-1])\n\n"}} diff --git a/cp/cp-10323.jsonl b/cp/cp-10323.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..278eda14625c8f8e301f59bd204727d487d6854b --- /dev/null +++ b/cp/cp-10323.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10323", "name": "LeetCode 0848: Shifting Letters"} +{"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: Shifting Letters (Difficulty: Medium)\nTags: Array, String, Prefix Sum\n\nYou are given a string s of lowercase English letters and an integer array shifts of the same length.\nCall the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a').\nNow for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times.\nReturn the final string after all such shifts to s are applied.\n\nExample 1:\nInput: s = \"abc\", shifts = [3,5,9]\nOutput: \"rpl\"\nExplanation: We start with \"abc\".\nAfter shifting the first 1 letters of s by 3, we have \"dbc\".\nAfter shifting the first 2 letters of s by 5, we have \"igc\".\nAfter shifting the first 3 letters of s by 9, we have \"rpl\", the answer.\n\nExample 2:\nInput: s = \"aaa\", shifts = [1,2,3]\nOutput: \"gfd\"\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s consists of lowercase English letters.\n- shifts.length == s.length\n- 0 <= shifts[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def shiftingLetters(self, S, shifts):\n \"\"\"\n :type S: str\n :type shifts: List[int]\n :rtype: str\n \"\"\"\n result = []\n times = sum(shifts) % 26\n for i, c in enumerate(S):\n index = ord(c) - ord('a')\n result.append(chr(ord('a') + (index+times) % 26))\n times = (times-shifts[i]) % 26\n return \"\".join(result)\n\n"}} diff --git a/cp/cp-10324.jsonl b/cp/cp-10324.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6ffd32eed5613b88927467a2b4b7bb23eb71529b --- /dev/null +++ b/cp/cp-10324.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10324", "name": "LeetCode 0849: Maximize Distance To Closest Person"} +{"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: Maximize Distance to Closest Person (Difficulty: Medium)\nTags: Array\n\nYou are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).\nThere is at least one empty seat, and at least one person sitting.\nAlex wants to sit in the seat such that the distance between him and the closest person to him is maximized.\nReturn that maximum distance to the closest person.\n\nExample 1:\nInput: seats = [1,0,0,0,1,0,1]\nOutput: 2\nExplanation: \nIf Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.\nIf Alex sits in any other open seat, the closest person has distance 1.\nThus, the maximum distance to the closest person is 2.\n\nExample 2:\nInput: seats = [1,0,0,0]\nOutput: 3\nExplanation: \nIf Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.\nThis is the maximum distance possible, so the answer is 3.\n\nExample 3:\nInput: seats = [0,1]\nOutput: 1\n\nConstraints:\n- 2 <= seats.length <= 2 * 10^4\n- seats[i] is 0 or 1.\n- At least one seat is empty.\n- At least one seat is occupied."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n\nclass Solution(object):\n def maxDistToClosest(self, seats):\n \"\"\"\n :type seats: List[int]\n :rtype: int\n \"\"\"\n prev, result = -1, 1\n for i in range(len(seats)):\n if seats[i]:\n if prev < 0:\n result = i\n else:\n result = max(result, (i-prev)//2)\n prev = i\n return max(result, len(seats)-1-prev)\n\n"}} diff --git a/cp/cp-10325.jsonl b/cp/cp-10325.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..be32c51bfff59f6791f78aa8bcb2691cc3627fc8 --- /dev/null +++ b/cp/cp-10325.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10325", "name": "LeetCode 0850: Rectangle Area 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: Rectangle Area II (Difficulty: Hard)\nTags: Array, Segment Tree, Line Sweep, Ordered Set\n\nYou are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner.\nCalculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once.\nReturn the total area. Since the answer may be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]\nOutput: 6\nExplanation: A total area of 6 is covered by all three rectangles, as illustrated in the picture.\nFrom (1,1) to (2,2), the green and red rectangles overlap.\nFrom (1,0) to (2,3), all three rectangles overlap.\n\nExample 2:\nInput: rectangles = [[0,0,1000000000,1000000000]]\nOutput: 49\nExplanation: The answer is 1018 modulo (109 + 7), which is 49.\n\nConstraints:\n- 1 <= rectangles.length <= 200\n- rectanges[i].length == 4\n- 0 <= xi1, yi1, xi2, yi2 <= 10^9\n- xi1 <= xi2\n- yi1 <= yi2\n- All rectangles have non zero area."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass SegmentTreeNode(object):\n def __init__(self, start, end):\n self.start, self.end = start, end\n self.total = self.count = 0\n self._left = self._right = None\n\n def mid(self):\n return (self.start+self.end) // 2\n\n def left(self):\n self._left = self._left or SegmentTreeNode(self.start, self.mid())\n return self._left\n\n def right(self):\n self._right = self._right or SegmentTreeNode(self.mid(), self.end)\n return self._right\n\n def update(self, X, i, j, val):\n if i >= j:\n return 0\n if self.start == i and self.end == j:\n self.count += val\n else:\n self.left().update(X, i, min(self.mid(), j), val)\n self.right().update(X, max(self.mid(), i), j, val)\n if self.count > 0:\n self.total = X[self.end]-X[self.start]\n else:\n self.total = self.left().total + self.right().total\n return self.total\n\n\nclass Solution(object):\n def rectangleArea(self, rectangles):\n \"\"\"\n :type rectangles: List[List[int]]\n :rtype: int\n \"\"\"\n OPEN, CLOSE = 1, -1\n events = []\n X = set()\n for x1, y1, x2, y2 in rectangles:\n events.append((y1, OPEN, x1, x2))\n events.append((y2, CLOSE, x1, x2))\n X.add(x1)\n X.add(x2)\n events.sort()\n X = sorted(X)\n Xi = {x: i for i, x in enumerate(X)}\n\n st = SegmentTreeNode(0, len(X)-1)\n result = 0\n cur_x_sum = 0\n cur_y = events[0][0]\n for y, typ, x1, x2 in events:\n result += cur_x_sum * (y-cur_y)\n cur_x_sum = st.update(X, Xi[x1], Xi[x2], typ)\n cur_y = y\n return result % (10**9+7)\n\n"}} diff --git a/cp/cp-10326.jsonl b/cp/cp-10326.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4bea30756c52337f9b5bae1585d921b118a658f2 --- /dev/null +++ b/cp/cp-10326.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10326", "name": "LeetCode 0851: Loud And Rich"} +{"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: Loud and Rich (Difficulty: Medium)\nTags: Array, Depth-First Search, Graph, Topological Sort\n\nThere is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness.\nYou are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time).\nReturn an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x.\n\nExample 1:\nInput: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]\nOutput: [5,5,2,5,4,5,6,7]\nExplanation: \nanswer[0] = 5.\nPerson 5 has more money than 3, which has more money than 1, which has more money than 0.\nThe only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0.\nanswer[7] = 7.\nAmong all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7.\nThe other answers can be filled out with similar reasoning.\n\nExample 2:\nInput: richer = [], quiet = [0]\nOutput: [0]\n\nConstraints:\n- n == quiet.length\n- 1 <= n <= 500\n- 0 <= quiet[i] < n\n- All the values of quiet are unique.\n- 0 <= richer.length <= n * (n - 1) / 2\n- 0 <= ai, bi < n\n- ai != bi\n- All the pairs of richer are unique.\n- The observations in richer are all logically consistent."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(q + r)\n# Space: O(q + r)\n\n\nclass Solution(object):\n def loudAndRich(self, richer, quiet):\n \"\"\"\n :type richer: List[List[int]]\n :type quiet: List[int]\n :rtype: List[int]\n \"\"\"\n def dfs(graph, quiet, node, result):\n if result[node] is None:\n result[node] = node\n for nei in graph[node]:\n smallest_person = dfs(graph, quiet, nei, result)\n if quiet[smallest_person] < quiet[result[node]]:\n result[node] = smallest_person\n return result[node]\n\n graph = [[] for _ in range(len(quiet))]\n for u, v in richer:\n graph[v].append(u)\n result = [None]*len(quiet)\n return map(lambda x: dfs(graph, quiet, x, result), range(len(quiet)))\n\n"}} diff --git a/cp/cp-10327.jsonl b/cp/cp-10327.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9b76ae1aaa5a9292cedce14d7889988117a14330 --- /dev/null +++ b/cp/cp-10327.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10327", "name": "LeetCode 0852: Peak Index In A Mountain 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: Peak Index in a Mountain Array (Difficulty: Medium)\nTags: Array, Binary Search\n\nYou are given an integer mountain array arr of length n where the values increase to a peak element and then decrease.\nReturn the index of the peak element.\nYour task is to solve it in O(log(n)) time complexity.\n\nExample 1:\nInput: arr = [0,1,0]\nOutput: 1\n\nExample 2:\nInput: arr = [0,2,1,0]\nOutput: 1\n\nExample 3:\nInput: arr = [0,10,5,2]\nOutput: 1\n\nConstraints:\n- 3 <= arr.length <= 10^5\n- 0 <= arr[i] <= 10^6\n- arr is guaranteed to be a mountain array."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nclass Solution(object):\n def peakIndexInMountainArray(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n left, right = 0, len(arr)-1\n while left <= right:\n mid = left + (right-left)//2\n if arr[mid] > arr[mid+1]:\n right = mid-1\n else:\n left = mid+1\n return left\n\n"}} diff --git a/cp/cp-10328.jsonl b/cp/cp-10328.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9e79d952d15ea408fe3c31dac3dd1853f86de9a7 --- /dev/null +++ b/cp/cp-10328.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10328", "name": "LeetCode 0853: Car Fleet"} +{"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: Car Fleet (Difficulty: Medium)\nTags: Array, Stack, Sorting, Monotonic Stack\n\nThere are n cars at given miles away from the starting mile 0, traveling to reach the mile target.\nYou are given two integer arrays position and speed, both of length n, where position[i] is the starting mile of the ith car and speed[i] is the speed of the ith car in miles per hour.\nA car cannot pass another car, but it can catch up and then travel next to it at the speed of the slower car.\nA car fleet is a car or cars driving next to each other. The speed of the car fleet is the minimum speed of any car in the fleet.\nIf a car catches up to a car fleet at the mile target, it will still be considered as part of the car fleet.\nReturn the number of car fleets that will arrive at the destination.\n\nExample 1:\nInput: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]\nOutput: 3\nExplanation:\n\nExample 2:\nInput: target = 10, position = [3], speed = [3]\nOutput: 1\nExplanation:\n\nExample 3:\nInput: target = 100, position = [0,2,4], speed = [4,2,1]\nOutput: 1\nExplanation:\n\nConstraints:\n- n == position.length == speed.length\n- 1 <= n <= 10^5\n- 0 < target <= 10^6\n- 0 <= position[i] < target\n- All the values of position are unique.\n- 0 < speed[i] <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass Solution(object):\n def carFleet(self, target, position, speed):\n \"\"\"\n :type target: int\n :type position: List[int]\n :type speed: List[int]\n :rtype: int\n \"\"\"\n times = [float(target-p)/s for p, s in sorted(zip(position, speed))]\n result, curr = 0, 0\n for t in reversed(times):\n if t > curr:\n result += 1\n curr = t\n return result\n\n"}} diff --git a/cp/cp-10329.jsonl b/cp/cp-10329.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bd3eb37c05c07e981bd983ddafec7d6c00a8006d --- /dev/null +++ b/cp/cp-10329.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10329", "name": "LeetCode 0854: K Similar Strings"} +{"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-Similar Strings (Difficulty: Hard)\nTags: Hash Table, String, Breadth-First Search\n\nStrings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.\nGiven two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.\n\nExample 1:\nInput: s1 = \"ab\", s2 = \"ba\"\nOutput: 1\nExplanation: The two string are 1-similar because we can use one swap to change s1 to s2: \"ab\" --> \"ba\".\n\nExample 2:\nInput: s1 = \"abc\", s2 = \"bca\"\nOutput: 2\nExplanation: The two strings are 2-similar because we can use two swaps to change s1 to s2: \"abc\" --> \"bac\" --> \"bca\".\n\nConstraints:\n- 1 <= s1.length <= 20\n- s2.length == s1.length\n- s1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}.\n- s2 is an anagram of s1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * n!/(c_a!*...*c_z!), n is the length of A, B,\n# c_a...c_z is the count of each alphabet,\n# n = sum(c_a...c_z)\n# Space: O(n * n!/(c_a!*...*c_z!)\n\nimport collections\n\n\nclass Solution(object):\n def kSimilarity(self, A, B):\n \"\"\"\n :type A: str\n :type B: str\n :rtype: int\n \"\"\"\n def neighbors(s, B):\n for i, c in enumerate(s):\n if c != B[i]:\n break\n t = list(s)\n for j in range(i+1, len(s)):\n if t[j] == B[i]:\n t[i], t[j] = t[j], t[i]\n yield \"\".join(t)\n t[j], t[i] = t[i], t[j]\n\n q = collections.deque([A])\n lookup = set()\n result = 0\n while q:\n for _ in range(len(q)):\n s = q.popleft()\n if s == B:\n return result\n for t in neighbors(s, B):\n if t not in lookup:\n lookup.add(t)\n q.append(t)\n result += 1\n\n"}} diff --git a/cp/cp-10330.jsonl b/cp/cp-10330.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f27dbd95f45ed9cf4082ffa9458ca419112f2e9a --- /dev/null +++ b/cp/cp-10330.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10330", "name": "LeetCode 0855: Exam Room"} +{"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: Exam Room (Difficulty: Medium)\nTags: Design, Heap (Priority Queue), Ordered Set\n\nThere is an exam room with n seats in a single row labeled from 0 to n - 1.\nWhen a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0.\nDesign a class that simulates the mentioned exam room.\nImplement the ExamRoom class:\n\nExample 1:\nInput\n[\"ExamRoom\", \"seat\", \"seat\", \"seat\", \"seat\", \"leave\", \"seat\"]\n[[10], [], [], [], [], [4], []]\nOutput\n[null, 0, 9, 4, 2, null, 5]\n\nExplanation\nExamRoom examRoom = new ExamRoom(10);\nexamRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0.\nexamRoom.seat(); // return 9, the student sits at the last seat number 9.\nexamRoom.seat(); // return 4, the student sits at the last seat number 4.\nexamRoom.seat(); // return 2, the student sits at the last seat number 2.\nexamRoom.leave(4);\nexamRoom.seat(); // return 5, the student sits at the last seat number 5.\n\nConstraints:\n- 1 <= n <= 10^9\n- It is guaranteed that there is a student sitting at seat p.\n- At most 104 calls will be made to seat and leave."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: seat: O(logn), amortized\n# leave: O(logn)\n# Space: O(n)\n\nimport heapq\n\n\nclass ExamRoom(object):\n\n def __init__(self, N):\n \"\"\"\n :type N: int\n \"\"\"\n self.__num = N\n self.__seats = {-1: [-1, self.__num], self.__num: [-1, self.__num]}\n self.__max_heap = [(-self.__distance((-1, self.__num)), -1, self.__num)]\n\n def seat(self):\n \"\"\"\n :rtype: int\n \"\"\"\n while self.__max_heap[0][1] not in self.__seats or \\\n self.__max_heap[0][2] not in self.__seats or \\\n self.__seats[self.__max_heap[0][1]][1] != self.__max_heap[0][2] or \\\n self.__seats[self.__max_heap[0][2]][0] != self.__max_heap[0][1]:\n heapq.heappop(self.__max_heap) # lazy deletion\n\n _, left, right = heapq.heappop(self.__max_heap)\n mid = 0 if left == -1 \\\n else self.__num-1 if right == self.__num \\\n else (left+right) // 2\n self.__seats[mid] = [left, right]\n heapq.heappush(self.__max_heap, (-self.__distance((left, mid)), left, mid))\n heapq.heappush(self.__max_heap, (-self.__distance((mid, right)), mid, right))\n self.__seats[left][1] = mid\n self.__seats[right][0] = mid\n return mid\n\n def leave(self, p):\n \"\"\"\n :type p: int\n :rtype: void\n \"\"\"\n left, right = self.__seats[p]\n self.__seats.pop(p)\n self.__seats[left][1] = right\n self.__seats[right][0] = left\n heapq.heappush(self.__max_heap, (-self.__distance((left, right)), left, right))\n \n def __distance(self, segment):\n return segment[1]-segment[0]-1 if segment[0] == -1 or segment[1] == self.__num \\\n else (segment[1]-segment[0]) // 2\n\n"}} diff --git a/cp/cp-10331.jsonl b/cp/cp-10331.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..55f0b2c0a4971e74829e2ba65c92e44d254e3f56 --- /dev/null +++ b/cp/cp-10331.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10331", "name": "LeetCode 0856: Score Of Parentheses"} +{"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: Score of Parentheses (Difficulty: Medium)\nTags: String, Stack\n\nGiven a balanced parentheses string s, return the score of the string.\nThe score of a balanced parentheses string is based on the following rule:\n\nExample 1:\nInput: s = \"()\"\nOutput: 1\n\nExample 2:\nInput: s = \"(())\"\nOutput: 2\n\nExample 3:\nInput: s = \"()()\"\nOutput: 2\n\nConstraints:\n- 2 <= s.length <= 50\n- s consists of only '(' and ')'.\n- s is a balanced parentheses string."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n\nclass Solution(object):\n def scoreOfParentheses(self, S):\n \"\"\"\n :type S: str\n :rtype: int\n \"\"\"\n result, depth = 0, 0\n for i in range(len(S)):\n if S[i] == '(':\n depth += 1\n else:\n depth -= 1\n if S[i-1] == '(':\n result += 2**depth\n return result\n\n\n# Time: O(n)\n# Space: O(h)\nclass Solution2(object):\n def scoreOfParentheses(self, S):\n \"\"\"\n :type S: str\n :rtype: int\n \"\"\"\n stack = [0]\n for c in S:\n if c == '(':\n stack.append(0)\n else:\n last = stack.pop()\n stack[-1] += max(1, 2*last)\n return stack[0]\n\n"}} diff --git a/cp/cp-10332.jsonl b/cp/cp-10332.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..782fe6dd8367a14111bbbe33228eb3f3e24e1f2a --- /dev/null +++ b/cp/cp-10332.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10332", "name": "LeetCode 0857: Minimum Cost To Hire K Workers"} +{"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: Minimum Cost to Hire K Workers (Difficulty: Hard)\nTags: Array, Greedy, Sorting, Heap (Priority Queue)\n\nThere are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker.\nWe want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules:\nGiven the integer k, return the least amount of money needed to form a paid group satisfying the above conditions. Answers within 10-5 of the actual answer will be accepted.\n\nExample 1:\nInput: quality = [10,20,5], wage = [70,50,30], k = 2\nOutput: 105.00000\nExplanation: We pay 70 to 0th worker and 35 to 2nd worker.\n\nExample 2:\nInput: quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3\nOutput: 30.66667\nExplanation: We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately.\n\nConstraints:\n- n == quality.length == wage.length\n- 1 <= k <= n <= 10^4\n- 1 <= quality[i], wage[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space : O(n)\n\nimport itertools\nimport heapq\n\n\nclass Solution(object):\n def mincostToHireWorkers(self, quality, wage, K):\n \"\"\"\n :type quality: List[int]\n :type wage: List[int]\n :type K: int\n :rtype: float\n \"\"\"\n result, qsum = float(\"inf\"), 0\n max_heap = []\n for r, q in sorted([float(w)/q, q] for w, q in itertools.izip(wage, quality)):\n qsum += q\n heapq.heappush(max_heap, -q)\n if len(max_heap) > K:\n qsum -= -heapq.heappop(max_heap)\n if len(max_heap) == K:\n result = min(result, qsum*r)\n return result\n\n"}} diff --git a/cp/cp-10333.jsonl b/cp/cp-10333.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3d20a7d935bd52c76be2c23cbaec7b3a07abc15b --- /dev/null +++ b/cp/cp-10333.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10333", "name": "LeetCode 0858: Mirror Reflection"} +{"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: Mirror Reflection (Difficulty: Medium)\nTags: Math, Geometry, Number Theory\n\nThere is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.\nThe square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.\nGiven the two integers p and q, return the number of the receptor that the ray meets first.\nThe test cases are guaranteed so that the ray will meet a receptor eventually.\n\nExample 1:\nInput: p = 2, q = 1\nOutput: 2\nExplanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.\n\nExample 2:\nInput: p = 3, q = 1\nOutput: 1\n\nConstraints:\n- 1 <= q <= p <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def mirrorReflection(self, p, q):\n \"\"\"\n :type p: int\n :type q: int\n :rtype: int\n \"\"\"\n # explanation commented in the following solution\n return 2 if (p & -p) > (q & -q) else 0 if (p & -p) < (q & -q) else 1\n\n\n# Time: O(log(max(p, q))) = O(1) due to 32-bit integer\n# Space: O(1)\nclass Solution2(object):\n def mirrorReflection(self, p, q):\n \"\"\"\n :type p: int\n :type q: int\n :rtype: int\n \"\"\"\n def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\n lcm = p*q // gcd(p, q)\n # let a = lcm / p, b = lcm / q\n if lcm // p % 2 == 1:\n if lcm // q % 2 == 1:\n return 1 # a is odd, b is odd <=> (p & -p) == (q & -q)\n return 2 # a is odd, b is even <=> (p & -p) > (q & -q)\n return 0 # a is even, b is odd <=> (p & -p) < (q & -q)\n\n"}} diff --git a/cp/cp-10334.jsonl b/cp/cp-10334.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fb9a15408637a32f464cea1f13f9137cfb449522 --- /dev/null +++ b/cp/cp-10334.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10334", "name": "LeetCode 0859: Buddy Strings"} +{"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: Buddy Strings (Difficulty: Easy)\nTags: Hash Table, String\n\nGiven two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.\nSwapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].\n\nExample 1:\nInput: s = \"ab\", goal = \"ba\"\nOutput: true\nExplanation: You can swap s[0] = 'a' and s[1] = 'b' to get \"ba\", which is equal to goal.\n\nExample 2:\nInput: s = \"ab\", goal = \"ab\"\nOutput: false\nExplanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in \"ba\" != goal.\n\nExample 3:\nInput: s = \"aa\", goal = \"aa\"\nOutput: true\nExplanation: You can swap s[0] = 'a' and s[1] = 'a' to get \"aa\", which is equal to goal.\n\nConstraints:\n- 1 <= s.length, goal.length <= 2 * 10^4\n- s and goal consist of lowercase letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def buddyStrings(self, A, B):\n \"\"\"\n :type A: str\n :type B: str\n :rtype: bool\n \"\"\"\n if len(A) != len(B):\n return False\n diff = []\n for a, b in itertools.izip(A, B):\n if a != b:\n diff.append((a, b))\n if len(diff) > 2:\n return False\n return (not diff and len(set(A)) < len(A)) or \\\n (len(diff) == 2 and diff[0] == diff[1][::-1])\n\n"}} diff --git a/cp/cp-10335.jsonl b/cp/cp-10335.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ee85c10149bc8f67f4c056b482607e39f1b797d5 --- /dev/null +++ b/cp/cp-10335.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10335", "name": "LeetCode 0860: Lemonade Change"} +{"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: Lemonade Change (Difficulty: Easy)\nTags: Array, Greedy\n\nAt a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.\nNote that you do not have any change in hand at first.\nGiven an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.\n\nExample 1:\nInput: bills = [5,5,5,10,20]\nOutput: true\nExplanation: \nFrom the first 3 customers, we collect three $5 bills in order.\nFrom the fourth customer, we collect a $10 bill and give back a $5.\nFrom the fifth customer, we give a $10 bill and a $5 bill.\nSince all customers got correct change, we output true.\n\nExample 2:\nInput: bills = [5,5,10,10,20]\nOutput: false\nExplanation: \nFrom the first two customers in order, we collect two $5 bills.\nFor the next two customers in order, we collect a $10 bill and give back a $5 bill.\nFor the last customer, we can not give the change of $15 back because we only have two $10 bills.\nSince not every customer received the correct change, the answer is false.\n\nConstraints:\n- 1 <= bills.length <= 10^5\n- bills[i] is either 5, 10, or 20."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def lemonadeChange(self, bills):\n \"\"\"\n :type bills: List[int]\n :rtype: bool\n \"\"\"\n coins = [20, 10, 5]\n counts = collections.defaultdict(int)\n for bill in bills:\n counts[bill] += 1\n change = bill - coins[-1]\n for coin in coins:\n if change == 0:\n break\n if change >= coin:\n count = min(counts[coin], change//coin)\n counts[coin] -= count\n change -= coin * count\n if change != 0:\n return False\n return True\n\n\nclass Solution2(object):\n def lemonadeChange(self, bills):\n \"\"\"\n :type bills: List[int]\n :rtype: bool\n \"\"\"\n five, ten = 0, 0\n for bill in bills:\n if bill == 5:\n five += 1\n elif bill == 10:\n if not five:\n return False\n five -= 1\n ten += 1\n else:\n if ten and five:\n ten -= 1\n five -= 1\n elif five >= 3:\n five -= 3\n else:\n return False\n return True\n\n"}} diff --git a/cp/cp-10336.jsonl b/cp/cp-10336.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..66f401cb0b4acaae03f42c1544eef72b24a72a13 --- /dev/null +++ b/cp/cp-10336.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10336", "name": "LeetCode 0861: Score After Flipping Matrix"} +{"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: Score After Flipping Matrix (Difficulty: Medium)\nTags: Array, Greedy, Bit Manipulation, Matrix\n\nYou are given an m x n binary matrix grid.\nA move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).\nEvery row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.\nReturn the highest possible score after making any number of moves (including zero moves).\n\nExample 1:\nInput: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]\nOutput: 39\nExplanation: 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39\n\nExample 2:\nInput: grid = [[0]]\nOutput: 1\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 20\n- grid[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(r * c)\n# Space: O(1)\n\n\nclass Solution(object):\n def matrixScore(self, A):\n \"\"\"\n :type A: List[List[int]]\n :rtype: int\n \"\"\"\n R, C = len(A), len(A[0])\n result = 0\n for c in range(C):\n col = 0\n for r in range(R):\n col += A[r][c] ^ A[r][0]\n result += max(col, R-col) * 2**(C-1-c)\n return result\n\n"}} diff --git a/cp/cp-10337.jsonl b/cp/cp-10337.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f4e33264ceb0d927ec4dfe3904ed54846d1f3979 --- /dev/null +++ b/cp/cp-10337.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10337", "name": "LeetCode 0862: Shortest Subarray With Sum At Least K"} +{"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: Shortest Subarray with Sum at Least K (Difficulty: Hard)\nTags: Array, Binary Search, Queue, Sliding Window, Heap (Priority Queue), Prefix Sum, Monotonic Queue\n\nGiven an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.\nA subarray is a contiguous part of an array.\n\nExample 1:\nInput: nums = [1], k = 1\nOutput: 1\n\nExample 2:\nInput: nums = [1,2], k = 4\nOutput: -1\n\nExample 3:\nInput: nums = [2,-1,2], k = 3\nOutput: 3\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- -10^5 <= nums[i] <= 10^5\n- 1 <= k <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def shortestSubarray(self, A, K):\n \"\"\"\n :type A: List[int]\n :type K: int\n :rtype: int\n \"\"\"\n accumulated_sum = [0]*(len(A)+1)\n for i in range(len(A)):\n accumulated_sum[i+1] = accumulated_sum[i]+A[i]\n\n result = float(\"inf\")\n mono_increasing_q = collections.deque()\n for i, curr in enumerate(accumulated_sum):\n while mono_increasing_q and curr <= \\\n accumulated_sum[mono_increasing_q[-1]]:\n mono_increasing_q.pop()\n while mono_increasing_q and \\\n curr-accumulated_sum[mono_increasing_q[0]] >= K:\n result = min(result, i-mono_increasing_q.popleft())\n mono_increasing_q.append(i)\n return result if result != float(\"inf\") else -1\n\n"}} diff --git a/cp/cp-10338.jsonl b/cp/cp-10338.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..48ae1db49fbef1551f0c707934dde12783795cad --- /dev/null +++ b/cp/cp-10338.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10338", "name": "LeetCode 0863: All Nodes Distance K 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: All Nodes Distance K in Binary Tree (Difficulty: Medium)\nTags: Hash Table, Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.\nYou can return the answer in any order.\n\nExample 1:\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2\nOutput: [7,4,1]\nExplanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.\n\nExample 2:\nInput: root = [1], target = 1, k = 3\nOutput: []\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 500].\n- 0 <= Node.val <= 500\n- All the values Node.val are unique.\n- target is the value of one of the nodes in the tree.\n- 0 <= k <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def distanceK(self, root, target, K):\n \"\"\"\n :type root: TreeNode\n :type target: TreeNode\n :type K: int\n :rtype: List[int]\n \"\"\"\n def dfs(parent, child, neighbors):\n if not child:\n return\n if parent:\n neighbors[parent.val].append(child.val)\n neighbors[child.val].append(parent.val)\n dfs(child, child.left, neighbors)\n dfs(child, child.right, neighbors)\n\n neighbors = collections.defaultdict(list)\n dfs(None, root, neighbors)\n bfs = [target.val]\n lookup = set(bfs)\n for _ in range(K):\n bfs = [nei for node in bfs\n for nei in neighbors[node]\n if nei not in lookup]\n lookup |= set(bfs)\n return bfs\n\n"}} diff --git a/cp/cp-10339.jsonl b/cp/cp-10339.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8aca0326a2b623f9dd68118e2f775e54fc0c7bea --- /dev/null +++ b/cp/cp-10339.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10339", "name": "LeetCode 0864: Shortest Path To Get All Keys"} +{"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: Shortest Path to Get All Keys (Difficulty: Hard)\nTags: Array, Bit Manipulation, Breadth-First Search, Matrix\n\nYou are given an m x n grid grid where:\nYou start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.\nIf you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.\nFor some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.\nReturn the lowest number of moves to acquire all keys. If it is impossible, return -1.\n\nExample 1:\nInput: grid = [\"@.a..\",\"###.#\",\"b.A.B\"]\nOutput: 8\nExplanation: Note that the goal is to obtain all the keys not to open all the locks.\n\nExample 2:\nInput: grid = [\"@..aA\",\"..B#.\",\"....b\"]\nOutput: 6\n\nExample 3:\nInput: grid = [\"@Aa\"]\nOutput: -1\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 30\n- grid[i][j] is either an English letter, '.', '#', or '@'.\n- There is exactly one '@' in the grid.\n- The number of keys in the grid is in the range [1, 6].\n- Each key in the grid is unique.\n- Each key in the grid has a matching lock."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(k*r*c + |E|log|V|) = O(k*r*c + (k*|V|)*log|V|)\n# = O(k*r*c + (k*(k*2^k))*log(k*2^k))\n# = O(k*r*c + (k*(k*2^k))*(logk + k*log2))\n# = O(k*r*c + (k*(k*2^k))*k)\n# = O(k*r*c + k^3*2^k)\n# Space: O(|V|) = O(k*2^k)\n\nimport collections\nimport heapq\n\n\nclass Solution(object):\n def shortestPathAllKeys(self, grid):\n \"\"\"\n :type grid: List[str]\n :rtype: int\n \"\"\"\n directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n\n def bfs(grid, source, locations):\n r, c = locations[source]\n lookup = [[False]*(len(grid[0])) for _ in range(len(grid))]\n lookup[r][c] = True\n q = collections.deque([(r, c, 0)])\n dist = {}\n while q:\n r, c, d = q.popleft()\n if source != grid[r][c] != '.':\n dist[grid[r][c]] = d\n continue\n for direction in directions:\n cr, cc = r+direction[0], c+direction[1]\n if not ((0 <= cr < len(grid)) and\n (0 <= cc < len(grid[cr]))):\n continue\n if grid[cr][cc] != '#' and not lookup[cr][cc]:\n lookup[cr][cc] = True\n q.append((cr, cc, d+1))\n return dist\n\n locations = {place: (r, c)\n for r, row in enumerate(grid)\n for c, place in enumerate(row)\n if place not in '.#'}\n dists = {place: bfs(grid, place, locations) for place in locations}\n\n # Dijkstra's algorithm\n min_heap = [(0, '@', 0)]\n best = collections.defaultdict(lambda: collections.defaultdict(\n lambda: float(\"inf\")))\n best['@'][0] = 0\n target_state = 2**sum(place.islower() for place in locations)-1\n while min_heap:\n cur_d, place, state = heapq.heappop(min_heap)\n if best[place][state] < cur_d:\n continue\n if state == target_state:\n return cur_d\n for dest, d in dists[place].iteritems():\n next_state = state\n if dest.islower():\n next_state |= (1 << (ord(dest)-ord('a')))\n elif dest.isupper():\n if not (state & (1 << (ord(dest)-ord('A')))):\n continue\n if cur_d+d < best[dest][next_state]:\n best[dest][next_state] = cur_d+d\n heapq.heappush(min_heap, (cur_d+d, dest, next_state))\n return -1\n\n"}} diff --git a/cp/cp-10340.jsonl b/cp/cp-10340.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..10efe10c6a41bda8a55356bd4d1e8955c3e490d7 --- /dev/null +++ b/cp/cp-10340.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10340", "name": "LeetCode 0865: Smallest Subtree With All The Deepest Nodes"} +{"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: Smallest Subtree with all the Deepest Nodes (Difficulty: Medium)\nTags: Hash Table, Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven the root of a binary tree, the depth of each node is the shortest distance to the root.\nReturn the smallest subtree such that it contains all the deepest nodes in the original tree.\nA node is called the deepest if it has the largest depth possible among any node in the entire tree.\nThe subtree of a node is a tree consisting of that node, plus the set of all descendants of that node.\nNote: This question is the same as 1123: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/\n\nExample 1:\nInput: root = [3,5,1,6,2,0,8,null,null,7,4]\nOutput: [2,7,4]\nExplanation: We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest nodes of the tree.\nNotice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.\n\nExample 2:\nInput: root = [1]\nOutput: [1]\nExplanation: The root is the deepest node in the tree.\n\nExample 3:\nInput: root = [0,1,3,null,2]\nOutput: [2]\nExplanation: The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.\n\nConstraints:\n- The number of nodes in the tree will be in the range [1, 500].\n- 0 <= Node.val <= 500\n- The values of the nodes in the tree are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nimport collections\n\n\nclass Solution(object):\n def subtreeWithAllDeepest(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n Result = collections.namedtuple(\"Result\", (\"node\", \"depth\"))\n\n def dfs(node):\n if not node:\n return Result(None, 0)\n left, right = dfs(node.left), dfs(node.right)\n if left.depth > right.depth:\n return Result(left.node, left.depth+1)\n if left.depth < right.depth:\n return Result(right.node, right.depth+1)\n return Result(node, left.depth+1)\n\n return dfs(root).node\n\n"}} diff --git a/cp/cp-10341.jsonl b/cp/cp-10341.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..659972fb9e551e2f4d911db812672c37c9d08062 --- /dev/null +++ b/cp/cp-10341.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10341", "name": "LeetCode 0866: Prime Palindrome"} +{"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: Prime Palindrome (Difficulty: Medium)\nTags: Math, Number Theory\n\nGiven an integer n, return the smallest prime palindrome greater than or equal to n.\nAn integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number.\nAn integer is a palindrome if it reads the same from left to right as it does from right to left.\nThe test cases are generated so that the answer always exists and is in the range [2, 2 * 10^8].\n\nExample 1:\nInput: n = 6\nOutput: 7\n\nExample 2:\nInput: n = 8\nOutput: 11\n\nExample 3:\nInput: n = 13\nOutput: 101\n\nConstraints:\n- 1 <= n <= 10^8"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^(1/2) * (logn + n^(1/2)))\n# Space: O(logn)\n\n\nclass Solution(object):\n def primePalindrome(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n def is_prime(n):\n if n < 2 or n % 2 == 0:\n return n == 2\n return all(n % d for d in range(3, int(n**.5) + 1, 2))\n\n if 8 <= N <= 11:\n return 11\n for i in range(10**(len(str(N))//2), 10**5):\n j = int(str(i) + str(i)[-2::-1])\n if j >= N and is_prime(j):\n return j\n\n"}} diff --git a/cp/cp-10342.jsonl b/cp/cp-10342.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fd8fafde89260d0860f4b9ca6407663d9f60e791 --- /dev/null +++ b/cp/cp-10342.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10342", "name": "LeetCode 0867: Transpose Matrix"} +{"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: Transpose Matrix (Difficulty: Easy)\nTags: Array, Matrix, Simulation\n\nGiven a 2D integer array matrix, return the transpose of matrix.\nThe transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.\n\nExample 1:\nInput: matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [[1,4,7],[2,5,8],[3,6,9]]\n\nExample 2:\nInput: matrix = [[1,2,3],[4,5,6]]\nOutput: [[1,4],[2,5],[3,6]]\n\nConstraints:\n- m == matrix.length\n- n == matrix[i].length\n- 1 <= m, n <= 1000\n- 1 <= m * n <= 10^5\n- -10^9 <= matrix[i][j] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(r * c)\n# Space: O(1)\n\n\nclass Solution(object):\n def transpose(self, A):\n \"\"\"\n :type A: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n result = [[None] * len(A) for _ in range(len(A[0]))]\n for r, row in enumerate(A):\n for c, val in enumerate(row):\n result[c][r] = val\n return result\n\n\n# Time: O(r * c)\n# Space: O(1)\nclass Solution2(object):\n def transpose(self, A):\n \"\"\"\n :type A: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n return zip(*A)\n\n"}} diff --git a/cp/cp-10343.jsonl b/cp/cp-10343.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6498f8aecca44f155ff9c147c6c3068663a06451 --- /dev/null +++ b/cp/cp-10343.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10343", "name": "LeetCode 0868: Binary Gap"} +{"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: Binary Gap (Difficulty: Easy)\nTags: Bit Manipulation\n\nGiven a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.\nTwo 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in \"1001\" have a distance of 3.\n\nExample 1:\nInput: n = 22\nOutput: 2\nExplanation: 22 in binary is \"10110\".\nThe first adjacent pair of 1's is \"10110\" with a distance of 2.\nThe second adjacent pair of 1's is \"10110\" with a distance of 1.\nThe answer is the largest of these two distances, which is 2.\nNote that \"10110\" is not a valid pair since there is a 1 separating the two 1's underlined.\n\nExample 2:\nInput: n = 8\nOutput: 0\nExplanation: 8 in binary is \"1000\".\nThere are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.\n\nExample 3:\nInput: n = 5\nOutput: 2\nExplanation: 5 in binary is \"101\".\n\nConstraints:\n- 1 <= n <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn) = O(1) due to n is a 32-bit number\n# Space: O(1)\n\nclass Solution(object):\n def binaryGap(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n result = 0\n last = None\n for i in range(32):\n if (N >> i) & 1:\n if last is not None:\n result = max(result, i-last)\n last = i\n return result\n\n"}} diff --git a/cp/cp-10344.jsonl b/cp/cp-10344.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..84e0ba7bfcc1e11322a08d0c25b9bca8d2336e74 --- /dev/null +++ b/cp/cp-10344.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10344", "name": "LeetCode 0869: Reordered Power Of 2"} +{"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: Reordered Power of 2 (Difficulty: Medium)\nTags: Hash Table, Math, Sorting, Counting, Enumeration\n\nYou are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero.\nReturn true if and only if we can do this so that the resulting number is a power of two.\n\nExample 1:\nInput: n = 1\nOutput: true\n\nExample 2:\nInput: n = 10\nOutput: false\n\nConstraints:\n- 1 <= n <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((logn)^2) = O(1) due to n is a 32-bit number\n# Space: O(logn) = O(1)\n\nimport collections\n\n\nclass Solution(object):\n def reorderedPowerOf2(self, N):\n \"\"\"\n :type N: int\n :rtype: bool\n \"\"\"\n count = collections.Counter(str(N))\n return any(count == collections.Counter(str(1 << i))\n for i in range(31))\n\n"}} diff --git a/cp/cp-10345.jsonl b/cp/cp-10345.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f918e86b94ae28ad45c1e4f631bd3fb02fade056 --- /dev/null +++ b/cp/cp-10345.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10345", "name": "LeetCode 0870: Advantage Shuffle"} +{"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: Advantage Shuffle (Difficulty: Medium)\nTags: Array, Two Pointers, Greedy, Sorting\n\nYou are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i].\nReturn any permutation of nums1 that maximizes its advantage with respect to nums2.\n\nExample 1:\nInput: nums1 = [2,7,11,15], nums2 = [1,10,4,11]\nOutput: [2,11,7,15]\n\nExample 2:\nInput: nums1 = [12,24,8,32], nums2 = [13,25,32,11]\nOutput: [24,32,8,12]\n\nConstraints:\n- 1 <= nums1.length <= 10^5\n- nums2.length == nums1.length\n- 0 <= nums1[i], nums2[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass Solution(object):\n def advantageCount(self, A, B):\n \"\"\"\n :type A: List[int]\n :type B: List[int]\n :rtype: List[int]\n \"\"\"\n sortedA = sorted(A)\n sortedB = sorted(B)\n\n candidates = {b: [] for b in B}\n others = []\n j = 0\n for a in sortedA:\n if a > sortedB[j]:\n candidates[sortedB[j]].append(a)\n j += 1\n else:\n others.append(a)\n return [candidates[b].pop() if candidates[b] else others.pop()\n for b in B]\n\n"}} diff --git a/cp/cp-10346.jsonl b/cp/cp-10346.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..29a2b40cfd68d034a251c8927544580502f984c8 --- /dev/null +++ b/cp/cp-10346.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10346", "name": "LeetCode 0871: Minimum Number Of Refueling Stops"} +{"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: Minimum Number of Refueling Stops (Difficulty: Hard)\nTags: Array, Dynamic Programming, Greedy, Heap (Priority Queue)\n\nA car travels from a starting position to a destination which is target miles east of the starting position.\nThere are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas.\nThe car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.\nReturn the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1.\nNote that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.\n\nExample 1:\nInput: target = 1, startFuel = 1, stations = []\nOutput: 0\nExplanation: We can reach the target without refueling.\n\nExample 2:\nInput: target = 100, startFuel = 1, stations = [[10,100]]\nOutput: -1\nExplanation: We can not reach the target (or even the first gas station).\n\nExample 3:\nInput: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]\nOutput: 2\nExplanation: We start with 10 liters of fuel.\nWe drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\nThen, we drive from position 10 to position 60 (expending 50 liters of fuel),\nand refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\nWe made 2 refueling stops along the way, so we return 2.\n\nConstraints:\n- 1 <= target, startFuel <= 10^9\n- 0 <= stations.length <= 500\n- 1 <= positioni < positioni+1 < target\n- 1 <= fueli < 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport heapq\n\n\nclass Solution(object):\n def minRefuelStops(self, target, startFuel, stations):\n \"\"\"\n :type target: int\n :type startFuel: int\n :type stations: List[List[int]]\n :rtype: int\n \"\"\"\n max_heap = []\n stations.append((target, float(\"inf\")))\n\n result = prev = 0\n for location, capacity in stations:\n startFuel -= location - prev\n while max_heap and startFuel < 0:\n startFuel += -heapq.heappop(max_heap)\n result += 1\n if startFuel < 0:\n return -1\n heapq.heappush(max_heap, -capacity)\n prev = location\n\n return result\n\n"}} diff --git a/cp/cp-10347.jsonl b/cp/cp-10347.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..41fd17cd6d81e5a1c29d2ee8811701a69b3c7c3a --- /dev/null +++ b/cp/cp-10347.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10347", "name": "LeetCode 0872: Leaf Similar 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: Leaf-Similar Trees (Difficulty: Easy)\nTags: Tree, Depth-First Search, Binary Tree\n\nConsider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.\nFor example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).\nTwo binary trees are considered leaf-similar if their leaf value sequence is the same.\nReturn true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.\n\nExample 1:\nInput: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]\nOutput: true\n\nExample 2:\nInput: root1 = [1,2,3], root2 = [1,3,2]\nOutput: false\n\nConstraints:\n- The number of nodes in each tree will be in the range [1, 200].\n- Both of the given trees will have values in the range [0, 200]."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nimport itertools\n\n\n# Definition for a binary tree node.\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 leafSimilar(self, root1, root2):\n \"\"\"\n :type root1: TreeNode\n :type root2: TreeNode\n :rtype: bool\n \"\"\"\n def dfs(node):\n if not node:\n return\n if not node.left and not node.right:\n yield node.val\n for i in dfs(node.left):\n yield i\n for i in dfs(node.right):\n yield i\n return all(a == b for a, b in\n itertools.izip_longest(dfs(root1), dfs(root2)))\n\n"}} diff --git a/cp/cp-10348.jsonl b/cp/cp-10348.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bbe9851a8b6491b578aa8398fce755305669dcf4 --- /dev/null +++ b/cp/cp-10348.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10348", "name": "LeetCode 0873: Length Of Longest Fibonacci 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: Length of Longest Fibonacci Subsequence (Difficulty: Medium)\nTags: Array, Hash Table, Dynamic Programming\n\nA sequence x1, x2, ..., xn is Fibonacci-like if:\nGiven a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.\nA subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].\n\nExample 1:\nInput: arr = [1,2,3,4,5,6,7,8]\nOutput: 5\nExplanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].\n\nExample 2:\nInput: arr = [1,3,7,11,12,14,18]\nOutput: 3\nExplanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].\n\nConstraints:\n- 3 <= arr.length <= 1000\n- 1 <= arr[i] < arr[i + 1] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def lenLongestFibSubseq(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n lookup = set(A)\n result = 2\n for i in range(len(A)):\n for j in range(i+1, len(A)):\n x, y, l = A[i], A[j], 2\n while x+y in lookup:\n x, y, l = y, x+y, l+1\n result = max(result, l)\n return result if result > 2 else 0\n\n"}} diff --git a/cp/cp-10349.jsonl b/cp/cp-10349.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2089b63fac2e747cd026209359cfcb9b33e9b41c --- /dev/null +++ b/cp/cp-10349.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10349", "name": "LeetCode 0874: Walking Robot Simulation"} +{"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: Walking Robot Simulation (Difficulty: Medium)\nTags: Array, Hash Table, Simulation\n\nA robot on an infinite XY-plane starts at point (0, 0) facing north. The robot receives an array of integers commands, which represents a sequence of moves that it needs to execute. There are only three possible types of instructions the robot can receive:\nSome of the grid squares are obstacles. The ith obstacle is at grid point obstacles[i] = (xi, yi). If the robot runs into an obstacle, it will stay in its current location (on the block adjacent to the obstacle) and move onto the next command.\nReturn the maximum squared Euclidean distance that the robot reaches at any point in its path (i.e. if the distance is 5, return 25).\nNote:\n\nExample 1:\nInput: commands = [4,-1,3], obstacles = []\nOutput: 25\nExplanation:\nThe robot starts at (0, 0) :\nThe furthest point the robot ever gets from the origin is (3, 4) , which squared is 3 2 + 4 2 = 25 units away.\n\nExample 2:\nInput: commands = [4,-1,4,-2,4], obstacles = [[2,4]]\nOutput: 65\nExplanation:\nThe robot starts at (0, 0) :\nThe furthest point the robot ever gets from the origin is (1, 8) , which squared is 1 2 + 8 2 = 65 units away.\n\nExample 3:\nInput: commands = [6,-1,-1,6], obstacles = [[0,0]]\nOutput: 36\nExplanation:\nThe robot starts at (0, 0) :\nThe furthest point the robot ever gets from the origin is (0, 6) , which squared is 6 2 = 36 units away.\n\nConstraints:\n- 1 <= commands.length <= 10^4\n- commands[i] is either -2, -1, or an integer in the range [1, 9].\n- 0 <= obstacles.length <= 10^4\n- -3 * 10^4 <= xi, yi <= 3 * 10^4\n- The answer is guaranteed to be less than 231."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + k)\n# Space: O(k)\n\nclass Solution(object):\n def robotSim(self, commands, obstacles):\n \"\"\"\n :type commands: List[int]\n :type obstacles: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n x, y, i = 0, 0, 0\n lookup = set(map(tuple, obstacles))\n result = 0\n for cmd in commands:\n if cmd == -2:\n i = (i-1) % 4\n elif cmd == -1:\n i = (i+1) % 4\n else:\n for k in range(cmd):\n if (x+directions[i][0], y+directions[i][1]) not in lookup:\n x += directions[i][0]\n y += directions[i][1]\n result = max(result, x*x + y*y)\n return result\n\n"}} diff --git a/cp/cp-10350.jsonl b/cp/cp-10350.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9cc860c7730f5196d8e147858a509707d9a03a6c --- /dev/null +++ b/cp/cp-10350.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10350", "name": "LeetCode 0875: Koko Eating Bananas"} +{"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: Koko Eating Bananas (Difficulty: Medium)\nTags: Array, Binary Search\n\nKoko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.\nKoko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.\nKoko likes to eat slowly but still wants to finish eating all the bananas before the guards return.\nReturn the minimum integer k such that she can eat all the bananas within h hours.\n\nExample 1:\nInput: piles = [3,6,7,11], h = 8\nOutput: 4\n\nExample 2:\nInput: piles = [30,11,23,4,20], h = 5\nOutput: 30\n\nExample 3:\nInput: piles = [30,11,23,4,20], h = 6\nOutput: 23\n\nConstraints:\n- 1 <= piles.length <= 10^4\n- piles.length <= h <= 10^9\n- 1 <= piles[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogr)\n# Space: O(1)\n\nclass Solution(object):\n def minEatingSpeed(self, piles, H):\n \"\"\"\n :type piles: List[int]\n :type H: int\n :rtype: int\n \"\"\"\n def possible(piles, H, K):\n return sum((pile-1)//K+1 for pile in piles) <= H\n\n left, right = 1, max(piles)\n while left <= right:\n mid = left + (right-left)//2\n if possible(piles, H, mid):\n right = mid-1\n else:\n left = mid+1\n return left\n\n"}} diff --git a/cp/cp-10351.jsonl b/cp/cp-10351.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..47b0b0b470df773793c2fdda51ff63d3acf73dcf --- /dev/null +++ b/cp/cp-10351.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10351", "name": "LeetCode 0876: Middle Of The Linked List"} +{"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: Middle of the Linked List (Difficulty: Easy)\nTags: Linked List, Two Pointers\n\nGiven the head of a singly linked list, return the middle node of the linked list.\nIf there are two middle nodes, return the second middle node.\n\nExample 1:\nInput: head = [1,2,3,4,5]\nOutput: [3,4,5]\nExplanation: The middle node of the list is node 3.\n\nExample 2:\nInput: head = [1,2,3,4,5,6]\nOutput: [4,5,6]\nExplanation: Since the list has two middle nodes with values 3 and 4, we return the second one.\n\nConstraints:\n- The number of nodes in the list is in the range [1, 100].\n- 1 <= Node.val <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def middleNode(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n slow, fast = head, head\n while fast and fast.next:\n slow, fast = slow.next, fast.next.next\n return slow\n\n"}} diff --git a/cp/cp-10352.jsonl b/cp/cp-10352.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fd9b945f2c2f08283e93aa0a64c34916d1173a89 --- /dev/null +++ b/cp/cp-10352.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10352", "name": "LeetCode 0877: Stone Game"} +{"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: Stone Game (Difficulty: Medium)\nTags: Array, Math, Dynamic Programming, Game Theory\n\nAlice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].\nThe objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties.\nAlice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.\nAssuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins.\n\nExample 1:\nInput: piles = [5,3,4,5]\nOutput: true\nExplanation: \nAlice starts first, and can only take the first 5 or the last 5.\nSay she takes the first 5, so that the row becomes [3, 4, 5].\nIf Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.\nIf Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.\nThis demonstrated that taking the first 5 was a winning move for Alice, so we return true.\n\nExample 2:\nInput: piles = [3,7,2,3]\nOutput: true\n\nConstraints:\n- 2 <= piles.length <= 500\n- piles.length is even.\n- 1 <= piles[i] <= 500\n- sum(piles[i]) is odd."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def stoneGame(self, piles):\n \"\"\"\n :type piles: List[int]\n :rtype: bool\n \"\"\"\n if len(piles) % 2 == 0 or len(piles) == 1:\n return True\n\n dp = [0] * len(piles)\n for i in reversed(range(len(piles))):\n dp[i] = piles[i]\n for j in range(i+1, len(piles)):\n dp[j] = max(piles[i] - dp[j], piles[j] - dp[j - 1])\n return dp[-1] >= 0\n\n"}} diff --git a/cp/cp-10353.jsonl b/cp/cp-10353.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7eb2ff1ddd2d54974bff236ee0f23c1f881c4abd --- /dev/null +++ b/cp/cp-10353.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10353", "name": "LeetCode 0878: Nth Magical 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: Nth Magical Number (Difficulty: Hard)\nTags: Math, Binary Search\n\nA positive integer is magical if it is divisible by either a or b.\nGiven the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.\n\nExample 1:\nInput: n = 1, a = 2, b = 3\nOutput: 2\n\nExample 2:\nInput: n = 4, a = 2, b = 3\nOutput: 6\n\nConstraints:\n- 1 <= n <= 10^9\n- 2 <= a, b <= 4 * 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nclass Solution(object):\n def nthMagicalNumber(self, N, A, B):\n \"\"\"\n :type N: int\n :type A: int\n :type B: int\n :rtype: int\n \"\"\"\n def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\n def check(A, B, N, lcm, target):\n return target//A + target//B - target//lcm >= N\n\n lcm = A*B // gcd(A, B)\n left, right = min(A, B), max(A, B)*N\n while left <= right:\n mid = left + (right-left)//2\n if check(A, B, N, lcm, mid):\n right = mid-1\n else:\n left = mid+1\n return left % (10**9 + 7)\n\n"}} diff --git a/cp/cp-10354.jsonl b/cp/cp-10354.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dc973318cffb267c23f9c139c821fab48e1777da --- /dev/null +++ b/cp/cp-10354.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10354", "name": "LeetCode 0879: Profitable Schemes"} +{"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: Profitable Schemes (Difficulty: Hard)\nTags: Array, Dynamic Programming\n\nThere is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime.\nLet's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n.\nReturn the number of schemes that can be chosen. Since the answer may be very large, return it modulo 109 + 7.\n\nExample 1:\nInput: n = 5, minProfit = 3, group = [2,2], profit = [2,3]\nOutput: 2\nExplanation: To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.\nIn total, there are 2 schemes.\n\nExample 2:\nInput: n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]\nOutput: 7\nExplanation: To make a profit of at least 5, the group could commit any crimes, as long as they commit one.\nThere are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).\n\nConstraints:\n- 1 <= n <= 100\n- 0 <= minProfit <= 100\n- 1 <= group.length <= 100\n- 1 <= group[i] <= 100\n- profit.length == group.length\n- 0 <= profit[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * p * g)\n# Space: O(p * g)\n\nimport itertools\n\n\nclass Solution(object):\n def profitableSchemes(self, G, P, group, profit):\n \"\"\"\n :type G: int\n :type P: int\n :type group: List[int]\n :type profit: List[int]\n :rtype: int\n \"\"\"\n dp = [[0 for _ in range(G+1)] for _ in range(P+1)]\n dp[0][0] = 1\n for p, g in itertools.izip(profit, group):\n for i in reversed(range(P+1)):\n for j in reversed(range(G-g+1)):\n dp[min(i+p, P)][j+g] += dp[i][j]\n return sum(dp[P]) % (10**9 + 7)\n\n"}} diff --git a/cp/cp-10355.jsonl b/cp/cp-10355.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..572c8145fcf8891a42f5a25bfce8bb93e7816aad --- /dev/null +++ b/cp/cp-10355.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10355", "name": "LeetCode 0880: Decoded String At Index"} +{"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: Decoded String at Index (Difficulty: Medium)\nTags: String, Stack\n\nYou are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:\nGiven an integer k, return the kth letter (1-indexed) in the decoded string.\n\nExample 1:\nInput: s = \"leet2code3\", k = 10\nOutput: \"o\"\nExplanation: The decoded string is \"leetleetcodeleetleetcodeleetleetcode\".\nThe 10th letter in the string is \"o\".\n\nExample 2:\nInput: s = \"ha22\", k = 5\nOutput: \"h\"\nExplanation: The decoded string is \"hahahaha\".\nThe 5th letter is \"h\".\n\nExample 3:\nInput: s = \"a2345678999999999999999\", k = 1\nOutput: \"a\"\nExplanation: The decoded string is \"a\" repeated 8301530446056247680 times.\nThe 1st letter is \"a\".\n\nConstraints:\n- 2 <= s.length <= 100\n- s consists of lowercase English letters and digits 2 through 9.\n- s starts with a letter.\n- 1 <= k <= 10^9\n- It is guaranteed that k is less than or equal to the length of the decoded string.\n- The decoded string is guaranteed to have less than 263 letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def decodeAtIndex(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n i = 0\n for c in S:\n if c.isdigit():\n i *= int(c)\n else:\n i += 1\n\n for c in reversed(S):\n K %= i\n if K == 0 and c.isalpha():\n return c\n\n if c.isdigit():\n i /= int(c)\n else:\n i -= 1\n\n"}} diff --git a/cp/cp-10356.jsonl b/cp/cp-10356.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..58e12c202ee4f5777c64a5484f277436f907d841 --- /dev/null +++ b/cp/cp-10356.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10356", "name": "LeetCode 0881: Boats To Save People"} +{"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: Boats to Save People (Difficulty: Medium)\nTags: Array, Two Pointers, Greedy, Sorting\n\nYou are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.\nReturn the minimum number of boats to carry every given person.\n\nExample 1:\nInput: people = [1,2], limit = 3\nOutput: 1\nExplanation: 1 boat (1, 2)\n\nExample 2:\nInput: people = [3,2,2,1], limit = 3\nOutput: 3\nExplanation: 3 boats (1, 2), (2) and (3)\n\nExample 3:\nInput: people = [3,5,3,4], limit = 5\nOutput: 4\nExplanation: 4 boats (3), (3), (4), (5)\n\nConstraints:\n- 1 <= people.length <= 5 * 10^4\n- 1 <= people[i] <= limit <= 3 * 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass Solution(object):\n def numRescueBoats(self, people, limit):\n \"\"\"\n :type people: List[int]\n :type limit: int\n :rtype: int\n \"\"\"\n people.sort()\n result = 0\n left, right = 0, len(people)-1\n while left <= right:\n result += 1\n if people[left] + people[right] <= limit:\n left += 1\n right -= 1\n return result\n\n"}} diff --git a/cp/cp-10357.jsonl b/cp/cp-10357.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4afb041a1f58cf0ae18d296dd760cc8b262eb213 --- /dev/null +++ b/cp/cp-10357.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10357", "name": "LeetCode 0882: Reachable Nodes In Subdivided Graph"} +{"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: Reachable Nodes In Subdivided Graph (Difficulty: Hard)\nTags: Graph, Heap (Priority Queue), Shortest Path\n\nYou are given an undirected graph (the \"original graph\") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.\nThe graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge.\nTo subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi].\nIn this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less.\nGiven the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph.\n\nExample 1:\nInput: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3\nOutput: 13\nExplanation: The edge subdivisions are shown in the image above.\nThe nodes that are reachable are highlighted in yellow.\n\nExample 2:\nInput: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4\nOutput: 23\n\nExample 3:\nInput: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5\nOutput: 1\nExplanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.\n\nConstraints:\n- 0 <= edges.length <= min(n * (n - 1) / 2, 104)\n- edges[i].length == 3\n- 0 <= ui < vi < n\n- There are no multiple edges in the graph.\n- 0 <= cnti <= 10^4\n- 0 <= maxMoves <= 10^9\n- 1 <= n <= 3000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|),\n# if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|)\n# Space: O(|E| + |V|) = O(|E|)\n\nimport collections\nimport heapq\n\nclass Solution(object):\n def reachableNodes(self, edges, M, N):\n \"\"\"\n :type edges: List[List[int]]\n :type M: int\n :type N: int\n :rtype: int\n \"\"\"\n adj = [[] for _ in range(N)]\n for u, v, w in edges:\n adj[u].append((v, w))\n adj[v].append((u, w))\n\n min_heap = [(0, 0)]\n best = collections.defaultdict(lambda: float(\"inf\"))\n best[0] = 0\n count = collections.defaultdict(lambda: collections.defaultdict(int))\n result = 0\n while min_heap:\n curr_total, u = heapq.heappop(min_heap) # O(|V|*log|V|) in total\n if best[u] < curr_total:\n continue\n result += 1\n for v, w in adj[u]:\n count[u][v] = min(w, M-curr_total)\n next_total = curr_total+w+1\n if next_total <= M and next_total < best[v]:\n best[v] = next_total\n heapq.heappush(min_heap, (next_total, v)) # binary heap O(|E|*log|V|) in total\n # Fibonacci heap O(|E|) in total\n for u, v, w in edges:\n result += min(w, count[u][v]+count[v][u])\n return result\n\n"}} diff --git a/cp/cp-10358.jsonl b/cp/cp-10358.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b59abfe049f1f673a5045e161b5dea6e0df7edeb --- /dev/null +++ b/cp/cp-10358.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10358", "name": "LeetCode 0883: Projection Area Of 3D Shapes"} +{"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: Projection Area of 3D Shapes (Difficulty: Easy)\nTags: Array, Math, Geometry, Matrix\n\nYou are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes.\nEach value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j).\nWe view the projection of these cubes onto the xy, yz, and zx planes.\nA projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the \"shadow\" when looking at the cubes from the top, the front, and the side.\nReturn the total area of all three projections.\n\nExample 1:\nInput: grid = [[1,2],[3,4]]\nOutput: 17\nExplanation: Here are the three projections (\"shadows\") of the shape made with each axis-aligned plane.\n\nExample 2:\nInput: grid = [[2]]\nOutput: 5\n\nExample 3:\nInput: grid = [[1,0],[0,2]]\nOutput: 8\n\nConstraints:\n- n == grid.length == grid[i].length\n- 1 <= n <= 50\n- 0 <= grid[i][j] <= 50"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(1)\n\nclass Solution(object):\n def projectionArea(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n result = 0\n for i in range(len(grid)):\n max_row, max_col = 0, 0\n for j in range(len(grid)):\n if grid[i][j]:\n result += 1\n max_row = max(max_row, grid[i][j])\n max_col = max(max_col, grid[j][i])\n result += max_row + max_col\n return result\n\n"}} diff --git a/cp/cp-10359.jsonl b/cp/cp-10359.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..23561c3be33dd12302cd06156af3568eb680f9b3 --- /dev/null +++ b/cp/cp-10359.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10359", "name": "LeetCode 0884: Uncommon Words From Two Sentences"} +{"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: Uncommon Words from Two Sentences (Difficulty: Easy)\nTags: Hash Table, String, Counting\n\nA sentence is a string of single-space separated words where each word consists only of lowercase letters.\nA word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.\nGiven two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.\n\nExample 1:\nInput: s1 = \"this apple is sweet\", s2 = \"this apple is sour\"\nOutput: [\"sweet\",\"sour\"]\nExplanation:\nThe word \"sweet\" appears only in s1 , while the word \"sour\" appears only in s2 .\n\nExample 2:\nInput: s1 = \"apple apple\", s2 = \"banana\"\nOutput: [\"banana\"]\n\nConstraints:\n- 1 <= s1.length, s2.length <= 200\n- s1 and s2 consist of lowercase English letters and spaces.\n- s1 and s2 do not have leading or trailing spaces.\n- All the words in s1 and s2 are separated by a single space."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n)\n# Space: O(m + n)\n\nimport collections\n\n \nclass Solution(object):\n def uncommonFromSentences(self, A, B):\n \"\"\"\n :type A: str\n :type B: str\n :rtype: List[str]\n \"\"\"\n count = collections.Counter(A.split())\n count += collections.Counter(B.split())\n return [word for word in count if count[word] == 1]\n\n"}} diff --git a/cp/cp-10360.jsonl b/cp/cp-10360.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f4174bce573a43016976c78aa8b133897b9cd6d8 --- /dev/null +++ b/cp/cp-10360.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10360", "name": "LeetCode 0885: Spiral Matrix 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: Spiral Matrix III (Difficulty: Medium)\nTags: Array, Matrix, Simulation\n\nYou start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.\nYou will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.\nReturn an array of coordinates representing the positions of the grid in the order you visited them.\n\nExample 1:\nInput: rows = 1, cols = 4, rStart = 0, cStart = 0\nOutput: [[0,0],[0,1],[0,2],[0,3]]\n\nExample 2:\nInput: rows = 5, cols = 6, rStart = 1, cStart = 4\nOutput: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]\n\nConstraints:\n- 1 <= rows, cols <= 100\n- 0 <= rStart < rows\n- 0 <= cStart < cols"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(max(m, n)^2)\n# Space: O(1)\n\nclass Solution(object):\n def spiralMatrixIII(self, R, C, r0, c0):\n \"\"\"\n :type R: int\n :type C: int\n :type r0: int\n :type c0: int\n :rtype: List[List[int]]\n \"\"\"\n r, c = r0, c0\n result = [[r, c]]\n x, y, n, i = 0, 1, 0, 0\n while len(result) < R*C:\n r, c, i = r+x, c+y, i+1\n if 0 <= r < R and 0 <= c < C:\n result.append([r, c])\n if i == n//2+1:\n x, y, n, i = y, -x, n+1, 0\n return result\n\n"}} diff --git a/cp/cp-10361.jsonl b/cp/cp-10361.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0d1c7514f2d96e9e7d124a8546b533f374efe059 --- /dev/null +++ b/cp/cp-10361.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10361", "name": "LeetCode 0886: Possible Bipartition"} +{"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: Possible Bipartition (Difficulty: Medium)\nTags: Depth-First Search, Breadth-First Search, Union Find, Graph\n\nWe want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.\nGiven the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.\n\nExample 1:\nInput: n = 4, dislikes = [[1,2],[1,3],[2,4]]\nOutput: true\nExplanation: The first group has [1,4], and the second group has [2,3].\n\nExample 2:\nInput: n = 3, dislikes = [[1,2],[1,3],[2,3]]\nOutput: false\nExplanation: We need at least 3 groups to divide them. We cannot put them in two groups.\n\nConstraints:\n- 1 <= n <= 2000\n- 0 <= dislikes.length <= 10^4\n- dislikes[i].length == 2\n- 1 <= ai < bi <= n\n- All the pairs of dislikes are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(|V| + |E|)\n# Space: O(|V| + |E|)\n\nimport collections\n\n\nclass Solution(object):\n def possibleBipartition(self, N, dislikes):\n \"\"\"\n :type N: int\n :type dislikes: List[List[int]]\n :rtype: bool\n \"\"\"\n adj = [[] for _ in range(N)]\n for u, v in dislikes:\n adj[u-1].append(v-1)\n adj[v-1].append(u-1)\n\n color = [0]*N\n color[0] = 1\n q = collections.deque([0])\n while q:\n cur = q.popleft()\n for nei in adj[cur]:\n if color[nei] == color[cur]:\n return False\n elif color[nei] == -color[cur]:\n continue\n color[nei] = -color[cur]\n q.append(nei)\n return True\n \n\n"}} diff --git a/cp/cp-10362.jsonl b/cp/cp-10362.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..66af21df4d8e09c95b0d280d6e854a9e38930b69 --- /dev/null +++ b/cp/cp-10362.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10362", "name": "LeetCode 0887: Super Egg Drop"} +{"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: Super Egg Drop (Difficulty: Hard)\nTags: Math, Binary Search, Dynamic Programming\n\nYou are given k identical eggs and you have access to a building with n floors labeled from 1 to n.\nYou know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.\nEach move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.\nReturn the minimum number of moves that you need to determine with certainty what the value of f is.\n\nExample 1:\nInput: k = 1, n = 2\nOutput: 2\nExplanation: \nDrop the egg from floor 1. If it breaks, we know that f = 0.\nOtherwise, drop the egg from floor 2. If it breaks, we know that f = 1.\nIf it does not break, then we know f = 2.\nHence, we need at minimum 2 moves to determine with certainty what the value of f is.\n\nExample 2:\nInput: k = 2, n = 6\nOutput: 3\n\nExample 3:\nInput: k = 3, n = 14\nOutput: 4\n\nConstraints:\n- 1 <= k <= 100\n- 1 <= n <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(klogn)\n# Space: O(1)\n\nclass Solution(object):\n def superEggDrop(self, K, N):\n \"\"\"\n :type K: int\n :type N: int\n :rtype: int\n \"\"\"\n def check(n, K, N):\n # let f(n, K) be the max number of floors could be solved by n moves and K eggs,\n # we want to do binary search to find min of n, s.t. f(n, K) >= N,\n # if we use one move to drop egg with X floors\n # 1. if it breaks, we can search new X in the range [X-f(n-1, K-1), X-1]\n # 2. if it doesn't break, we can search new X in the range [X+1, X+f(n-1, K)]\n # => f(n, K) = (X+f(n-1, K))-(X-f(n-1, K-1))+1 = f(n-1, K)+f(n-1, K-1)+1\n # => (1) f(n, K) = f(n-1, K) +1+f(n-1, K-1)\n # (2) f(n, K-1) = f(n-1, K-1)+1+f(n-1, K-2)\n # let g(n, K) = f(n, K)-f(n, K-1), and we subtract (1) by (2)\n # => g(n, K) = g(n-1, K)+g(n-1, K-1), obviously, it is binomial coefficient\n # => C(n, K) = g(n, K) = f(n, K)-f(n, K-1),\n # which also implies if we have one more egg with n moves and x-1 eggs, we can have more C(n, x) floors solvable\n # => f(n, K) = C(n, K)+f(n, K-1) = C(n, K) + C(n, K-1) + ... + C(n, 1) + f(n, 0) = sum(C(n, k) for k in [1, K])\n # => all we have to do is to check sum(C(n, k) for k in [1, K]) >= N,\n # if true, there must exist a 1-to-1 mapping from each F in [1, N] to each success and failure sequence of every C(n, k) combinations for k in [1, K]\n total, c = 0, 1\n for k in range(1, K+1):\n c *= n-k+1\n c //= k\n total += c\n if total >= N:\n return True\n return False\n\n left, right = 1, N\n while left <= right:\n mid = left + (right-left)//2\n if check(mid, K, N):\n right = mid-1\n else:\n left = mid+1\n return left\n\n"}} diff --git a/cp/cp-10363.jsonl b/cp/cp-10363.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd196727c9ee1f96d7bb3469be475218711f7fdf --- /dev/null +++ b/cp/cp-10363.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10363", "name": "LeetCode 0888: Fair Candy 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: Fair Candy Swap (Difficulty: Easy)\nTags: Array, Hash Table, Binary Search, Sorting\n\nAlice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has.\nSince they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have.\nReturn an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.\n\nExample 1:\nInput: aliceSizes = [1,1], bobSizes = [2,2]\nOutput: [1,2]\n\nExample 2:\nInput: aliceSizes = [1,2], bobSizes = [2,3]\nOutput: [1,2]\n\nExample 3:\nInput: aliceSizes = [2], bobSizes = [1,3]\nOutput: [2,3]\n\nConstraints:\n- 1 <= aliceSizes.length, bobSizes.length <= 10^4\n- 1 <= aliceSizes[i], bobSizes[j] <= 10^5\n- Alice and Bob have a different total number of candies.\n- There will be at least one valid answer for the given input."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n)\n# Space: O(m + n)\n\nclass Solution(object):\n def fairCandySwap(self, A, B):\n \"\"\"\n :type A: List[int]\n :type B: List[int]\n :rtype: List[int]\n \"\"\"\n diff = (sum(A)-sum(B))//2\n setA = set(A)\n for b in set(B):\n if diff+b in setA:\n return [diff+b, b]\n return []\n\n"}} diff --git a/cp/cp-10364.jsonl b/cp/cp-10364.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9b147cf2e56b185a5bcb5c812a687cb9e0011d85 --- /dev/null +++ b/cp/cp-10364.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10364", "name": "LeetCode 0889: Construct Binary Tree From Preorder And Postorder Traversal"} +{"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 Binary Tree from Preorder and Postorder Traversal (Difficulty: Medium)\nTags: Array, Hash Table, Divide and Conquer, Tree, Binary Tree\n\nGiven two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.\nIf there exist multiple answers, you can return any of them.\n\nExample 1:\nInput: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]\nOutput: [1,2,3,4,5,6,7]\n\nExample 2:\nInput: preorder = [1], postorder = [1]\nOutput: [1]\n\nConstraints:\n- 1 <= preorder.length <= 30\n- 1 <= preorder[i] <= preorder.length\n- All the values of preorder are unique.\n- postorder.length == preorder.length\n- 1 <= postorder[i] <= postorder.length\n- All the values of postorder are unique.\n- It is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree."}} +{"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 constructFromPrePost(self, pre, post):\n \"\"\"\n :type pre: List[int]\n :type post: List[int]\n :rtype: TreeNode\n \"\"\"\n stack = [TreeNode(pre[0])]\n j = 0\n for i in range(1, len(pre)):\n node = TreeNode(pre[i])\n while stack[-1].val == post[j]:\n stack.pop()\n j += 1\n if not stack[-1].left:\n stack[-1].left = node\n else:\n stack[-1].right = node\n stack.append(node)\n return stack[0]\n\n\n# Time: O(n)\n# Space: O(n)\nclass Solution2(object):\n def constructFromPrePost(self, pre, post):\n \"\"\"\n :type pre: List[int]\n :type post: List[int]\n :rtype: TreeNode\n \"\"\"\n def constructFromPrePostHelper(pre, pre_s, pre_e, post, post_s, post_e, post_entry_idx_map):\n if pre_s >= pre_e or post_s >= post_e:\n return None\n node = TreeNode(pre[pre_s])\n if pre_e-pre_s > 1:\n left_tree_size = post_entry_idx_map[pre[pre_s+1]]-post_s+1\n node.left = constructFromPrePostHelper(pre, pre_s+1, pre_s+1+left_tree_size, \n post, post_s, post_s+left_tree_size,\n post_entry_idx_map)\n node.right = constructFromPrePostHelper(pre, pre_s+1+left_tree_size, pre_e,\n post, post_s+left_tree_size, post_e-1,\n post_entry_idx_map)\n return node\n\n post_entry_idx_map = {}\n for i, val in enumerate(post):\n post_entry_idx_map[val] = i\n return constructFromPrePostHelper(pre, 0, len(pre), post, 0, len(post), post_entry_idx_map)\n\n"}} diff --git a/cp/cp-10365.jsonl b/cp/cp-10365.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..80efc19878e3e132eaa17b2d2b5c3bc89a364792 --- /dev/null +++ b/cp/cp-10365.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10365", "name": "LeetCode 0890: Find And Replace Pattern"} +{"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 and Replace Pattern (Difficulty: Medium)\nTags: Array, Hash Table, String\n\nGiven a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.\nA word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.\nRecall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.\n\nExample 1:\nInput: words = [\"abc\",\"deq\",\"mee\",\"aqq\",\"dkd\",\"ccc\"], pattern = \"abb\"\nOutput: [\"mee\",\"aqq\"]\nExplanation: \"mee\" matches the pattern because there is a permutation {a -> m, b -> e, ...}. \n\"ccc\" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.\n\nExample 2:\nInput: words = [\"a\",\"b\",\"c\"], pattern = \"a\"\nOutput: [\"a\",\"b\",\"c\"]\n\nConstraints:\n- 1 <= pattern.length <= 20\n- 1 <= words.length <= 50\n- words[i].length == pattern.length\n- pattern and words[i] are lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * l)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def findAndReplacePattern(self, words, pattern):\n \"\"\"\n :type words: List[str]\n :type pattern: str\n :rtype: List[str]\n \"\"\"\n def match(word):\n lookup = {}\n for x, y in itertools.izip(pattern, word):\n if lookup.setdefault(x, y) != y:\n return False\n return len(set(lookup.values())) == len(lookup.values())\n\n return filter(match, words)\n\n"}} diff --git a/cp/cp-10366.jsonl b/cp/cp-10366.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..db4569042265e7f9ae98ce49de4348a8fef9dfc4 --- /dev/null +++ b/cp/cp-10366.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10366", "name": "LeetCode 0891: Sum Of Subsequence Widths"} +{"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 Subsequence Widths (Difficulty: Hard)\nTags: Array, Math, Sorting\n\nThe width of a sequence is the difference between the maximum and minimum elements in the sequence.\nGiven an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7.\nA subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].\n\nExample 1:\nInput: nums = [2,1,3]\nOutput: 6\nExplanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\nThe corresponding widths are 0, 0, 0, 1, 1, 2, 2.\nThe sum of these widths is 6.\n\nExample 2:\nInput: nums = [2]\nOutput: 0\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Spce: O(1)\n\nclass Solution(object):\n def sumSubseqWidths(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n M = 10**9+7\n # sum(A[i] * (2^i - 2^(len(A)-1-i))), i = 0..len(A)-1\n # <=>\n # sum(((A[i] - A[len(A)-1-i]) * 2^i), i = 0..len(A)-1\n result, c = 0, 1\n A.sort()\n for i in range(len(A)):\n result = (result + (A[i]-A[len(A)-1-i])*c % M) % M\n c = (c<<1) % M\n return result\n\n"}} diff --git a/cp/cp-10367.jsonl b/cp/cp-10367.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ebc65d4c61110f4375fdcbfcff5ff94dc7fd52c0 --- /dev/null +++ b/cp/cp-10367.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10367", "name": "LeetCode 0892: Surface Area Of 3D Shapes"} +{"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: Surface Area of 3D Shapes (Difficulty: Easy)\nTags: Array, Math, Geometry, Matrix\n\nYou are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j).\nAfter placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes.\nReturn the total surface area of the resulting shapes.\nNote: The bottom face of each shape counts toward its surface area.\n\nExample 1:\nInput: grid = [[1,2],[3,4]]\nOutput: 34\n\nExample 2:\nInput: grid = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: 32\n\nExample 3:\nInput: grid = [[2,2,2],[2,1,2],[2,2,2]]\nOutput: 46\n\nConstraints:\n- n == grid.length == grid[i].length\n- 1 <= n <= 50\n- 0 <= grid[i][j] <= 50"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(1)\n\nclass Solution(object):\n def surfaceArea(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n result = 0\n for i in range(len(grid)):\n for j in range(len(grid)):\n if grid[i][j]:\n result += 2 + grid[i][j]*4\n if i:\n result -= min(grid[i][j], grid[i-1][j])*2\n if j:\n result -= min(grid[i][j], grid[i][j-1])*2\n return result\n\n"}} diff --git a/cp/cp-10368.jsonl b/cp/cp-10368.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c2ddf79efcf96cf571b7a7592f680c62276b4077 --- /dev/null +++ b/cp/cp-10368.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10368", "name": "LeetCode 0893: Groups Of Special Equivalent Strings"} +{"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: Groups of Special-Equivalent Strings (Difficulty: Medium)\nTags: Array, Hash Table, String, Sorting\n\nYou are given an array of strings of the same length words.\nIn one move, you can swap any two even indexed characters or any two odd indexed characters of a string words[i].\nTwo strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j].\nA group of special-equivalent strings from words is a non-empty subset of words such that:\nReturn the number of groups of special-equivalent strings from words.\n\nExample 1:\nInput: words = [\"abcd\",\"cdab\",\"cbad\",\"xyzz\",\"zzxy\",\"zzyx\"]\nOutput: 3\nExplanation: \nOne group is [\"abcd\", \"cdab\", \"cbad\"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these.\nThe other two groups are [\"xyzz\", \"zzxy\"] and [\"zzyx\"].\nNote that in particular, \"zzxy\" is not special equivalent to \"zzyx\".\n\nExample 2:\nInput: words = [\"abc\",\"acb\",\"bac\",\"bca\",\"cab\",\"cba\"]\nOutput: 3\n\nConstraints:\n- 1 <= words.length <= 1000\n- 1 <= words[i].length <= 20\n- words[i] consist of lowercase English letters.\n- All the strings are of the same length."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * l)\n# Space: O(n)\n\nclass Solution(object):\n def numSpecialEquivGroups(self, A):\n \"\"\"\n :type A: List[str]\n :rtype: int\n \"\"\"\n def count(word):\n result = [0]*52\n for i, letter in enumerate(word):\n result[ord(letter)-ord('a') + 26*(i%2)] += 1\n return tuple(result)\n\n return len({count(word) for word in A})\n\n"}} diff --git a/cp/cp-10369.jsonl b/cp/cp-10369.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b6bd97a3f46dfdbd3b567ca297780b64167b69c8 --- /dev/null +++ b/cp/cp-10369.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10369", "name": "LeetCode 0894: All Possible Full 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: All Possible Full Binary Trees (Difficulty: Medium)\nTags: Dynamic Programming, Tree, Recursion, Memoization, Binary Tree\n\nGiven an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0.\nEach element of the answer is the root node of one possible tree. You may return the final list of trees in any order.\nA full binary tree is a binary tree where each node has exactly 0 or 2 children.\n\nExample 1:\nInput: n = 7\nOutput: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]\n\nExample 2:\nInput: n = 3\nOutput: [[0,0,0]]\n\nConstraints:\n- 1 <= n <= 20"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * 4^n / n^(3/2)) ~= sum of Catalan numbers from 1 .. N\n# Space: O(n * 4^n / n^(3/2)) ~= sum of Catalan numbers from 1 .. 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 __init__(self):\n self.__memo = {1: [TreeNode(0)]}\n \n def allPossibleFBT(self, N):\n \"\"\"\n :type N: int\n :rtype: List[TreeNode]\n \"\"\"\n if N % 2 == 0:\n return []\n\n if N not in self.__memo:\n result = []\n for i in range(N):\n for left in self.allPossibleFBT(i):\n for right in self.allPossibleFBT(N-1-i):\n node = TreeNode(0)\n node.left = left\n node.right = right\n result.append(node)\n self.__memo[N] = result\n\n return self.__memo[N]\n \n\n"}} diff --git a/cp/cp-10370.jsonl b/cp/cp-10370.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3be240ee63416f3c40a8860a9b0e0209f3668eee --- /dev/null +++ b/cp/cp-10370.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10370", "name": "LeetCode 0895: Maximum Frequency Stack"} +{"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 Frequency Stack (Difficulty: Hard)\nTags: Hash Table, Stack, Design, Ordered Set\n\nDesign a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.\nImplement the FreqStack class:\n\nExample 1:\nInput\n[\"FreqStack\", \"push\", \"push\", \"push\", \"push\", \"push\", \"push\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[], [5], [7], [5], [7], [4], [5], [], [], [], []]\nOutput\n[null, null, null, null, null, null, null, 5, 7, 5, 4]\n\nExplanation\nFreqStack freqStack = new FreqStack();\nfreqStack.push(5); // The stack is [5]\nfreqStack.push(7); // The stack is [5,7]\nfreqStack.push(5); // The stack is [5,7,5]\nfreqStack.push(7); // The stack is [5,7,5,7]\nfreqStack.push(4); // The stack is [5,7,5,7,4]\nfreqStack.push(5); // The stack is [5,7,5,7,4,5]\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].\nfreqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4].\nfreqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].\n\nConstraints:\n- 0 <= val <= 10^9\n- At most 2 * 10^4 calls will be made to push and pop.\n- It is guaranteed that there will be at least one element in the stack before calling pop."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(n)\n\nimport collections\n\n\nclass FreqStack(object):\n\n def __init__(self):\n self.__freq = collections.Counter()\n self.__group = collections.defaultdict(list)\n self.__maxfreq = 0\n\n def push(self, x):\n \"\"\"\n :type x: int\n :rtype: void\n \"\"\"\n self.__freq[x] += 1\n if self.__freq[x] > self.__maxfreq:\n self.__maxfreq = self.__freq[x]\n self.__group[self.__freq[x]].append(x) \n\n def pop(self):\n \"\"\"\n :rtype: int\n \"\"\"\n x = self.__group[self.__maxfreq].pop()\n if not self.__group[self.__maxfreq]:\n self.__group.pop(self.__maxfreq)\n self.__maxfreq -= 1\n self.__freq[x] -= 1\n if not self.__freq[x]:\n self.__freq.pop(x)\n return x\n\n\n\n"}} diff --git a/cp/cp-10371.jsonl b/cp/cp-10371.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fb273856b0638dded303807e7719df05d37bb7f7 --- /dev/null +++ b/cp/cp-10371.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10371", "name": "LeetCode 0896: Monotonic 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: Monotonic Array (Difficulty: Easy)\nTags: Array\n\nAn array is monotonic if it is either monotone increasing or monotone decreasing.\nAn array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].\nGiven an integer array nums, return true if the given array is monotonic, or false otherwise.\n\nExample 1:\nInput: nums = [1,2,2,3]\nOutput: true\n\nExample 2:\nInput: nums = [6,5,4,4]\nOutput: true\n\nExample 3:\nInput: nums = [1,3,2]\nOutput: false\n\nConstraints:\n- 1 <= nums.length <= 10^5\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 isMonotonic(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: bool\n \"\"\"\n inc, dec = False, False\n for i in range(len(A)-1):\n if A[i] < A[i+1]:\n inc = True\n elif A[i] > A[i+1]:\n dec = True\n return not inc or not dec\n\n"}} diff --git a/cp/cp-10372.jsonl b/cp/cp-10372.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..46b20844661e02262819f8ebf0bf3b9ff5f73442 --- /dev/null +++ b/cp/cp-10372.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10372", "name": "LeetCode 0897: Increasing Order 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: Increasing Order Search Tree (Difficulty: Easy)\nTags: Stack, Tree, Depth-First Search, Binary Search Tree, Binary Tree\n\nGiven the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.\n\nExample 1:\nInput: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]\nOutput: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]\n\nExample 2:\nInput: root = [5,1,7]\nOutput: [1,null,5,null,7]\n\nConstraints:\n- The number of nodes in the given tree will be in the range [1, 100].\n- 0 <= Node.val <= 1000"}} +{"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 increasingBST(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n def increasingBSTHelper(root, tail):\n if not root:\n return tail\n result = increasingBSTHelper(root.left, root)\n root.left = None\n root.right = increasingBSTHelper(root.right, tail)\n return result\n return increasingBSTHelper(root, None)\n\n"}} diff --git a/cp/cp-10373.jsonl b/cp/cp-10373.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..131f3d8ac24dd27ef630cc40c864e6b89cad9d85 --- /dev/null +++ b/cp/cp-10373.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10373", "name": "LeetCode 0898: Bitwise Ors Of Subarrays"} +{"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: Bitwise ORs of Subarrays (Difficulty: Medium)\nTags: Array, Dynamic Programming, Bit Manipulation\n\nGiven an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr.\nThe bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer.\nA subarray is a contiguous non-empty sequence of elements within an array.\n\nExample 1:\nInput: arr = [0]\nOutput: 1\nExplanation: There is only one possible result: 0.\n\nExample 2:\nInput: arr = [1,1,2]\nOutput: 3\nExplanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].\nThese yield the results 1, 1, 2, 1, 3, 3.\nThere are 3 unique values, so the answer is 3.\n\nExample 3:\nInput: arr = [1,2,4]\nOutput: 6\nExplanation: The possible results are 1, 2, 3, 4, 6, and 7.\n\nConstraints:\n- 1 <= arr.length <= 5 * 10^4\n- 0 <= arr[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(32 * n)\n# Space: O(1)\n\nclass Solution(object):\n def subarrayBitwiseORs(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n result, curr = set(), {0}\n for i in A:\n curr = {i} | {i | j for j in curr}\n result |= curr\n return len(result)\n\n"}} diff --git a/cp/cp-10375.jsonl b/cp/cp-10375.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4f93b4f797c6efcaeeedbbc2efe5d46dd2951c58 --- /dev/null +++ b/cp/cp-10375.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10375", "name": "LeetCode 0900: Rle Iterator"} +{"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: RLE Iterator (Difficulty: Medium)\nTags: Array, Design, Counting, Iterator\n\nWe can use run-length encoding (i.e., RLE) to encode a sequence of integers. In a run-length encoded array of even length encoding (0-indexed), for all even i, encoding[i] tells us the number of times that the non-negative integer value encoding[i + 1] is repeated in the sequence.\nGiven a run-length encoded array, design an iterator that iterates through it.\nImplement the RLEIterator class:\n\nExample 1:\nInput\n[\"RLEIterator\", \"next\", \"next\", \"next\", \"next\"]\n[[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]]\nOutput\n[null, 8, 8, 5, -1]\n\nExplanation\nRLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5].\nrLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5].\nrLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,\nbut the second term did not exist. Since the last term exhausted does not exist, we return -1.\n\nConstraints:\n- 2 <= encoding.length <= 1000\n- encoding.length is even.\n- 0 <= encoding[i] <= 10^9\n- 1 <= n <= 10^9\n- At most 1000 calls will be made to next."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass RLEIterator(object):\n\n def __init__(self, A):\n \"\"\"\n :type A: List[int]\n \"\"\"\n self.__A = A\n self.__i = 0\n self.__cnt = 0\n\n def next(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n while self.__i < len(self.__A):\n if n > self.__A[self.__i] - self.__cnt:\n n -= self.__A[self.__i] - self.__cnt\n self.__cnt = 0\n self.__i += 2\n else:\n self.__cnt += n\n return self.__A[self.__i+1]\n return -1\n\n\n\n"}} diff --git a/cp/cp-10376.jsonl b/cp/cp-10376.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..195102d905d7ed8030ba07c15694f6c17768b017 --- /dev/null +++ b/cp/cp-10376.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10376", "name": "LeetCode 0901: Online Stock Span"} +{"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: Online Stock Span (Difficulty: Medium)\nTags: Stack, Design, Monotonic Stack, Data Stream\n\nDesign an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day.\nThe span of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.\nImplement the StockSpanner class:\n\nExample 1:\nInput\n[\"StockSpanner\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\"]\n[[], [100], [80], [60], [70], [60], [75], [85]]\nOutput\n[null, 1, 1, 1, 2, 1, 4, 6]\n\nExplanation\nStockSpanner stockSpanner = new StockSpanner();\nstockSpanner.next(100); // return 1\nstockSpanner.next(80); // return 1\nstockSpanner.next(60); // return 1\nstockSpanner.next(70); // return 2\nstockSpanner.next(60); // return 1\nstockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.\nstockSpanner.next(85); // return 6\n\nConstraints:\n- 1 <= price <= 10^5\n- At most 104 calls will be made to next."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass StockSpanner(object):\n\n def __init__(self):\n self.__s = []\n\n def next(self, price):\n \"\"\"\n :type price: int\n :rtype: int\n \"\"\"\n result = 1\n while self.__s and self.__s[-1][0] <= price:\n result += self.__s.pop()[1]\n self.__s.append([price, result])\n return result\n\n\n\n"}} diff --git a/cp/cp-10377.jsonl b/cp/cp-10377.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3ef42da133b54aa0088b960faed7bef9beaec1bd --- /dev/null +++ b/cp/cp-10377.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10377", "name": "LeetCode 0902: Numbers At Most N Given Digit Set"} +{"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: Numbers At Most N Given Digit Set (Difficulty: Hard)\nTags: Array, Math, String, Binary Search, Dynamic Programming\n\nGiven an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'.\nReturn the number of positive integers that can be generated that are less than or equal to a given integer n.\n\nExample 1:\nInput: digits = [\"1\",\"3\",\"5\",\"7\"], n = 100\nOutput: 20\nExplanation: \nThe 20 numbers that can be written are:\n1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.\n\nExample 2:\nInput: digits = [\"1\",\"4\",\"9\"], n = 1000000000\nOutput: 29523\nExplanation: \nWe can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,\n81 four digit numbers, 243 five digit numbers, 729 six digit numbers,\n2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.\nIn total, this is 29523 integers that can be written using the digits array.\n\nExample 3:\nInput: digits = [\"7\"], n = 8\nOutput: 1\n\nConstraints:\n- 1 <= digits.length <= 9\n- digits[i].length == 1\n- digits[i] is a digit from '1' to '9'.\n- All the values in digits are unique.\n- digits is sorted in non-decreasing order.\n- 1 <= n <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(logn)\n\nclass Solution(object):\n def atMostNGivenDigitSet(self, D, N):\n \"\"\"\n :type D: List[str]\n :type N: int\n :rtype: int\n \"\"\"\n str_N = str(N)\n set_D = set(D)\n result = sum(len(D)**i for i in range(1, len(str_N)))\n i = 0\n while i < len(str_N):\n result += sum(c < str_N[i] for c in D) * (len(D)**(len(str_N)-i-1))\n if str_N[i] not in set_D:\n break\n i += 1\n return result + int(i == len(str_N))\n\n"}} diff --git a/cp/cp-10378.jsonl b/cp/cp-10378.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4947a8577017da32c0532a936fe6daff83c151c5 --- /dev/null +++ b/cp/cp-10378.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10378", "name": "LeetCode 0903: Valid Permutations For Di Sequence"} +{"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 Permutations for DI Sequence (Difficulty: Hard)\nTags: String, Dynamic Programming, Prefix Sum\n\nYou are given a string s of length n where s[i] is either:\nA permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i:\nReturn the number of valid permutations perm. Since the answer may be large, return it modulo 109 + 7.\n\nExample 1:\nInput: s = \"DID\"\nOutput: 5\nExplanation: The 5 valid permutations of (0, 1, 2, 3) are:\n(1, 0, 3, 2)\n(2, 0, 3, 1)\n(2, 1, 3, 0)\n(3, 0, 2, 1)\n(3, 1, 2, 0)\n\nExample 2:\nInput: s = \"D\"\nOutput: 1\n\nConstraints:\n- n == s.length\n- 1 <= n <= 200\n- s[i] is either 'I' or 'D'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def numPermsDISequence(self, S):\n \"\"\"\n :type S: str\n :rtype: int\n \"\"\"\n dp = [1]*(len(S)+1)\n for c in S:\n if c == \"I\":\n dp = dp[:-1]\n for i in range(1, len(dp)):\n dp[i] += dp[i-1]\n else:\n dp = dp[1:]\n for i in reversed(range(len(dp)-1)):\n dp[i] += dp[i+1]\n return dp[0] % (10**9+7)\n\n"}} diff --git a/cp/cp-10379.jsonl b/cp/cp-10379.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..86fafc9033691fd99714a1efa385d7ed3b5ec078 --- /dev/null +++ b/cp/cp-10379.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10379", "name": "LeetCode 0904: Fruit Into Baskets"} +{"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: Fruit Into Baskets (Difficulty: Medium)\nTags: Array, Hash Table, Sliding Window\n\nYou are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.\nYou want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:\nGiven the integer array fruits, return the maximum number of fruits you can pick.\n\nExample 1:\nInput: fruits = [1,2,1]\nOutput: 3\nExplanation: We can pick from all 3 trees.\n\nExample 2:\nInput: fruits = [0,1,2,2]\nOutput: 3\nExplanation: We can pick from trees [1,2,2].\nIf we had started at the first tree, we would only pick from trees [0,1].\n\nExample 3:\nInput: fruits = [1,2,3,2,2]\nOutput: 4\nExplanation: We can pick from trees [2,3,2,2].\nIf we had started at the first tree, we would only pick from trees [1,2].\n\nConstraints:\n- 1 <= fruits.length <= 10^5\n- 0 <= fruits[i] < fruits.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def totalFruit(self, tree):\n \"\"\"\n :type tree: List[int]\n :rtype: int\n \"\"\"\n count = collections.defaultdict(int)\n result, i = 0, 0\n for j, v in enumerate(tree):\n count[v] += 1\n while len(count) > 2:\n count[tree[i]] -= 1\n if count[tree[i]] == 0:\n del count[tree[i]]\n i += 1\n result = max(result, j-i+1)\n return result\n \n\n"}} diff --git a/cp/cp-10380.jsonl b/cp/cp-10380.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..31e2a742d11dd973e9645d026642a78b3feca684 --- /dev/null +++ b/cp/cp-10380.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10380", "name": "LeetCode 0905: Sort Array By Parity"} +{"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: Sort Array By Parity (Difficulty: Easy)\nTags: Array, Two Pointers, Sorting\n\nGiven an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.\nReturn any array that satisfies this condition.\n\nExample 1:\nInput: nums = [3,1,2,4]\nOutput: [2,4,3,1]\nExplanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.\n\nExample 2:\nInput: nums = [0]\nOutput: [0]\n\nConstraints:\n- 1 <= nums.length <= 5000\n- 0 <= nums[i] <= 5000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def sortArrayByParity(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: List[int]\n \"\"\"\n i = 0\n for j in range(len(A)):\n if A[j] % 2 == 0:\n A[i], A[j] = A[j], A[i]\n i += 1\n return A\n\n"}} diff --git a/cp/cp-10381.jsonl b/cp/cp-10381.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..73a08d96bc0fe5bf1e3b402ac395387e227e8eca --- /dev/null +++ b/cp/cp-10381.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10381", "name": "LeetCode 0906: Super Palindromes"} +{"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: Super Palindromes (Difficulty: Hard)\nTags: Math, String, Enumeration\n\nLet's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.\nGiven two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right].\n\nExample 1:\nInput: left = \"4\", right = \"1000\"\nOutput: 4\nExplanation: 4, 9, 121, and 484 are superpalindromes.\nNote that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.\n\nExample 2:\nInput: left = \"1\", right = \"2\"\nOutput: 1\n\nConstraints:\n- 1 <= left.length, right.length <= 18\n- left and right consist of only digits.\n- left and right cannot have leading zeros.\n- left and right represent integers in the range [1, 1018 - 1].\n- left is less than or equal to right."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^0.25 * logn)\n# Space: O(logn)\n\nclass Solution(object):\n def superpalindromesInRange(self, L, R):\n \"\"\"\n :type L: str\n :type R: str\n :rtype: int\n \"\"\"\n def is_palindrome(k):\n return str(k) == str(k)[::-1]\n\n K = int((10**((len(R)+1)*0.25)))\n l, r = int(L), int(R)\n\n result = 0\n\n # count odd length\n for k in range(K):\n s = str(k)\n t = s + s[-2::-1]\n v = int(t)**2\n if v > r:\n break\n if v >= l and is_palindrome(v):\n result += 1\n\n # count even length\n for k in range(K):\n s = str(k)\n t = s + s[::-1]\n v = int(t)**2\n if v > r:\n break\n if v >= l and is_palindrome(v):\n result += 1\n\n return result\n\n"}} diff --git a/cp/cp-10382.jsonl b/cp/cp-10382.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b23d55309a669b26ffb57a326275e4379ca12e6c --- /dev/null +++ b/cp/cp-10382.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10382", "name": "LeetCode 0907: Sum Of Subarray Minimums"} +{"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 Subarray Minimums (Difficulty: Medium)\nTags: Array, Dynamic Programming, Stack, Monotonic Stack\n\nGiven an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.\n\nExample 1:\nInput: arr = [3,1,2,4]\nOutput: 17\nExplanation: \nSubarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. \nMinimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.\nSum is 17.\n\nExample 2:\nInput: arr = [11,81,94,43,3]\nOutput: 444\n\nConstraints:\n- 1 <= arr.length <= 3 * 10^4\n- 1 <= arr[i] <= 3 * 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport itertools\n\n\n# Ascending stack solution\nclass Solution(object):\n def sumSubarrayMins(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n M = 10**9 + 7\n\n left, s1 = [0]*len(A), []\n for i in range(len(A)):\n count = 1\n while s1 and s1[-1][0] > A[i]:\n count += s1.pop()[1]\n left[i] = count\n s1.append([A[i], count])\n\n right, s2 = [0]*len(A), []\n for i in reversed(range(len(A))):\n count = 1\n while s2 and s2[-1][0] >= A[i]:\n count += s2.pop()[1]\n right[i] = count\n s2.append([A[i], count])\n\n return sum(a*l*r for a, l, r in itertools.izip(A, left, right)) % M\n\n"}} diff --git a/cp/cp-10384.jsonl b/cp/cp-10384.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e9e70d63cb949fc0ced9d686ddfd1643513b96d1 --- /dev/null +++ b/cp/cp-10384.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10384", "name": "LeetCode 0909: Snakes And Ladders"} +{"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: Snakes and Ladders (Difficulty: Medium)\nTags: Array, Breadth-First Search, Matrix\n\nYou are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.\nYou start on square 1 of the board. In each move, starting from square curr, do the following:\nA board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 are not the starting points of any snake or ladder.\nNote that you only take a snake or ladder at most once per dice roll. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder.\nReturn the least number of dice rolls required to reach the square n2. If it is not possible to reach the square, return -1.\n\nExample 1:\nInput: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]\nOutput: 4\nExplanation: \nIn the beginning, you start at square 1 (at row 5, column 0).\nYou decide to move to square 2 and must take the ladder to square 15.\nYou then decide to move to square 17 and must take the snake to square 13.\nYou then decide to move to square 14 and must take the ladder to square 35.\nYou then decide to move to square 36, ending the game.\nThis is the lowest possible number of moves to reach the last square, so return 4.\n\nExample 2:\nInput: board = [[-1,-1],[-1,3]]\nOutput: 1\n\nConstraints:\n- n == board.length == board[i].length\n- 2 <= n <= 20\n- board[i][j] is either -1 or in the range [1, n2].\n- The squares labeled 1 and n2 are not the starting points of any snake or ladder."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2)\n\nimport collections\n\n\nclass Solution(object):\n def snakesAndLadders(self, board):\n \"\"\"\n :type board: List[List[int]]\n :rtype: int\n \"\"\"\n def coordinate(n, s):\n a, b = divmod(s-1, n)\n r = n-1-a\n c = b if r%2 != n%2 else n-1-b\n return r, c\n\n n = len(board)\n lookup = {1: 0}\n q = collections.deque([1])\n while q:\n s = q.popleft()\n if s == n*n:\n return lookup[s]\n for s2 in range(s+1, min(s+6, n*n)+1):\n r, c = coordinate(n, s2)\n if board[r][c] != -1:\n s2 = board[r][c]\n if s2 not in lookup:\n lookup[s2] = lookup[s]+1\n q.append(s2)\n return -1\n\n"}} diff --git a/cp/cp-10385.jsonl b/cp/cp-10385.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..35571b9da940319ef533330f809967d91b906791 --- /dev/null +++ b/cp/cp-10385.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10385", "name": "LeetCode 0910: Smallest Range 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: Smallest Range II (Difficulty: Medium)\nTags: Array, Math, Greedy, Sorting\n\nYou are given an integer array nums and an integer k.\nFor each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k.\nThe score of nums is the difference between the maximum and minimum elements in nums.\nReturn the minimum score of nums after changing the values at each index.\n\nExample 1:\nInput: nums = [1], k = 0\nOutput: 0\nExplanation: The score is max(nums) - min(nums) = 1 - 1 = 0.\n\nExample 2:\nInput: nums = [0,10], k = 2\nOutput: 6\nExplanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.\n\nExample 3:\nInput: nums = [1,3,6], k = 3\nOutput: 3\nExplanation: Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3.\n\nConstraints:\n- 1 <= nums.length <= 10^4\n- 0 <= nums[i] <= 10^4\n- 0 <= k <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def smallestRangeII(self, A, K):\n \"\"\"\n :type A: List[int]\n :type K: int\n :rtype: int\n \"\"\"\n A.sort()\n result = A[-1]-A[0]\n for i in range(len(A)-1):\n result = min(result,\n max(A[-1]-K, A[i]+K) -\n min(A[0]+K, A[i+1]-K))\n return result\n\n"}} diff --git a/cp/cp-10386.jsonl b/cp/cp-10386.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..726d43eeba2ee53568b9d1cd5cccf3ddf67182e9 --- /dev/null +++ b/cp/cp-10386.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10386", "name": "LeetCode 0911: Online Election"} +{"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: Online Election (Difficulty: Medium)\nTags: Array, Hash Table, Binary Search, Design\n\nYou are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i].\nFor each query at a time t, find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins.\nImplement the TopVotedCandidate class:\n\nExample 1:\nInput\n[\"TopVotedCandidate\", \"q\", \"q\", \"q\", \"q\", \"q\", \"q\"]\n[[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]\nOutput\n[null, 0, 1, 1, 0, 0, 1]\n\nExplanation\nTopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]);\ntopVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading.\ntopVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading.\ntopVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.)\ntopVotedCandidate.q(15); // return 0\ntopVotedCandidate.q(24); // return 0\ntopVotedCandidate.q(8); // return 1\n\nConstraints:\n- 1 <= persons.length <= 5000\n- times.length == persons.length\n- 0 <= persons[i] < persons.length\n- 0 <= times[i] <= 10^9\n- times is sorted in a strictly increasing order.\n- times[0] <= t <= 10^9\n- At most 104 calls will be made to q."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(n)\n# q: O(logn)\n# Space: O(n)\n\nimport collections\nimport itertools\nimport bisect\n\n\nclass TopVotedCandidate(object):\n\n def __init__(self, persons, times):\n \"\"\"\n :type persons: List[int]\n :type times: List[int]\n \"\"\"\n lead = -1\n self.__lookup, count = [], collections.defaultdict(int)\n for t, p in itertools.izip(times, persons):\n count[p] += 1\n if count[p] >= count[lead]:\n lead = p\n self.__lookup.append((t, lead))\n\n def q(self, t):\n \"\"\"\n :type t: int\n :rtype: int\n \"\"\"\n return self.__lookup[bisect.bisect(self.__lookup,\n (t, float(\"inf\")))-1][1]\n\n\n\n"}} diff --git a/cp/cp-10387.jsonl b/cp/cp-10387.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..083ae83274eb18d5054121df1b311ad63eec678e --- /dev/null +++ b/cp/cp-10387.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10387", "name": "LeetCode 0912: Sort An 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: Sort an Array (Difficulty: Medium)\nTags: Array, Divide and Conquer, Sorting, Heap (Priority Queue), Merge Sort, Bucket Sort, Radix Sort, Counting Sort\n\nGiven an array of integers nums, sort the array in ascending order and return it.\nYou must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.\n\nExample 1:\nInput: nums = [5,2,3,1]\nOutput: [1,2,3,5]\nExplanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).\n\nExample 2:\nInput: nums = [5,1,1,2,0,0]\nOutput: [0,0,1,1,2,5]\nExplanation: Note that the values of nums are not necessarily unique.\n\nConstraints:\n- 1 <= nums.length <= 5 * 10^4\n- -5 * 10^4 <= nums[i] <= 5 * 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\n# merge sort solution\nclass Solution(object):\n def sortArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n def mergeSort(left, right, nums):\n if left == right:\n return\n mid = left + (right-left)//2\n mergeSort(left, mid, nums)\n mergeSort(mid+1, right, nums)\n r = mid+1\n tmp = []\n for l in range(left, mid+1):\n while r <= right and nums[r] < nums[l]:\n tmp.append(nums[r])\n r += 1\n tmp.append(nums[l])\n nums[left:left+len(tmp)] = tmp\n\n mergeSort(0, len(nums)-1, nums)\n return nums\n\n\n# Time: O(nlogn), on average\n# Space: O(logn)\nimport random\n# quick sort solution\nclass Solution2(object):\n def sortArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n def nth_element(nums, left, n, right, compare=lambda a, b: a < b):\n def tri_partition(nums, left, right, target):\n i = left\n while i <= right:\n if compare(nums[i], target):\n nums[i], nums[left] = nums[left], nums[i]\n left += 1\n i += 1\n elif compare(target, nums[i]):\n nums[i], nums[right] = nums[right], nums[i]\n right -= 1\n else:\n i += 1\n return left, right\n\n while left <= right:\n pivot_idx = random.randint(left, right)\n pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx])\n if pivot_left <= n <= pivot_right:\n return\n elif pivot_left > n:\n right = pivot_left-1\n else: # pivot_right < n.\n left = pivot_right+1\n\n def quickSort(left, right, nums):\n if left > right:\n return\n mid = left + (right-left)//2\n nth_element(nums, left, mid, right)\n quickSort(left, mid-1, nums)\n quickSort(mid+1, right, nums)\n\n quickSort(0, len(nums)-1, nums)\n return nums\n"}} diff --git a/cp/cp-10388.jsonl b/cp/cp-10388.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8ad7f8d47106f7e2713b8257152d8d9bd521b1c7 --- /dev/null +++ b/cp/cp-10388.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10388", "name": "LeetCode 0913: Cat And Mouse"} +{"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: Cat and Mouse (Difficulty: Hard)\nTags: Math, Dynamic Programming, Graph, Topological Sort, Memoization, Game Theory\n\nA game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.\nThe graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.\nThe mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0.\nDuring each player's turn, they must travel along one edge of the graph that meets where they are.  For example, if the Mouse is at node 1, it must travel to any node in graph[1].\nAdditionally, it is not allowed for the Cat to travel to the Hole (node 0).\nThen, the game can end in three ways:\nGiven a graph, and assuming both players play optimally, return\n\nExample 1:\nInput: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]\nOutput: 0\n\nExample 2:\nInput: graph = [[1,3],[0],[3],[0,2]]\nOutput: 1\n\nConstraints:\n- 3 <= graph.length <= 50\n- 1 <= graph[i].length < graph.length\n- 0 <= graph[i][j] < graph.length\n- graph[i][j] != i\n- graph[i] is unique.\n- The mouse and the cat can always move."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(n^2)\n\nimport collections\n\n\nclass Solution(object):\n def catMouseGame(self, graph):\n \"\"\"\n :type graph: List[List[int]]\n :rtype: int\n \"\"\"\n HOLE, MOUSE_START, CAT_START = range(3)\n DRAW, MOUSE, CAT = range(3)\n def parents(m, c, t):\n if t == CAT:\n for nm in graph[m]:\n yield nm, c, MOUSE^CAT^t\n else:\n for nc in graph[c]:\n if nc != HOLE:\n yield m, nc, MOUSE^CAT^t\n\n degree = {}\n ignore = set(graph[HOLE])\n for m in range(len(graph)):\n for c in range(len(graph)):\n degree[m, c, MOUSE] = len(graph[m])\n degree[m, c, CAT] = len(graph[c])-(c in ignore)\n color = collections.defaultdict(int)\n q = collections.deque()\n for i in range(len(graph)):\n if i == HOLE:\n continue\n color[HOLE, i, CAT] = MOUSE\n q.append((HOLE, i, CAT, MOUSE))\n for t in [MOUSE, CAT]:\n color[i, i, t] = CAT\n q.append((i, i, t, CAT))\n while q:\n i, j, t, c = q.popleft()\n for ni, nj, nt in parents(i, j, t):\n if color[ni, nj, nt] != DRAW:\n continue\n if nt == c:\n color[ni, nj, nt] = c\n q.append((ni, nj, nt, c))\n continue\n degree[ni, nj, nt] -= 1\n if not degree[ni, nj, nt]:\n color[ni, nj, nt] = c\n q.append((ni, nj, nt, c))\n return color[MOUSE_START, CAT_START, MOUSE]\n\n \n# Time: O(n^3)\n# Space: O(n^2)\nimport collections\n\n\nclass Solution2(object):\n def catMouseGame(self, graph):\n \"\"\"\n :type graph: List[List[int]]\n :rtype: int\n \"\"\"\n HOLE, MOUSE_START, CAT_START = range(3)\n DRAW, MOUSE, CAT = range(3)\n def parents(m, c, t):\n if t == CAT:\n for nm in graph[m]:\n yield nm, c, MOUSE^CAT^t\n else:\n for nc in graph[c]:\n if nc != HOLE:\n yield m, nc, MOUSE^CAT^t\n\n color = collections.defaultdict(int)\n degree = {}\n ignore = set(graph[HOLE])\n for m in range(len(graph)):\n for c in range(len(graph)):\n degree[m, c, MOUSE] = len(graph[m])\n degree[m, c, CAT] = len(graph[c])-(c in ignore)\n q1 = collections.deque()\n q2 = collections.deque()\n for i in range(len(graph)):\n if i == HOLE:\n continue\n color[HOLE, i, CAT] = MOUSE\n q1.append((HOLE, i, CAT))\n for t in [MOUSE, CAT]:\n color[i, i, t] = CAT\n q2.append((i, i, t))\n while q1:\n i, j, t = q1.popleft()\n for ni, nj, nt in parents(i, j, t):\n if color[ni, nj, nt] != DRAW:\n continue\n if t == CAT:\n color[ni, nj, nt] = MOUSE\n q1.append((ni, nj, nt))\n continue\n degree[ni, nj, nt] -= 1\n if not degree[ni, nj, nt]:\n color[ni, nj, nt] = MOUSE\n q1.append((ni, nj, nt))\n while q2:\n i, j, t = q2.popleft()\n for ni, nj, nt in parents(i, j, t):\n if color[ni, nj, nt] != DRAW:\n continue\n if t == MOUSE:\n color[ni, nj, nt] = CAT\n q2.append((ni, nj, nt))\n continue\n degree[ni, nj, nt] -= 1\n if not degree[ni, nj, nt]:\n color[ni, nj, nt] = CAT\n q2.append((ni, nj, nt))\n return color[MOUSE_START, CAT_START, MOUSE]\n"}} diff --git a/cp/cp-10389.jsonl b/cp/cp-10389.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b30353cda6184d402d52bb0a52a875ebc104cb21 --- /dev/null +++ b/cp/cp-10389.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10389", "name": "LeetCode 0914: X Of A Kind In A Deck Of Cards"} +{"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: X of a Kind in a Deck of Cards (Difficulty: Easy)\nTags: Array, Hash Table, Math, Counting, Number Theory\n\nYou are given an integer array deck where deck[i] represents the number written on the ith card.\nPartition the cards into one or more groups such that:\nReturn true if such partition is possible, or false otherwise.\n\nExample 1:\nInput: deck = [1,2,3,4,4,3,2,1]\nOutput: true\nExplanation: Possible partition [1,1],[2,2],[3,3],[4,4].\n\nExample 2:\nInput: deck = [1,1,1,2,2,2,3,3]\nOutput: false\nExplanation: No possible partition.\n\nConstraints:\n- 1 <= deck.length <= 10^4\n- 0 <= deck[i] < 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * (logn)^2)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def hasGroupsSizeX(self, deck):\n \"\"\"\n :type deck: List[int]\n :rtype: bool\n \"\"\"\n def gcd(a, b): # Time: O((logn)^2)\n while b:\n a, b = b, a % b\n return a\n\n vals = collections.Counter(deck).values()\n return reduce(gcd, vals) >= 2\n\n"}} diff --git a/cp/cp-10390.jsonl b/cp/cp-10390.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6c69e1cd629ed327db3c170a79ed2bf71396631d --- /dev/null +++ b/cp/cp-10390.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10390", "name": "LeetCode 0915: Partition Array Into Disjoint Intervals"} +{"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: Partition Array into Disjoint Intervals (Difficulty: Medium)\nTags: Array\n\nGiven an integer array nums, partition it into two (contiguous) subarrays left and right so that:\nReturn the length of left after such a partitioning.\nTest cases are generated such that partitioning exists.\n\nExample 1:\nInput: nums = [5,0,3,8,6]\nOutput: 3\nExplanation: left = [5,0,3], right = [8,6]\n\nExample 2:\nInput: nums = [1,1,1,0,6,12]\nOutput: 4\nExplanation: left = [1,1,1,0], right = [6,12]\n\nConstraints:\n- 2 <= nums.length <= 10^5\n- 0 <= nums[i] <= 10^6\n- There is at least one valid answer for the given input."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def partitionDisjoint(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n B = A[:]\n for i in reversed(range(len(A)-1)):\n B[i] = min(B[i], B[i+1])\n p_max = 0\n for i in range(1, len(A)):\n p_max = max(p_max, A[i-1])\n if p_max <= B[i]:\n return i\n\n"}} diff --git a/cp/cp-10391.jsonl b/cp/cp-10391.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..45a449abc0568cbf0f5e9095987a1f39714d9814 --- /dev/null +++ b/cp/cp-10391.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10391", "name": "LeetCode 0916: Word Subsets"} +{"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: Word Subsets (Difficulty: Medium)\nTags: Array, Hash Table, String\n\nYou are given two string arrays words1 and words2.\nA string b is a subset of string a if every letter in b occurs in a including multiplicity.\nA string a from words1 is universal if for every string b in words2, b is a subset of a.\nReturn an array of all the universal strings in words1. You may return the answer in any order.\n\nExample 1:\nInput: words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"e\",\"o\"]\nOutput: [\"facebook\",\"google\",\"leetcode\"]\n\nExample 2:\nInput: words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"lc\",\"eo\"]\nOutput: [\"leetcode\"]\n\nExample 3:\nInput: words1 = [\"acaac\",\"cccbb\",\"aacbb\",\"caacc\",\"bcbbb\"], words2 = [\"c\",\"cc\",\"b\"]\nOutput: [\"cccbb\"]\n\nConstraints:\n- 1 <= words1.length, words2.length <= 10^4\n- 1 <= words1[i].length, words2[i].length <= 10\n- words1[i] and words2[i] consist only of lowercase English letters.\n- All the strings of words1 are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def wordSubsets(self, A, B):\n \"\"\"\n :type A: List[str]\n :type B: List[str]\n :rtype: List[str]\n \"\"\"\n count = collections.Counter()\n for b in B:\n for c, n in collections.Counter(b).items():\n count[c] = max(count[c], n)\n result = []\n for a in A:\n count = collections.Counter(a)\n if all(count[c] >= count[c] for c in count):\n result.append(a)\n return result\n\n"}} diff --git a/cp/cp-10392.jsonl b/cp/cp-10392.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b738e05a66e2a56c3f441250e3ec25aaf955e3f6 --- /dev/null +++ b/cp/cp-10392.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10392", "name": "LeetCode 0917: Reverse Only Letters"} +{"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: Reverse Only Letters (Difficulty: Easy)\nTags: Two Pointers, String\n\nGiven a string s, reverse the string according to the following rules:\nReturn s after reversing it.\n\nExample 1:\nInput: s = \"ab-cd\"\nOutput: \"dc-ba\"\n\nExample 2:\nInput: s = \"a-bC-dEf-ghIj\"\nOutput: \"j-Ih-gfE-dCba\"\n\nExample 3:\nInput: s = \"Test1ng-Leet=code-Q!\"\nOutput: \"Qedo1ct-eeLg=ntse-T!\"\n\nConstraints:\n- 1 <= s.length <= 100\n- s consists of characters with ASCII values in the range [33, 122].\n- s does not contain '\\\"' or '\\\\'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def reverseOnlyLetters(self, S):\n \"\"\"\n :type S: str\n :rtype: str\n \"\"\"\n def getNext(S):\n for i in reversed(range(len(S))):\n if S[i].isalpha():\n yield S[i]\n\n result = []\n letter = getNext(S)\n for i in range(len(S)):\n if S[i].isalpha():\n result.append(letter.next())\n else:\n result.append(S[i])\n return \"\".join(result)\n\n"}} diff --git a/cp/cp-10393.jsonl b/cp/cp-10393.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7ea04ab3efcf85457f2d1e8a5637dcc1667eaaa1 --- /dev/null +++ b/cp/cp-10393.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10393", "name": "LeetCode 0918: Maximum Sum Circular Subarray"} +{"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 Sum Circular Subarray (Difficulty: Medium)\nTags: Array, Divide and Conquer, Dynamic Programming, Queue, Monotonic Queue\n\nGiven a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.\nA circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n].\nA subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i <= k1, k2 <= j with k1 % n == k2 % n.\n\nExample 1:\nInput: nums = [1,-2,3,-2]\nOutput: 3\nExplanation: Subarray [3] has maximum sum 3.\n\nExample 2:\nInput: nums = [5,-3,5]\nOutput: 10\nExplanation: Subarray [5,5] has maximum sum 5 + 5 = 10.\n\nExample 3:\nInput: nums = [-3,-2,-3]\nOutput: -2\nExplanation: Subarray [-2] has maximum sum -2.\n\nConstraints:\n- n == nums.length\n- 1 <= n <= 3 * 10^4\n- -3 * 10^4 <= nums[i] <= 3 * 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxSubarraySumCircular(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n total, max_sum, cur_max, min_sum, cur_min = 0, -float(\"inf\"), 0, float(\"inf\"), 0\n for a in A:\n cur_max = max(cur_max+a, a)\n max_sum = max(max_sum, cur_max)\n cur_min = min(cur_min+a, a)\n min_sum = min(min_sum, cur_min)\n total += a\n return max(max_sum, total-min_sum) if max_sum >= 0 else max_sum\n\n"}} diff --git a/cp/cp-10394.jsonl b/cp/cp-10394.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4087a471a8518742060fd2a6e626c263a468ab47 --- /dev/null +++ b/cp/cp-10394.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10394", "name": "LeetCode 0919: Complete Binary Tree Inserter"} +{"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: Complete Binary Tree Inserter (Difficulty: Medium)\nTags: Tree, Breadth-First Search, Design, Binary Tree\n\nA complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.\nDesign an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion.\nImplement the CBTInserter class:\n\nExample 1:\nInput\n[\"CBTInserter\", \"insert\", \"insert\", \"get_root\"]\n[[[1, 2]], [3], [4], []]\nOutput\n[null, 1, 2, [1, 2, 3, 4]]\n\nExplanation\nCBTInserter cBTInserter = new CBTInserter([1, 2]);\ncBTInserter.insert(3); // return 1\ncBTInserter.insert(4); // return 2\ncBTInserter.get_root(); // return [1, 2, 3, 4]\n\nConstraints:\n- The number of nodes in the tree will be in the range [1, 1000].\n- 0 <= Node.val <= 5000\n- root is a complete binary tree.\n- 0 <= val <= 5000\n- At most 104 calls will be made to insert and get_root."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(n)\n# insert: O(1)\n# get_root: O(1)\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\nclass CBTInserter(object):\n\n def __init__(self, root):\n \"\"\"\n :type root: TreeNode\n \"\"\"\n self.__tree = [root]\n for i in self.__tree:\n if i.left:\n self.__tree.append(i.left)\n if i.right:\n self.__tree.append(i.right) \n\n def insert(self, v):\n \"\"\"\n :type v: int\n :rtype: int\n \"\"\"\n n = len(self.__tree)\n self.__tree.append(TreeNode(v))\n if n % 2:\n self.__tree[(n-1)//2].left = self.__tree[-1]\n else:\n self.__tree[(n-1)//2].right = self.__tree[-1]\n return self.__tree[(n-1)//2].val\n\n def get_root(self):\n \"\"\"\n :rtype: TreeNode\n \"\"\"\n return self.__tree[0]\n\n\n\n"}} diff --git a/cp/cp-10395.jsonl b/cp/cp-10395.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..364cd78a4116074eb7012851cd2e44dce99ec82d --- /dev/null +++ b/cp/cp-10395.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10395", "name": "LeetCode 0920: Number Of Music Playlists"} +{"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 Music Playlists (Difficulty: Hard)\nTags: Math, Dynamic Programming, Combinatorics\n\nYour music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:\nGiven n, goal, and k, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 109 + 7.\n\nExample 1:\nInput: n = 3, goal = 3, k = 1\nOutput: 6\nExplanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1].\n\nExample 2:\nInput: n = 2, goal = 3, k = 0\nOutput: 6\nExplanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2].\n\nExample 3:\nInput: n = 2, goal = 3, k = 1\nOutput: 2\nExplanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].\n\nConstraints:\n- 0 <= k < n <= goal <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * l)\n# Space: O(l)\n\nclass Solution(object):\n def numMusicPlaylists(self, N, L, K):\n \"\"\"\n :type N: int\n :type L: int\n :type K: int\n :rtype: int\n \"\"\"\n M = 10**9+7\n dp = [[0 for _ in range(1+L)] for _ in range(2)]\n dp[0][0] = dp[1][1] = 1\n for n in range(1, N+1):\n dp[n % 2][n] = (dp[(n-1) % 2][n-1] * n) % M\n for l in range(n+1, L+1):\n dp[n % 2][l] = ((dp[n % 2][l-1] * max(n-K, 0)) % M + \\\n (dp[(n-1) % 2][l-1] * n) % M) % M\n return dp[N % 2][L]\n\n"}} diff --git a/cp/cp-10396.jsonl b/cp/cp-10396.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bd0c642d54207579bdf2c2e5e3367bab2d2e6d75 --- /dev/null +++ b/cp/cp-10396.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10396", "name": "LeetCode 0921: Minimum Add To Make Parentheses Valid"} +{"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: Minimum Add to Make Parentheses Valid (Difficulty: Medium)\nTags: String, Stack, Greedy\n\nA parentheses string is valid if and only if:\nYou are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.\nReturn the minimum number of moves required to make s valid.\n\nExample 1:\nInput: s = \"())\"\nOutput: 1\n\nExample 2:\nInput: s = \"(((\"\nOutput: 3\n\nConstraints:\n- 1 <= s.length <= 1000\n- s[i] is either '(' or ')'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minAddToMakeValid(self, S):\n \"\"\"\n :type S: str\n :rtype: int\n \"\"\"\n add, bal, = 0, 0\n for c in S:\n bal += 1 if c == '(' else -1\n if bal == -1:\n add += 1\n bal += 1\n return add + bal\n"}} diff --git a/cp/cp-10397.jsonl b/cp/cp-10397.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4d0d0e84be8b74d06baf69bc093eb7f1a9554b89 --- /dev/null +++ b/cp/cp-10397.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10397", "name": "LeetCode 0922: Sort Array By Parity 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: Sort Array By Parity II (Difficulty: Easy)\nTags: Array, Two Pointers, Sorting\n\nGiven an array of integers nums, half of the integers in nums are odd, and the other half are even.\nSort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.\nReturn any answer array that satisfies this condition.\nFollow Up: Could you solve it in-place?\n\nExample 1:\nInput: nums = [4,2,5,7]\nOutput: [4,5,2,7]\nExplanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.\n\nExample 2:\nInput: nums = [2,3]\nOutput: [2,3]\n\nConstraints:\n- 2 <= nums.length <= 2 * 10^4\n- nums.length is even.\n- Half of the integers in nums are even.\n- 0 <= nums[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def sortArrayByParityII(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: List[int]\n \"\"\"\n j = 1\n for i in range(0, len(A), 2):\n if A[i] % 2:\n while A[j] % 2:\n j += 2\n A[i], A[j] = A[j], A[i]\n return A\n"}} diff --git a/cp/cp-10398.jsonl b/cp/cp-10398.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..87df5cc9934a46553fcb2856a7ff5d1b20de3e0c --- /dev/null +++ b/cp/cp-10398.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10398", "name": "LeetCode 0923: 3Sum With Multiplicity"} +{"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: 3Sum With Multiplicity (Difficulty: Medium)\nTags: Array, Hash Table, Two Pointers, Sorting, Counting\n\nGiven an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target.\nAs the answer can be very large, return it modulo 109 + 7.\n\nExample 1:\nInput: arr = [1,1,2,2,3,3,4,4,5,5], target = 8\nOutput: 20\nExplanation: \nEnumerating by the values (arr[i], arr[j], arr[k]):\n(1, 2, 5) occurs 8 times;\n(1, 3, 4) occurs 8 times;\n(2, 2, 4) occurs 2 times;\n(2, 3, 3) occurs 2 times.\n\nExample 2:\nInput: arr = [1,1,2,2,2,2], target = 5\nOutput: 12\nExplanation: \narr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:\nWe choose one 1 from [1,1] in 2 ways,\nand two 2s from [2,2,2,2] in 6 ways.\n\nExample 3:\nInput: arr = [2,1,3], target = 6\nOutput: 1\nExplanation: (1, 2, 3) occured one time in the array so we return 1.\n\nConstraints:\n- 3 <= arr.length <= 3000\n- 0 <= arr[i] <= 100\n- 0 <= target <= 300"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2), n is the number of disctinct A[i]\n# Space: O(n)\n\nimport collections\nimport itertools\n\n\nclass Solution(object):\n def threeSumMulti(self, A, target):\n \"\"\"\n :type A: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n count = collections.Counter(A)\n result = 0\n for i, j in itertools.combinations_with_replacement(count, 2):\n k = target - i - j\n if i == j == k:\n result += count[i] * (count[i]-1) * (count[i]-2) // 6\n elif i == j != k:\n result += count[i] * (count[i]-1) // 2 * count[k]\n elif max(i, j) < k:\n result += count[i] * count[j] * count[k]\n return result % (10**9 + 7)\n"}} diff --git a/cp/cp-10399.jsonl b/cp/cp-10399.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fd95d589b0ef44071c9ef0ecc6e21519693deff7 --- /dev/null +++ b/cp/cp-10399.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10399", "name": "LeetCode 0924: Minimize Malware Spread"} +{"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: Minimize Malware Spread (Difficulty: Hard)\nTags: Array, Hash Table, Depth-First Search, Breadth-First Search, Union Find, Graph\n\nYou are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.\nSome nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.\nSuppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial.\nReturn the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.\nNote that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.\n\nExample 1:\nInput: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput: 0\n\nExample 2:\nInput: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]\nOutput: 0\n\nExample 3:\nInput: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]\nOutput: 1\n\nConstraints:\n- n == graph.length\n- n == graph[i].length\n- 2 <= n <= 300\n- graph[i][j] is 0 or 1.\n- graph[i][j] == graph[j][i]\n- graph[i][i] == 1\n- 1 <= initial.length <= n\n- 0 <= initial[i] <= n - 1\n- All the integers in initial are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nimport collections\n\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n return True\n\n\nclass Solution(object):\n def minMalwareSpread(self, graph, initial):\n \"\"\"\n :type graph: List[List[int]]\n :type initial: List[int]\n :rtype: int\n \"\"\"\n union_find = UnionFind(len(graph))\n for i in range(len(graph)):\n for j in range(i+1, len(graph)):\n if graph[i][j] == 1:\n union_find.union_set(i, j)\n union_size = collections.Counter(union_find.find_set(i) for i in range(len(graph)))\n malware_count = collections.Counter(union_find.find_set(i) for i in initial)\n return min(initial, key=lambda x: [malware_count[union_find.find_set(x)] > 1,\n -union_size[union_find.find_set(x)],\n x])\n"}} diff --git a/cp/cp-10400.jsonl b/cp/cp-10400.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ed99fe0ec59756d5a30eabcd65eb6899f336f056 --- /dev/null +++ b/cp/cp-10400.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10400", "name": "LeetCode 0925: Long Pressed Name"} +{"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: Long Pressed Name (Difficulty: Easy)\nTags: Two Pointers, String\n\nYour friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.\nYou examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.\n\nExample 1:\nInput: name = \"alex\", typed = \"aaleex\"\nOutput: true\nExplanation: 'a' and 'e' in 'alex' were long pressed.\n\nExample 2:\nInput: name = \"saeed\", typed = \"ssaaedd\"\nOutput: false\nExplanation: 'e' must have been pressed twice, but it was not in the typed output.\n\nConstraints:\n- 1 <= name.length, typed.length <= 1000\n- name and typed consist of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def isLongPressedName(self, name, typed):\n \"\"\"\n :type name: str\n :type typed: str\n :rtype: bool\n \"\"\"\n i = 0\n for j in range(len(typed)):\n if i < len(name) and name[i] == typed[j]:\n i += 1\n elif j == 0 or typed[j] != typed[j-1]:\n return False\n return i == len(name)\n"}} diff --git a/cp/cp-10401.jsonl b/cp/cp-10401.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..994a50d7a192c59b9143b48da62ce4305fe31cdc --- /dev/null +++ b/cp/cp-10401.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10401", "name": "LeetCode 0926: Flip String To Monotone Increasing"} +{"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: Flip String to Monotone Increasing (Difficulty: Medium)\nTags: String, Dynamic Programming\n\nA binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none).\nYou are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0.\nReturn the minimum number of flips to make s monotone increasing.\n\nExample 1:\nInput: s = \"00110\"\nOutput: 1\nExplanation: We flip the last digit to get 00111.\n\nExample 2:\nInput: s = \"010110\"\nOutput: 2\nExplanation: We flip to get 011111, or alternatively 000111.\n\nExample 3:\nInput: s = \"00011000\"\nOutput: 2\nExplanation: We flip to get 00000000.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s[i] is either '0' or '1'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minFlipsMonoIncr(self, S):\n \"\"\"\n :type S: str\n :rtype: int\n \"\"\"\n flip0, flip1 = 0, 0\n for c in S:\n flip0 += int(c == '1')\n flip1 = min(flip0, flip1 + int(c == '0'))\n return flip1\n"}} diff --git a/cp/cp-10402.jsonl b/cp/cp-10402.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4143c8d9087ce950782495dbfb8792872e8b2519 --- /dev/null +++ b/cp/cp-10402.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10402", "name": "LeetCode 0927: Three Equal Parts"} +{"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: Three Equal Parts (Difficulty: Hard)\nTags: Array, Math\n\nYou are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value.\nIf it is possible, return any [i, j] with i + 1 < j, such that:\nIf it is not possible, return [-1, -1].\nNote that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.\n\nExample 1:\nInput: arr = [1,0,1,0,1]\nOutput: [0,3]\n\nExample 2:\nInput: arr = [1,1,0,1,1]\nOutput: [-1,-1]\n\nExample 3:\nInput: arr = [1,1,0,0,1]\nOutput: [0,2]\n\nConstraints:\n- 3 <= arr.length <= 3 * 10^4\n- arr[i] is 0 or 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def threeEqualParts(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: List[int]\n \"\"\"\n total = sum(A)\n if total % 3 != 0:\n return [-1, -1]\n if total == 0:\n return [0, len(A)-1]\n\n count = total//3\n nums = [0]*3\n c = 0\n for i in range(len(A)):\n if A[i] == 1:\n if c % count == 0:\n nums[c//count] = i\n c += 1\n\n while nums[2] != len(A):\n if not A[nums[0]] == A[nums[1]] == A[nums[2]]:\n return [-1, -1]\n nums[0] += 1\n nums[1] += 1\n nums[2] += 1\n return [nums[0]-1, nums[1]]\n"}} diff --git a/cp/cp-10403.jsonl b/cp/cp-10403.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b7270438996faedc59f8e60a9280c3d309ee3c51 --- /dev/null +++ b/cp/cp-10403.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10403", "name": "LeetCode 0928: Minimize Malware Spread 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: Minimize Malware Spread II (Difficulty: Hard)\nTags: Array, Hash Table, Depth-First Search, Breadth-First Search, Union Find, Graph\n\nYou are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.\nSome nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.\nSuppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops.\nWe will remove exactly one node from initial, completely removing it and any connections from this node to any other node.\nReturn the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.\n\nExample 1:\nInput: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput: 0\n\nExample 2:\nInput: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]\nOutput: 1\n\nExample 3:\nInput: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]\nOutput: 1\n\nConstraints:\n- n == graph.length\n- n == graph[i].length\n- 2 <= n <= 300\n- graph[i][j] is 0 or 1.\n- graph[i][j] == graph[j][i]\n- graph[i][i] == 1\n- 1 <= initial.length < n\n- 0 <= initial[i] <= n - 1\n- All the integers in initial are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nimport collections\n\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n return True\n\n\nclass Solution(object):\n def minMalwareSpread(self, graph, initial):\n \"\"\"\n :type graph: List[List[int]]\n :type initial: List[int]\n :rtype: int\n \"\"\"\n initial_set = set(initial)\n clean = [i for i in range(len(graph)) if i not in initial_set]\n union_find = UnionFind(len(graph))\n for i in range(len(clean)):\n for j in range(i+1, len(clean)):\n if graph[clean[i]][clean[j]] == 1:\n union_find.union_set(clean[i], clean[j])\n union_size = collections.Counter(union_find.find_set(i) for i in range(len(graph)))\n \n shared_union = collections.defaultdict(set)\n for i in initial:\n for j in clean: \n if graph[i][j] == 1:\n x = union_find.find_set(j)\n shared_union[x].add(i)\n\n result, total = float(\"inf\"), float(\"-inf\")\n for i in initial:\n lookup = set()\n curr = 0\n for j in clean: \n if graph[i][j] == 1:\n x = union_find.find_set(j)\n if len(shared_union[x]) == 1 and \\\n x not in lookup:\n curr += union_size[x]\n lookup.add(x)\n if curr > total or \\\n (curr == total and i < result):\n total = curr\n result = i\n return result\n"}} diff --git a/cp/cp-10404.jsonl b/cp/cp-10404.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..638d315676d4698d715addcd726841e4827300de --- /dev/null +++ b/cp/cp-10404.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10404", "name": "LeetCode 0929: Unique Email Addresses"} +{"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: Unique Email Addresses (Difficulty: Easy)\nTags: Array, Hash Table, String\n\nEvery valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'.\nIf you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names.\nIf you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names.\nIt is possible to use both of these rules at the same time.\nGiven an array of strings emails where we send one email to each emails[i], return the number of different addresses that actually receive mails.\n\nExample 1:\nInput: emails = [\"test.email+alex@leetcode.com\",\"test.e.mail+bob.cathy@leetcode.com\",\"testemail+david@lee.tcode.com\"]\nOutput: 2\nExplanation: \"testemail@leetcode.com\" and \"testemail@lee.tcode.com\" actually receive mails.\n\nExample 2:\nInput: emails = [\"a@leetcode.com\",\"b@leetcode.com\",\"c@leetcode.com\"]\nOutput: 3\n\nConstraints:\n- 1 <= emails.length <= 100\n- 1 <= emails[i].length <= 100\n- emails[i] consist of lowercase English letters, '+', '.' and '@'.\n- Each emails[i] contains exactly one '@' character.\n- All local and domain names are non-empty.\n- Local names do not start with a '+' character.\n- Domain names end with the \".com\" suffix.\n- Domain names must contain at least one character before \".com\" suffix."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * l)\n# Space: O(n * l)\n\nclass Solution(object):\n def numUniqueEmails(self, emails):\n \"\"\"\n :type emails: List[str]\n :rtype: int\n \"\"\"\n def convert(email):\n name, domain = email.split('@')\n name = name[:name.index('+')]\n return \"\".join([\"\".join(name.split(\".\")), '@', domain])\n\n lookup = set()\n for email in emails:\n lookup.add(convert(email))\n return len(lookup)\n \n"}} diff --git a/cp/cp-10405.jsonl b/cp/cp-10405.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fad38e03fd89a17d2d98b1054a7f2bc3f04e0ba8 --- /dev/null +++ b/cp/cp-10405.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10405", "name": "LeetCode 0930: Binary Subarrays With Sum"} +{"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: Binary Subarrays With Sum (Difficulty: Medium)\nTags: Array, Hash Table, Sliding Window, Prefix Sum\n\nGiven a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.\nA subarray is a contiguous part of the array.\n\nExample 1:\nInput: nums = [1,0,1,0,1], goal = 2\nOutput: 4\nExplanation: The 4 subarrays are bolded and underlined below:\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]\n\nExample 2:\nInput: nums = [0,0,0,0,0], goal = 0\nOutput: 15\n\nConstraints:\n- 1 <= nums.length <= 3 * 10^4\n- nums[i] is either 0 or 1.\n- 0 <= goal <= nums.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# Two pointers solution\nclass Solution(object):\n def numSubarraysWithSum(self, A, S):\n \"\"\"\n :type A: List[int]\n :type S: int\n :rtype: int\n \"\"\"\n result = 0\n left, right, sum_left, sum_right = 0, 0, 0, 0\n for i, a in enumerate(A):\n sum_left += a\n while left < i and sum_left > S:\n sum_left -= A[left]\n left += 1\n sum_right += a\n while right < i and \\\n (sum_right > S or (sum_right == S and not A[right])):\n sum_right -= A[right]\n right += 1\n if sum_left == S:\n result += right-left+1\n return result\n"}} diff --git a/cp/cp-10406.jsonl b/cp/cp-10406.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e12d4b418e7036ab625b123e91c9480b393afa09 --- /dev/null +++ b/cp/cp-10406.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10406", "name": "LeetCode 0931: Minimum Falling Path Sum"} +{"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: Minimum Falling Path Sum (Difficulty: Medium)\nTags: Array, Dynamic Programming, Matrix\n\nGiven an n x n array of integers matrix, return the minimum sum of any falling path through matrix.\nA falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).\n\nExample 1:\nInput: matrix = [[2,1,3],[6,5,4],[7,8,9]]\nOutput: 13\nExplanation: There are two falling paths with a minimum sum as shown.\n\nExample 2:\nInput: matrix = [[-19,57],[-40,-5]]\nOutput: -59\nExplanation: The falling path with a minimum sum is shown.\n\nConstraints:\n- n == matrix.length == matrix[i].length\n- 1 <= n <= 100\n- -100 <= matrix[i][j] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(1)\n\nclass Solution(object):\n def minFallingPathSum(self, A):\n \"\"\"\n :type A: List[List[int]]\n :rtype: int\n \"\"\"\n for i in range(1, len(A)):\n for j in range(len(A[i])):\n A[i][j] += min(A[i-1][max(j-1, 0):j+2])\n return min(A[-1])\n"}} diff --git a/cp/cp-10407.jsonl b/cp/cp-10407.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..10b0f9011e43d10a8dbbcc7e0510ff7221fd78a5 --- /dev/null +++ b/cp/cp-10407.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10407", "name": "LeetCode 0932: Beautiful 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: Beautiful Array (Difficulty: Medium)\nTags: Array, Math, Divide and Conquer\n\nAn array nums of length n is beautiful if:\nGiven the integer n, return any beautiful array nums of length n. There will be at least one valid answer for the given n.\n\nExample 1:\nInput: n = 4\nOutput: [2,1,4,3]\n\nExample 2:\nInput: n = 5\nOutput: [3,1,2,5,4]\n\nConstraints:\n- 1 <= n <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def beautifulArray(self, N):\n \"\"\"\n :type N: int\n :rtype: List[int]\n \"\"\"\n result = [1]\n while len(result) < N:\n result = [i*2 - 1 for i in result] + [i*2 for i in result]\n return [i for i in result if i <= N]\n"}} diff --git a/cp/cp-10408.jsonl b/cp/cp-10408.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..44a7a59a10acac37330127ed6a48cc629dae58ee --- /dev/null +++ b/cp/cp-10408.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10408", "name": "LeetCode 0933: Number Of Recent Calls"} +{"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 Recent Calls (Difficulty: Easy)\nTags: Design, Queue, Data Stream\n\nYou have a RecentCounter class which counts the number of recent requests within a certain time frame.\nImplement the RecentCounter class:\nIt is guaranteed that every call to ping uses a strictly larger value of t than the previous call.\n\nExample 1:\nInput\n[\"RecentCounter\", \"ping\", \"ping\", \"ping\", \"ping\"]\n[[], [1], [100], [3001], [3002]]\nOutput\n[null, 1, 2, 3, 3]\n\nExplanation\nRecentCounter recentCounter = new RecentCounter();\nrecentCounter.ping(1); // requests = [1], range is [-2999,1], return 1\nrecentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2\nrecentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3\nrecentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3\n\nConstraints:\n- 1 <= t <= 10^9\n- Each test case will call ping with strictly increasing values of t.\n- At most 104 calls will be made to ping."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1) on average\n# Space: O(w), w means the size of the last milliseconds.\n\nimport collections\n\n\nclass RecentCounter(object):\n\n def __init__(self):\n self.__q = collections.deque()\n\n def ping(self, t):\n \"\"\"\n :type t: int\n :rtype: int\n \"\"\"\n self.__q.append(t)\n while self.__q[0] < t-3000:\n self.__q.popleft()\n return len(self.__q)\n"}} diff --git a/cp/cp-10409.jsonl b/cp/cp-10409.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8fa98888908f943b4e396f4e12b9605d28c039dc --- /dev/null +++ b/cp/cp-10409.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10409", "name": "LeetCode 0934: Shortest Bridge"} +{"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: Shortest Bridge (Difficulty: Medium)\nTags: Array, Depth-First Search, Breadth-First Search, Matrix\n\nYou are given an n x n binary matrix grid where 1 represents land and 0 represents water.\nAn island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid.\nYou may change 0's to 1's to connect the two islands to form one island.\nReturn the smallest number of 0's you must flip to connect the two islands.\n\nExample 1:\nInput: grid = [[0,1],[1,0]]\nOutput: 1\n\nExample 2:\nInput: grid = [[0,1,0],[0,0,0],[0,0,1]]\nOutput: 2\n\nExample 3:\nInput: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]\nOutput: 1\n\nConstraints:\n- n == grid.length == grid[i].length\n- 2 <= n <= 100\n- grid[i][j] is either 0 or 1.\n- There are exactly two islands in grid."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2)\n\nimport collections\n\n\nclass Solution(object):\n def shortestBridge(self, A):\n \"\"\"\n :type A: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n\n def get_islands(A):\n islands = []\n done = set()\n for r, row in enumerate(A):\n for c, val in enumerate(row):\n if val == 0 or (r, c) in done:\n continue\n s = [(r, c)]\n lookup = set(s)\n while s:\n node = s.pop()\n for d in directions:\n nei = node[0]+d[0], node[1]+d[1]\n if not (0 <= nei[0] < len(A) and 0 <= nei[1] < len(A[0])) or \\\n nei in lookup or A[nei[0]][nei[1]] == 0:\n continue\n s.append(nei)\n lookup.add(nei)\n done |= lookup\n islands.append(lookup)\n if len(islands) == 2:\n break\n return islands\n\n lookup, target = get_islands(A)\n q = collections.deque([(node, 0) for node in lookup])\n while q:\n node, dis = q.popleft()\n if node in target:\n return dis-1\n for d in directions:\n nei = node[0]+d[0], node[1]+d[1]\n if not (0 <= nei[0] < len(A) and 0 <= nei[1] < len(A[0])) or \\\n nei in lookup:\n continue\n q.append((nei, dis+1))\n lookup.add(nei)\n"}} diff --git a/cp/cp-10410.jsonl b/cp/cp-10410.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e6c2f33f6597776270e06075eba143b756ed30d3 --- /dev/null +++ b/cp/cp-10410.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10410", "name": "LeetCode 0935: Knight Dialer"} +{"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: Knight Dialer (Difficulty: Medium)\nTags: Dynamic Programming\n\nThe chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagram:\nA chess knight can move as indicated in the chess diagram below:\nWe have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).\nGiven an integer n, return how many distinct phone numbers of length n we can dial.\nYou are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.\nAs the answer may be very large, return the answer modulo 109 + 7.\n\nExample 1:\nInput: n = 1\nOutput: 10\nExplanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.\n\nExample 2:\nInput: n = 2\nOutput: 20\nExplanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]\n\nExample 3:\nInput: n = 3131\nOutput: 136006598\nExplanation: Please take care of the mod.\n\nConstraints:\n- 1 <= n <= 5000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def knightDialer(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n def matrix_expo(A, K):\n result = [[int(i==j) for j in range(len(A))] \\\n for i in range(len(A))]\n while K:\n if K % 2:\n result = matrix_mult(result, A)\n A = matrix_mult(A, A)\n K /= 2\n return result\n\n def matrix_mult(A, B):\n ZB = zip(*B)\n return [[sum(a*b for a, b in itertools.izip(row, col)) % M \\\n for col in ZB] for row in A]\n \n M = 10**9 + 7\n T = [[0, 0, 0, 0, 1, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0, 1, 0],\n [0, 0, 0, 0, 0, 0, 0, 1, 0, 1],\n [0, 0, 0, 0, 1, 0, 0, 0, 1, 0],\n [1, 0, 0, 1, 0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 1, 0, 0, 0, 1, 0, 0, 0],\n [0, 1, 0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 1, 0, 0, 0, 0, 0]]\n return sum(map(sum, matrix_expo(T, N-1))) % M\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def knightDialer(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n M = 10**9 + 7\n moves = [[4, 6], [6, 8], [7, 9], [4, 8], [3, 9, 0], [],\n [1, 7, 0], [2, 6], [1, 3], [2, 4]]\n\n dp = [[1 for _ in range(10)] for _ in range(2)]\n for i in range(N-1):\n dp[(i+1) % 2] = [0] * 10\n for j in range(10):\n for nei in moves[j]:\n dp[(i+1) % 2][nei] += dp[i % 2][j]\n dp[(i+1) % 2][nei] %= M\n return sum(dp[(N-1) % 2]) % M\n"}} diff --git a/cp/cp-10411.jsonl b/cp/cp-10411.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ce71ad74b85a146e2a1fd1e8c2c98046a164c8bb --- /dev/null +++ b/cp/cp-10411.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10411", "name": "LeetCode 0936: Stamping The Sequence"} +{"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: Stamping The Sequence (Difficulty: Hard)\nTags: String, Stack, Greedy, Queue\n\nYou are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'.\nIn one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp.\nWe want to convert s to target using at most 10 * target.length turns.\nReturn an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns, return an empty array.\n\nExample 1:\nInput: stamp = \"abc\", target = \"ababc\"\nOutput: [0,2]\nExplanation: Initially s = \"?????\".\n- Place stamp at index 0 to get \"abc??\".\n- Place stamp at index 2 to get \"ababc\".\n[1,0,2] would also be accepted as an answer, as well as some other answers.\n\nExample 2:\nInput: stamp = \"abca\", target = \"aabcaca\"\nOutput: [3,0,1]\nExplanation: Initially s = \"???????\".\n- Place stamp at index 3 to get \"???abca\".\n- Place stamp at index 0 to get \"abcabca\".\n- Place stamp at index 1 to get \"aabcaca\".\n\nConstraints:\n- 1 <= stamp.length <= target.length <= 1000\n- stamp and target consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((n - m) * m)\n# Space: O((n - m) * m)\n\nimport collections\n\n\nclass Solution(object):\n def movesToStamp(self, stamp, target):\n M, N = len(stamp), len(target)\n\n q = collections.deque()\n lookup = [False]*N\n result = []\n A = []\n for i in range(N-M+1):\n made, todo = set(), set()\n for j, c in enumerate(stamp):\n if c == target[i+j]:\n made.add(i+j)\n else:\n todo.add(i+j)\n A.append((made, todo))\n if todo:\n continue\n result.append(i)\n for m in made:\n if lookup[m]:\n continue\n q.append(m)\n lookup[m] = True\n\n while q:\n i = q.popleft()\n for j in range(max(0, i-M+1), min(N-M, i)+1):\n made, todo = A[j]\n if i not in todo:\n continue\n todo.discard(i)\n if todo:\n continue\n result.append(j)\n for m in made:\n if lookup[m]:\n continue\n q.append(m)\n lookup[m] = True\n return result[::-1] if all(lookup) else []\n"}} diff --git a/cp/cp-10412.jsonl b/cp/cp-10412.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b0eb47e8db210a02d9f0f42f3902da3cf3589b18 --- /dev/null +++ b/cp/cp-10412.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10412", "name": "LeetCode 0937: Reorder Log Files"} +{"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: Reorder Data in Log Files (Difficulty: Medium)\nTags: Array, String, Sorting\n\nYou are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.\nThere are two types of logs:\nReorder these logs so that:\nReturn the final order of the logs.\n\nExample 1:\nInput: logs = [\"dig1 8 1 5 1\",\"let1 art can\",\"dig2 3 6\",\"let2 own kit dig\",\"let3 art zero\"]\nOutput: [\"let1 art can\",\"let3 art zero\",\"let2 own kit dig\",\"dig1 8 1 5 1\",\"dig2 3 6\"]\nExplanation:\nThe letter-log contents are all different, so their ordering is \"art can\", \"art zero\", \"own kit dig\".\nThe digit-logs have a relative order of \"dig1 8 1 5 1\", \"dig2 3 6\".\n\nExample 2:\nInput: logs = [\"a1 9 2 3 1\",\"g1 act car\",\"zo4 4 7\",\"ab1 off key dog\",\"a8 act zoo\"]\nOutput: [\"g1 act car\",\"a8 act zoo\",\"ab1 off key dog\",\"a1 9 2 3 1\",\"zo4 4 7\"]\n\nConstraints:\n- 1 <= logs.length <= 100\n- 3 <= logs[i].length <= 100\n- All the tokens of logs[i] are separated by a single space.\n- logs[i] is guaranteed to have an identifier and at least one word after the identifier."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn * l), n is the length of files, l is the average length of strings\n# Space: O(l)\n\nclass Solution(object):\n def reorderLogFiles(self, logs):\n \"\"\"\n :type logs: List[str]\n :rtype: List[str]\n \"\"\"\n def f(log):\n i, content = log.split(\" \", 1)\n return (0, content, i) if content[0].isalpha() else (1,)\n\n logs.sort(key=f)\n return logs\n"}} diff --git a/cp/cp-10413.jsonl b/cp/cp-10413.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b9d41b9209ec9ec8415f4220b1bafbca34830137 --- /dev/null +++ b/cp/cp-10413.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10413", "name": "LeetCode 0938: Range Sum Of 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: Range Sum of BST (Difficulty: Easy)\nTags: Tree, Depth-First Search, Binary Search Tree, Binary Tree\n\nGiven the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].\n\nExample 1:\nInput: root = [10,5,15,3,7,null,18], low = 7, high = 15\nOutput: 32\nExplanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.\n\nExample 2:\nInput: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10\nOutput: 23\nExplanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 2 * 10^4].\n- 1 <= Node.val <= 10^5\n- 1 <= low <= high <= 10^5\n- All Node.val are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 rangeSumBST(self, root, L, R):\n \"\"\"\n :type root: TreeNode\n :type L: int\n :type R: int\n :rtype: int\n \"\"\"\n result = 0\n s = [root]\n while s:\n node = s.pop()\n if node:\n if L <= node.val <= R:\n result += node.val\n if L < node.val:\n s.append(node.left)\n if node.val < R:\n s.append(node.right)\n return result\n"}} diff --git a/cp/cp-10414.jsonl b/cp/cp-10414.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1820ef02ba4f54ed714ac75bb60462bacc06a355 --- /dev/null +++ b/cp/cp-10414.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10414", "name": "LeetCode 0939: Minimum Area Rectangle"} +{"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: Minimum Area Rectangle (Difficulty: Medium)\nTags: Array, Hash Table, Math, Geometry, Sorting\n\nYou are given an array of points in the X-Y plane points where points[i] = [xi, yi].\nReturn the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0.\n\nExample 1:\nInput: points = [[1,1],[1,3],[3,1],[3,3],[2,2]]\nOutput: 4\n\nExample 2:\nInput: points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]\nOutput: 2\n\nConstraints:\n- 1 <= points.length <= 500\n- points[i].length == 2\n- 0 <= xi, yi <= 4 * 10^4\n- All the given points are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^1.5) on average\n# O(n^2) on worst\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def minAreaRect(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n nx = len(set(x for x, y in points))\n ny = len(set(y for x, y in points))\n\n p = collections.defaultdict(list)\n if nx > ny:\n for x, y in points:\n p[x].append(y)\n else:\n for x, y in points:\n p[y].append(x)\n\n lookup = {}\n result = float(\"inf\")\n for x in sorted(p):\n p[x].sort()\n for j in range(len(p[x])):\n for i in range(j):\n y1, y2 = p[x][i], p[x][j]\n if (y1, y2) in lookup:\n result = min(result, (x-lookup[y1, y2]) * (y2-y1))\n lookup[y1, y2] = x\n return result if result != float(\"inf\") else 0\n \n\n# Time: O(n^2)\n# Space: O(n)\nclass Solution2(object):\n def minAreaRect(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n lookup = set()\n result = float(\"inf\")\n for x1, y1 in points:\n for x2, y2 in lookup:\n if (x1, y2) in lookup and (x2, y1) in lookup:\n result = min(result, abs(x1-x2) * abs(y1-y2))\n lookup.add((x1, y1))\n return result if result != float(\"inf\") else 0\n"}} diff --git a/cp/cp-10415.jsonl b/cp/cp-10415.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1198dfaeb13b888ea8c931a7fa43180a08ab0a29 --- /dev/null +++ b/cp/cp-10415.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10415", "name": "LeetCode 0940: Distinct Subsequences 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: Distinct Subsequences II (Difficulty: Hard)\nTags: String, Dynamic Programming\n\nGiven a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 109 + 7.\n\nExample 1:\nInput: s = \"abc\"\nOutput: 7\nExplanation: The 7 distinct subsequences are \"a\", \"b\", \"c\", \"ab\", \"ac\", \"bc\", and \"abc\".\n\nExample 2:\nInput: s = \"aba\"\nOutput: 6\nExplanation: The 6 distinct subsequences are \"a\", \"b\", \"ab\", \"aa\", \"ba\", and \"aba\".\n\nExample 3:\nInput: s = \"aaa\"\nOutput: 3\nExplanation: The 3 distinct subsequences are \"a\", \"aa\" and \"aaa\".\n\nConstraints:\n- 1 <= s.length <= 2000\n- s consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def distinctSubseqII(self, S):\n \"\"\"\n :type S: str\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n result, dp = 0, [0]*26\n for c in S:\n result, dp[ord(c)-ord('a')] = (result+((result+1)-dp[ord(c)-ord('a')]))%MOD, (result+1)%MOD\n return result\n"}} diff --git a/cp/cp-10416.jsonl b/cp/cp-10416.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..79d4043765da161b5749c11349e3d59df27fbbfd --- /dev/null +++ b/cp/cp-10416.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10416", "name": "LeetCode 0941: Valid Mountain 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: Valid Mountain Array (Difficulty: Easy)\nTags: Array\n\nGiven an array of integers arr, return true if and only if it is a valid mountain array.\nRecall that arr is a mountain array if and only if:\n\nExample 1:\nInput: arr = [2,1]\nOutput: false\n\nExample 2:\nInput: arr = [3,5,5]\nOutput: false\n\nExample 3:\nInput: arr = [0,3,2,1]\nOutput: true\n\nConstraints:\n- 1 <= arr.length <= 10^4\n- 0 <= arr[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def validMountainArray(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: bool\n \"\"\"\n i = 0\n while i+1 < len(A) and A[i] < A[i+1]:\n i += 1\n j = len(A)-1\n while j-1 >= 0 and A[j-1] > A[j]:\n j -= 1\n return 0 < i == j < len(A)-1\n"}} diff --git a/cp/cp-10417.jsonl b/cp/cp-10417.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e004a01af5f87cf2861297e1f5846161d21bf4c1 --- /dev/null +++ b/cp/cp-10417.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10417", "name": "LeetCode 0942: Di String Match"} +{"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: DI String Match (Difficulty: Easy)\nTags: Array, Two Pointers, String, Greedy\n\nA permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:\nGiven a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.\n\nExample 1:\nInput: s = \"IDID\"\nOutput: [0,4,1,3,2]\n\nExample 2:\nInput: s = \"III\"\nOutput: [0,1,2,3]\n\nExample 3:\nInput: s = \"DDI\"\nOutput: [3,2,0,1]\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s[i] is either 'I' or 'D'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def diStringMatch(self, S):\n \"\"\"\n :type S: str\n :rtype: List[int]\n \"\"\"\n result = []\n left, right = 0, len(S)\n for c in S:\n if c == 'I':\n result.append(left)\n left += 1\n else:\n result.append(right)\n right -= 1\n result.append(left)\n return result\n"}} diff --git a/cp/cp-10418.jsonl b/cp/cp-10418.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..491523f4633049e137f632970af9b10e15a5a6f1 --- /dev/null +++ b/cp/cp-10418.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10418", "name": "LeetCode 0943: Find The Shortest Superstring"} +{"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 the Shortest Superstring (Difficulty: Hard)\nTags: Array, String, Dynamic Programming, Bit Manipulation, Bitmask\n\nGiven an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them.\nYou may assume that no string in words is a substring of another string in words.\n\nExample 1:\nInput: words = [\"alex\",\"loves\",\"leetcode\"]\nOutput: \"alexlovesleetcode\"\nExplanation: All permutations of \"alex\",\"loves\",\"leetcode\" would also be accepted.\n\nExample 2:\nInput: words = [\"catg\",\"ctaagt\",\"gcta\",\"ttca\",\"atgcatc\"]\nOutput: \"gctaagttcatgcatc\"\n\nConstraints:\n- 1 <= words.length <= 12\n- 1 <= words[i].length <= 20\n- words[i] consists of lowercase English letters.\n- All the strings of words are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2 * (l^2 + 2^n))\n# Space: O(n^2)\n\nclass Solution(object):\n def shortestSuperstring(self, A):\n \"\"\"\n :type A: List[str]\n :rtype: str\n \"\"\"\n n = len(A)\n overlaps = [[0]*n for _ in range(n)]\n for i, x in enumerate(A):\n for j, y in enumerate(A):\n for l in reversed(range(min(len(x), len(y)))):\n if y[:l].startswith(x[len(x)-l:]):\n overlaps[i][j] = l\n break\n\n dp = [[0]*n for _ in range(1<>bit) & 1) == 0:\n continue\n prev_mask = mask^(1<>i) & 1) == 0:\n continue\n value = dp[prev_mask][i] + overlaps[i][bit]\n if value > dp[mask][bit]:\n dp[mask][bit] = value\n prev[mask][bit] = i\n \n bit = max(range(n), key = dp[-1].__getitem__)\n words = []\n mask = (1< A[r][c]:\n result += 1\n break\n return result\n\n\n# Time: O(n * l)\n# Space: O(n)\nimport itertools\n\n\nclass Solution2(object):\n def minDeletionSize(self, A):\n \"\"\"\n :type A: List[str]\n :rtype: int\n \"\"\"\n result = 0\n for col in itertools.izip(*A):\n if any(col[i] > col[i+1] for i in range(len(col)-1)):\n result += 1\n return result\n"}} diff --git a/cp/cp-10420.jsonl b/cp/cp-10420.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e3f6ab2fb123ee258ff1376166675c9aee725a54 --- /dev/null +++ b/cp/cp-10420.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10420", "name": "LeetCode 0945: Minimum Increment To Make Array Unique"} +{"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: Minimum Increment to Make Array Unique (Difficulty: Medium)\nTags: Array, Greedy, Sorting, Counting\n\nYou are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1.\nReturn the minimum number of moves to make every value in nums unique.\nThe test cases are generated so that the answer fits in a 32-bit integer.\n\nExample 1:\nInput: nums = [1,2,2]\nOutput: 1\nExplanation: After 1 move, the array could be [1, 2, 3].\n\nExample 2:\nInput: nums = [3,2,1,2,1,7]\nOutput: 6\nExplanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7].\nIt can be shown that it is impossible for the array to have all unique values with 5 or less moves.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 0 <= nums[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass Solution(object):\n def minIncrementForUnique(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n A.sort()\n A.append(float(\"inf\"))\n result, duplicate = 0, 0\n for i in range(1, len(A)):\n if A[i-1] == A[i]:\n duplicate += 1\n result -= A[i]\n else:\n move = min(duplicate, A[i]-A[i-1]-1)\n duplicate -= move\n result += move*A[i-1] + move*(move+1)//2\n return result\n"}} diff --git a/cp/cp-10421.jsonl b/cp/cp-10421.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..918cc8368f9cf8925f761a2a52cac35e2ab15689 --- /dev/null +++ b/cp/cp-10421.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10421", "name": "LeetCode 0946: Validate Stack Sequences"} +{"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: Validate Stack Sequences (Difficulty: Medium)\nTags: Array, Stack, Simulation\n\nGiven two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.\n\nExample 1:\nInput: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]\nOutput: true\nExplanation: We might do the following sequence:\npush(1), push(2), push(3), push(4),\npop() -> 4,\npush(5),\npop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1\n\nExample 2:\nInput: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]\nOutput: false\nExplanation: 1 cannot be popped before 2.\n\nConstraints:\n- 1 <= pushed.length <= 1000\n- 0 <= pushed[i] <= 1000\n- All the elements of pushed are unique.\n- popped.length == pushed.length\n- popped is a permutation of pushed."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def validateStackSequences(self, pushed, popped):\n \"\"\"\n :type pushed: List[int]\n :type popped: List[int]\n :rtype: bool\n \"\"\"\n i = 0\n s = []\n for v in pushed:\n s.append(v)\n while s and i < len(popped) and s[-1] == popped[i]:\n s.pop()\n i += 1\n return i == len(popped)\n"}} diff --git a/cp/cp-10422.jsonl b/cp/cp-10422.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ea68a6b682b837e946c05aef9f85ab9db0f0a1bb --- /dev/null +++ b/cp/cp-10422.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10422", "name": "LeetCode 0947: Most Stones Removed With Same Row Or Column"} +{"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: Most Stones Removed with Same Row or Column (Difficulty: Medium)\nTags: Hash Table, Depth-First Search, Union Find, Graph\n\nOn a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.\nA stone can be removed if it shares either the same row or the same column as another stone that has not been removed.\nGiven an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.\n\nExample 1:\nInput: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]\nOutput: 5\nExplanation: One way to remove 5 stones is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,1].\n2. Remove stone [2,1] because it shares the same column as [0,1].\n3. Remove stone [1,2] because it shares the same row as [1,0].\n4. Remove stone [1,0] because it shares the same column as [0,0].\n5. Remove stone [0,1] because it shares the same row as [0,0].\nStone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.\n\nExample 2:\nInput: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]\nOutput: 3\nExplanation: One way to make 3 moves is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,0].\n2. Remove stone [2,0] because it shares the same column as [0,0].\n3. Remove stone [0,2] because it shares the same row as [0,0].\nStones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.\n\nExample 3:\nInput: stones = [[0,0]]\nOutput: 0\nExplanation: [0,0] is the only stone on the plane, so you cannot remove it.\n\nConstraints:\n- 1 <= stones.length <= 1000\n- 0 <= xi, yi <= 10^4\n- No two stones are at the same coordinate point."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n return True\n\n\nclass Solution(object):\n def removeStones(self, stones):\n \"\"\"\n :type stones: List[List[int]]\n :rtype: int\n \"\"\"\n MAX_ROW = 10000\n union_find = UnionFind(2*MAX_ROW)\n for r, c in stones:\n union_find.union_set(r, c+MAX_ROW)\n return len(stones) - len({union_find.find_set(r) for r, _ in stones})\n"}} diff --git a/cp/cp-10423.jsonl b/cp/cp-10423.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3078a1dcbe8d0ce29789a5fd02d59be1a4dc0d2f --- /dev/null +++ b/cp/cp-10423.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10423", "name": "LeetCode 0948: Bag Of Tokens"} +{"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: Bag of Tokens (Difficulty: Medium)\nTags: Array, Two Pointers, Greedy, Sorting\n\nYou start with an initial power of power, an initial score of 0, and a bag of tokens given as an integer array tokens, where each tokens[i] denotes the value of tokeni.\nYour goal is to maximize the total score by strategically playing these tokens. In one move, you can play an unplayed token in one of the two ways (but not both for the same token):\nReturn the maximum possible score you can achieve after playing any number of tokens.\n\nExample 1:\nInput: tokens = [100], power = 50\nOutput: 0\nExplanation : Since your score is 0 initially, you cannot play the token face-down. You also cannot play it face-up since your power ( 50 ) is less than tokens[0] ( 100 ).\n\nExample 2:\nInput: tokens = [200,100], power = 150\nOutput: 1\nExplanation: Play token 1 ( 100 ) face-up, reducing your power to 50 and increasing your score to 1 .\nThere is no need to play token 0 , since you cannot play it face-up to add to your score. The maximum score achievable is 1 .\n\nExample 3:\nInput: tokens = [100,200,300,400], power = 200\nOutput: 2\nExplanation: Play the tokens in this order to get a score of 2 :\nThe maximum score achievable is 2 .\n\nConstraints:\n- 0 <= tokens.length <= 1000\n- 0 <= tokens[i], power < 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def bagOfTokensScore(self, tokens, P):\n \"\"\"\n :type tokens: List[int]\n :type P: int\n :rtype: int\n \"\"\"\n tokens.sort()\n result, points = 0, 0\n left, right = 0, len(tokens)-1\n while left <= right:\n if P >= tokens[left]:\n P -= tokens[left]\n left += 1\n points += 1\n result = max(result, points)\n elif points > 0:\n points -= 1\n P += tokens[right]\n right -= 1\n else:\n break\n return result\n"}} diff --git a/cp/cp-10424.jsonl b/cp/cp-10424.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..939bb457faa0d01a914961b685ca8b3ac63e6bc6 --- /dev/null +++ b/cp/cp-10424.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10424", "name": "LeetCode 0949: Largest Time For Given Digits"} +{"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: Largest Time for Given Digits (Difficulty: Medium)\nTags: Array, String, Backtracking, Enumeration\n\nGiven an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.\n24-hour times are formatted as \"HH:MM\", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.\nReturn the latest 24-hour time in \"HH:MM\" format. If no valid time can be made, return an empty string.\n\nExample 1:\nInput: arr = [1,2,3,4]\nOutput: \"23:41\"\nExplanation: The valid 24-hour times are \"12:34\", \"12:43\", \"13:24\", \"13:42\", \"14:23\", \"14:32\", \"21:34\", \"21:43\", \"23:14\", and \"23:41\". Of these times, \"23:41\" is the latest.\n\nExample 2:\nInput: arr = [5,5,5,5]\nOutput: \"\"\nExplanation: There are no valid 24-hour times as \"55:55\" is not valid.\n\nConstraints:\n- arr.length == 4\n- 0 <= arr[i] <= 9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def largestTimeFromDigits(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: str\n \"\"\"\n result = \"\"\n for i in range(len(A)):\n A[i] *= -1\n A.sort()\n for h1, h2, m1, m2 in itertools.permutations(A):\n hours = -(10*h1 + h2)\n mins = -(10*m1 + m2)\n if 0 <= hours < 24 and 0 <= mins < 60:\n result = \"{:02}:{:02}\".format(hours, mins)\n break\n return result\n \n"}} diff --git a/cp/cp-10425.jsonl b/cp/cp-10425.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd6151cc4450a37409e31d0f17fbfada08a48e9c --- /dev/null +++ b/cp/cp-10425.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10425", "name": "LeetCode 0950: Reveal Cards In Increasing Order"} +{"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: Reveal Cards In Increasing Order (Difficulty: Medium)\nTags: Array, Queue, Sorting, Simulation\n\nYou are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i].\nYou can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.\nYou will do the following steps repeatedly until all cards are revealed:\nReturn an ordering of the deck that would reveal the cards in increasing order.\nNote that the first entry in the answer is considered to be the top of the deck.\n\nExample 1:\nInput: deck = [17,13,11,2,3,5,7]\nOutput: [2,13,3,11,5,17,7]\nExplanation: \nWe get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it.\nAfter reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.\nWe reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].\nWe reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].\nWe reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17].\nWe reveal 7, and move 13 to the bottom. The deck is now [11,17,13].\nWe reveal 11, and move 17 to the bottom. The deck is now [13,17].\nWe reveal 13, and move 17 to the bottom. The deck is now [17].\nWe reveal 17.\nSince all the cards revealed are in increasing order, the answer is correct.\n\nExample 2:\nInput: deck = [1,1000]\nOutput: [1,1000]\n\nConstraints:\n- 1 <= deck.length <= 1000\n- 1 <= deck[i] <= 10^6\n- All the values of deck are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def deckRevealedIncreasing(self, deck):\n \"\"\"\n :type deck: List[int]\n :rtype: List[int]\n \"\"\"\n d = collections.deque()\n deck.sort(reverse=True)\n for i in deck:\n if d:\n d.appendleft(d.pop())\n d.appendleft(i)\n return list(d)\n"}} diff --git a/cp/cp-10426.jsonl b/cp/cp-10426.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f5935b25daf129b9498e5b8904d35c185eaef085 --- /dev/null +++ b/cp/cp-10426.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10426", "name": "LeetCode 0951: Flip Equivalent 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: Flip Equivalent Binary Trees (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Tree\n\nFor a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.\nA binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.\nGiven the roots of two binary trees root1 and root2, return true if the two trees are flip equivalent or false otherwise.\n\nExample 1:\nInput: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]\nOutput: true\nExplanation: We flipped at nodes with values 1, 3, and 5.\n\nExample 2:\nInput: root1 = [], root2 = []\nOutput: true\n\nExample 3:\nInput: root1 = [], root2 = [1]\nOutput: false\n\nConstraints:\n- The number of nodes in each tree is in the range [0, 100].\n- Each tree will have unique node values in the range [0, 99]."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nimport collections\n\n\n# bfs solution\nclass Solution(object):\n def flipEquiv(self, root1, root2):\n \"\"\"\n :type root1: TreeNode\n :type root2: TreeNode\n :rtype: bool\n \"\"\"\n dq1, dq2 = collections.deque([root1]), collections.deque([root2])\n while dq1 and dq2:\n node1, node2 = dq1.pop(), dq2.pop()\n if not node1 and not node2:\n continue \n if not node1 or not node2 or node1.val != node2.val:\n return False\n if (not node1.left and not node2.right) or \\\n (node1.left and node2.right and node1.left.val == node2.right.val):\n dq1.extend([node1.right, node1.left])\n else:\n dq1.extend([node1.left, node1.right])\n dq2.extend([node2.left, node2.right])\n return not dq1 and not dq2\n\n\n# Time: O(n)\n# Space: O(h)\n# iterative dfs solution\nclass Solution2(object):\n def flipEquiv(self, root1, root2):\n \"\"\"\n :type root1: TreeNode\n :type root2: TreeNode\n :rtype: bool\n \"\"\"\n stk1, stk2 = [root1], [root2]\n while stk1 and stk2:\n node1, node2 = stk1.pop(), stk2.pop()\n if not node1 and not node2:\n continue \n if not node1 or not node2 or node1.val != node2.val:\n return False\n if (not node1.left and not node2.right) or \\\n (node1.left and node2.right and node1.left.val == node2.right.val):\n stk1.extend([node1.right, node1.left])\n else:\n stk1.extend([node1.left, node1.right])\n stk2.extend([node2.left, node2.right])\n return not stk1 and not stk2\n\n\n# Time: O(n)\n# Space: O(h)\n# recursive dfs solution\nclass Solution3(object):\n def flipEquiv(self, root1, root2):\n \"\"\"\n :type root1: TreeNode\n :type root2: TreeNode\n :rtype: bool\n \"\"\"\n if not root1 and not root2:\n return True\n if not root1 or not root2 or root1.val != root2.val:\n return False\n\n return (self.flipEquiv(root1.left, root2.left) and\n self.flipEquiv(root1.right, root2.right) or\n self.flipEquiv(root1.left, root2.right) and\n self.flipEquiv(root1.right, root2.left))\n"}} diff --git a/cp/cp-10427.jsonl b/cp/cp-10427.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b3190617ce797ba3941257a69cd7974682b948a8 --- /dev/null +++ b/cp/cp-10427.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10427", "name": "LeetCode 0952: Largest Component Size By Common Factor"} +{"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: Largest Component Size by Common Factor (Difficulty: Hard)\nTags: Array, Hash Table, Math, Union Find, Number Theory\n\nYou are given an integer array of unique positive integers nums. Consider the following graph:\nReturn the size of the largest connected component in the graph.\n\nExample 1:\nInput: nums = [4,6,15,35]\nOutput: 4\n\nExample 2:\nInput: nums = [20,50,9,63]\nOutput: 2\n\nExample 3:\nInput: nums = [2,3,6,7,4,12,21,39]\nOutput: 8\n\nConstraints:\n- 1 <= nums.length <= 2 * 10^4\n- 1 <= nums[i] <= 10^5\n- All the values of nums are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(f * n), f is the max number of unique prime factors\n# Space: O(p + n), p is the total number of unique primes\n\nimport collections\n\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n self.size = [1]*n\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n self.size[max(x_root, y_root)] += self.size[min(x_root, y_root)]\n return True\n\n\nclass Solution(object):\n def largestComponentSize(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n def prime_factors(i): # prime factor decomposition\n result = []\n d = 2\n if i%d == 0:\n while i%d == 0:\n i //= d\n result.append(d)\n d = 3\n while d*d <= i:\n if i%d == 0:\n while i%d == 0:\n i //= d\n result.append(d)\n d += 2\n if i != 1:\n result.append(i)\n return result\n \n union_find = UnionFind(len(A))\n nodesWithCommonFactor = collections.defaultdict(int)\n for i in range(len(A)):\n for factor in prime_factors(A[i]):\n if factor not in nodesWithCommonFactor:\n nodesWithCommonFactor[factor] = i\n union_find.union_set(nodesWithCommonFactor[factor], i)\n return max(union_find.size)\n\n\n# Time: O(f * n), f is the max number of unique prime factors\n# Space: O(p + n), p is the total number of unique primes\nimport collections\n\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n self.size = [1]*n\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n self.size[max(x_root, y_root)] += self.size[min(x_root, y_root)]\n return True\n\n\nclass Solution2(object):\n def largestComponentSize(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n def prime_factors(x): # prime factor decomposition\n result = []\n p = 2\n while p*p <= x:\n if x%p == 0:\n while x%p == 0:\n x //= p\n result.append(p)\n p += 1\n if x != 1:\n result.append(x)\n return result\n \n union_find = UnionFind(len(A))\n nodesWithCommonFactor = collections.defaultdict(int)\n for i in range(len(A)):\n for factor in prime_factors(A[i]):\n if factor not in nodesWithCommonFactor:\n nodesWithCommonFactor[factor] = i\n union_find.union_set(nodesWithCommonFactor[factor], i)\n return max(union_find.size)\n"}} diff --git a/cp/cp-10428.jsonl b/cp/cp-10428.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7de43e54cdedae7ae92182896b1f9c3ff5973d4b --- /dev/null +++ b/cp/cp-10428.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10428", "name": "LeetCode 0953: Verifying An Alien 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: Verifying an Alien Dictionary (Difficulty: Easy)\nTags: Array, Hash Table, String\n\nIn an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.\nGiven a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.\n\nExample 1:\nInput: words = [\"hello\",\"leetcode\"], order = \"hlabcdefgijkmnopqrstuvwxyz\"\nOutput: true\nExplanation: As 'h' comes before 'l' in this language, then the sequence is sorted.\n\nExample 2:\nInput: words = [\"word\",\"world\",\"row\"], order = \"worldabcefghijkmnpqstuvxyz\"\nOutput: false\nExplanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.\n\nExample 3:\nInput: words = [\"apple\",\"app\"], order = \"abcdefghijklmnopqrstuvwxyz\"\nOutput: false\nExplanation: The first three characters \"app\" match, and the second string is shorter (in size.) According to lexicographical rules \"apple\" > \"app\", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).\n\nConstraints:\n- 1 <= words.length <= 100\n- 1 <= words[i].length <= 20\n- order.length == 26\n- All characters in words[i] and order are English lowercase letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * l), l is the average length of words\n# Space: O(1)\n\nclass Solution(object):\n def isAlienSorted(self, words, order):\n \"\"\"\n :type words: List[str]\n :type order: str\n :rtype: bool\n \"\"\"\n lookup = {c: i for i, c in enumerate(order)}\n for i in range(len(words)-1):\n word1 = words[i]\n word2 = words[i+1]\n for k in range(min(len(word1), len(word2))):\n if word1[k] != word2[k]:\n if lookup[word1[k]] > lookup[word2[k]]:\n return False\n break\n else:\n if len(word1) > len(word2):\n return False\n return True\n"}} diff --git a/cp/cp-10429.jsonl b/cp/cp-10429.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c2e799824df343d87f325373bb3977f12f9aa906 --- /dev/null +++ b/cp/cp-10429.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10429", "name": "LeetCode 0954: Array Of Doubled 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: Array of Doubled Pairs (Difficulty: Medium)\nTags: Array, Hash Table, Greedy, Sorting\n\nGiven an integer array of even length arr, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise.\n\nExample 1:\nInput: arr = [3,1,3,6]\nOutput: false\n\nExample 2:\nInput: arr = [2,1,2,6]\nOutput: false\n\nExample 3:\nInput: arr = [4,-2,2,-4]\nOutput: true\nExplanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].\n\nConstraints:\n- 2 <= arr.length <= 3 * 10^4\n- arr.length is even.\n- -10^5 <= arr[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + klogk)\n# Space: O(k)\n\nimport collections\n\n\nclass Solution(object):\n def canReorderDoubled(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: bool\n \"\"\"\n count = collections.Counter(A)\n for x in sorted(count, key=abs):\n if count[x] > count[2*x]:\n return False\n count[2*x] -= count[x]\n return True\n"}} diff --git a/cp/cp-10430.jsonl b/cp/cp-10430.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..26671019d3ebcfa4485b216e9696dcf99f523e43 --- /dev/null +++ b/cp/cp-10430.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10430", "name": "LeetCode 0955: Delete Columns To Make Sorted 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: Delete Columns to Make Sorted II (Difficulty: Medium)\nTags: Array, String, Greedy\n\nYou are given an array of n strings strs, all of the same length.\nWe may choose any deletion indices, and we delete all the characters in those indices for each string.\nFor example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3}, then the final array after deletions is [\"bef\", \"vyz\"].\nSuppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]). Return the minimum possible value of answer.length.\n\nExample 1:\nInput: strs = [\"ca\",\"bb\",\"ac\"]\nOutput: 1\nExplanation: \nAfter deleting the first column, strs = [\"a\", \"b\", \"c\"].\nNow strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).\nWe require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.\n\nExample 2:\nInput: strs = [\"xc\",\"yb\",\"za\"]\nOutput: 0\nExplanation: \nstrs is already in lexicographic order, so we do not need to delete anything.\nNote that the rows of strs are not necessarily in lexicographic order:\ni.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...)\n\nExample 3:\nInput: strs = [\"zyx\",\"wvu\",\"tsr\"]\nOutput: 3\nExplanation: We have to delete every column.\n\nConstraints:\n- n == strs.length\n- 1 <= n <= 100\n- 1 <= strs[i].length <= 100\n- strs[i] consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * l)\n# Space: O(n)\n\nclass Solution(object):\n def minDeletionSize(self, A):\n \"\"\"\n :type A: List[str]\n :rtype: int\n \"\"\"\n result = 0\n unsorted = set(range(len(A)-1))\n for j in range(len(A[0])):\n if any(A[i][j] > A[i+1][j] for i in unsorted):\n result += 1\n else:\n unsorted -= set(i for i in unsorted if A[i][j] < A[i+1][j])\n return result\n\n\n# Time: O(n * m)\n# Space: O(n)\nclass Solution2(object):\n def minDeletionSize(self, A):\n \"\"\"\n :type A: List[str]\n :rtype: int\n \"\"\"\n result = 0\n is_sorted = [False]*(len(A)-1)\n for j in range(len(A[0])):\n tmp = is_sorted[:]\n for i in range(len(A)-1):\n if A[i][j] > A[i+1][j] and tmp[i] == False:\n result += 1\n break\n if A[i][j] < A[i+1][j]:\n tmp[i] = True\n else:\n is_sorted = tmp\n return result\n"}} diff --git a/cp/cp-10431.jsonl b/cp/cp-10431.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..39c3ae92dd62a58889ecfee435b59bda52f5764d --- /dev/null +++ b/cp/cp-10431.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10431", "name": "LeetCode 0956: Tallest Billboard"} +{"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: Tallest Billboard (Difficulty: Hard)\nTags: Array, Dynamic Programming\n\nYou are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.\nYou are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.\nReturn the largest possible height of your billboard installation. If you cannot support the billboard, return 0.\n\nExample 1:\nInput: rods = [1,2,3,6]\nOutput: 6\nExplanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.\n\nExample 2:\nInput: rods = [1,2,3,4,5,6]\nOutput: 10\nExplanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.\n\nExample 3:\nInput: rods = [1,2]\nOutput: 0\nExplanation: The billboard cannot be supported, so we return 0.\n\nConstraints:\n- 1 <= rods.length <= 20\n- 1 <= rods[i] <= 1000\n- sum(rods[i]) <= 5000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * 3^(n/2))\n# Space: O(3^(n/2))\n\nimport collections\n\n\nclass Solution(object):\n def tallestBillboard(self, rods):\n \"\"\"\n :type rods: List[int]\n :rtype: int\n \"\"\"\n def dp(A):\n lookup = collections.defaultdict(int)\n lookup[0] = 0\n for x in A:\n for d, y in lookup.items():\n lookup[d+x] = max(lookup[d+x], y)\n lookup[abs(d-x)] = max(lookup[abs(d-x)], y + min(d, x))\n return lookup\n\n left, right = dp(rods[:len(rods)//2]), dp(rods[len(rods)//2:])\n return max(left[d]+right[d]+d for d in left if d in right)\n"}} diff --git a/cp/cp-10432.jsonl b/cp/cp-10432.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f44d06143881ed4cd92b16d7312bf51483cd2f7f --- /dev/null +++ b/cp/cp-10432.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10432", "name": "LeetCode 0957: Prison Cells After N Days"} +{"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: Prison Cells After N Days (Difficulty: Medium)\nTags: Array, Hash Table, Math, Bit Manipulation\n\nThere are 8 prison cells in a row and each cell is either occupied or vacant.\nEach day, whether the cell is occupied or vacant changes according to the following rules:\nNote that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.\nYou are given an integer array cells where cells[i] == 1 if the ith cell is occupied and cells[i] == 0 if the ith cell is vacant, and you are given an integer n.\nReturn the state of the prison after n days (i.e., n such changes described above).\n\nExample 1:\nInput: cells = [0,1,0,1,1,0,0,1], n = 7\nOutput: [0,0,1,1,0,0,0,0]\nExplanation: The following table summarizes the state of the prison on each day:\nDay 0: [0, 1, 0, 1, 1, 0, 0, 1]\nDay 1: [0, 1, 1, 0, 0, 0, 0, 0]\nDay 2: [0, 0, 0, 0, 1, 1, 1, 0]\nDay 3: [0, 1, 1, 0, 0, 1, 0, 0]\nDay 4: [0, 0, 0, 0, 0, 1, 0, 0]\nDay 5: [0, 1, 1, 1, 0, 1, 0, 0]\nDay 6: [0, 0, 1, 0, 1, 1, 0, 0]\nDay 7: [0, 0, 1, 1, 0, 0, 0, 0]\n\nExample 2:\nInput: cells = [1,0,0,1,0,0,1,0], n = 1000000000\nOutput: [0,0,1,1,1,1,1,0]\n\nConstraints:\n- cells.length == 8\n- cells[i] is either 0 or 1.\n- 1 <= n <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def prisonAfterNDays(self, cells, N):\n \"\"\"\n :type cells: List[int]\n :type N: int\n :rtype: List[int]\n \"\"\"\n N -= max(N-1, 0) // 14 * 14 # 14 is got from Solution2\n for i in range(N):\n cells = [0] + [cells[i-1] ^ cells[i+1] ^ 1 for i in range(1, 7)] + [0]\n return cells\n\n\n# Time: O(1)\n# Space: O(1)\nclass Solution2(object):\n def prisonAfterNDays(self, cells, N):\n \"\"\"\n :type cells: List[int]\n :type N: int\n :rtype: List[int]\n \"\"\"\n cells = tuple(cells)\n lookup = {}\n while N:\n lookup[cells] = N\n N -= 1\n cells = tuple([0] + [cells[i - 1] ^ cells[i + 1] ^ 1 for i in range(1, 7)] + [0])\n if cells in lookup:\n assert(lookup[cells] - N in (1, 7, 14))\n N %= lookup[cells] - N\n break\n\n while N:\n N -= 1\n cells = tuple([0] + [cells[i - 1] ^ cells[i + 1] ^ 1 for i in range(1, 7)] + [0])\n return list(cells)\n"}} diff --git a/cp/cp-10433.jsonl b/cp/cp-10433.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..57799e73d50742926babfab9af4a5c9615e1f137 --- /dev/null +++ b/cp/cp-10433.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10433", "name": "LeetCode 0958: Check Completeness Of 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: Check Completeness of a Binary Tree (Difficulty: Medium)\nTags: Tree, Breadth-First Search, Binary Tree\n\nGiven the root of a binary tree, determine if it is a complete binary tree.\nIn a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.\n\nExample 1:\nInput: root = [1,2,3,4,5,6]\nOutput: true\nExplanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.\n\nExample 2:\nInput: root = [1,2,3,4,5,null,7]\nOutput: false\nExplanation: The node with value 7 isn't as far left as possible.\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 100].\n- 1 <= Node.val <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(w)\n\n# Definition for a binary tree node.\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 isCompleteTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n end = False\n current = [root]\n while current:\n next_level = []\n for node in current:\n if not node:\n end = True\n continue\n if end:\n return False\n next_level.append(node.left)\n next_level.append(node.right)\n current = next_level\n return True\n\n\n# Time: O(n)\n# Space: O(w)\nclass Solution2(object):\n def isCompleteTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n prev_level, current = [], [(root, 1)]\n count = 0\n while current:\n count += len(current)\n next_level = []\n for node, v in current:\n if not node:\n continue\n next_level.append((node.left, 2*v))\n next_level.append((node.right, 2*v+1))\n prev_level, current = current, next_level\n return prev_level[-1][1] == count\n"}} diff --git a/cp/cp-10434.jsonl b/cp/cp-10434.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9693382666109998c03e30d73d4ce28df163c877 --- /dev/null +++ b/cp/cp-10434.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10434", "name": "LeetCode 0959: Regions Cut By Slashes"} +{"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: Regions Cut By Slashes (Difficulty: Medium)\nTags: Array, Hash Table, Depth-First Search, Breadth-First Search, Union Find, Matrix\n\nAn n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\\', or blank space ' '. These characters divide the square into contiguous regions.\nGiven the grid grid represented as a string array, return the number of regions.\nNote that backslash characters are escaped, so a '\\' is represented as '\\\\'.\n\nExample 1:\nInput: grid = [\" /\",\"/ \"]\nOutput: 2\n\nExample 2:\nInput: grid = [\" /\",\" \"]\nOutput: 1\n\nExample 3:\nInput: grid = [\"/\\\\\",\"\\\\/\"]\nOutput: 5\nExplanation: Recall that because \\ characters are escaped, \"\\\\/\" refers to \\/, and \"/\\\\\" refers to /\\.\n\nConstraints:\n- n == grid.length == grid[i].length\n- 1 <= n <= 30\n- grid[i][j] is either '/', '\\', or ' '."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2)\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n self.count = n\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root != y_root:\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n self.count -= 1\n\n\nclass Solution(object):\n def regionsBySlashes(self, grid):\n \"\"\"\n :type grid: List[str]\n :rtype: int\n \"\"\"\n def index(n, i, j, k):\n return (i*n + j)*4 + k\n \n union_find = UnionFind(len(grid)**2 * 4)\n N, E, S, W = range(4)\n for i in range(len(grid)):\n for j in range(len(grid)):\n if i:\n union_find.union_set(index(len(grid), i-1, j, S),\n index(len(grid),i, j, N))\n if j:\n union_find.union_set(index(len(grid), i, j-1, E),\n index(len(grid), i, j, W))\n if grid[i][j] != \"/\":\n union_find.union_set(index(len(grid), i, j, N),\n index(len(grid), i, j, E))\n union_find.union_set(index(len(grid), i, j, S),\n index(len(grid), i, j, W))\n if grid[i][j] != \"\\\\\":\n union_find.union_set(index(len(grid), i, j, W),\n index(len(grid), i, j, N))\n union_find.union_set(index(len(grid), i, j, E),\n index(len(grid), i, j, S))\n return union_find.count\n"}} diff --git a/cp/cp-10435.jsonl b/cp/cp-10435.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fe13bde4d632f587138cd823c2463bb07f4bba01 --- /dev/null +++ b/cp/cp-10435.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10435", "name": "LeetCode 0960: Delete Columns To Make Sorted 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: Delete Columns to Make Sorted III (Difficulty: Hard)\nTags: Array, String, Dynamic Programming\n\nYou are given an array of n strings strs, all of the same length.\nWe may choose any deletion indices, and we delete all the characters in those indices for each string.\nFor example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3}, then the final array after deletions is [\"bef\", \"vyz\"].\nSuppose we chose a set of deletion indices answer such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]), and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), and so on). Return the minimum possible value of answer.length.\n\nExample 1:\nInput: strs = [\"babca\",\"bbazb\"]\nOutput: 3\nExplanation: After deleting columns 0, 1, and 4, the final array is strs = [\"bc\", \"az\"].\nBoth these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]).\nNote that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order.\n\nExample 2:\nInput: strs = [\"edcba\"]\nOutput: 4\nExplanation: If we delete less than 4 columns, the only row will not be lexicographically sorted.\n\nExample 3:\nInput: strs = [\"ghi\",\"def\",\"abc\"]\nOutput: 0\nExplanation: All rows are already lexicographically sorted.\n\nConstraints:\n- n == strs.length\n- 1 <= n <= 100\n- 1 <= strs[i].length <= 100\n- strs[i] consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * l^2)\n# Space: O(l)\n\nclass Solution(object):\n def minDeletionSize(self, A):\n \"\"\"\n :type A: List[str]\n :rtype: int\n \"\"\"\n dp = [1] * len(A[0])\n for j in range(1, len(A[0])):\n for i in range(j):\n if all(A[k][i] <= A[k][j] for k in range(len(A))):\n dp[j] = max(dp[j], dp[i]+1)\n return len(A[0]) - max(dp)\n"}} diff --git a/cp/cp-10437.jsonl b/cp/cp-10437.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eda0b796c9ed08dfa174069048b0396a31d3504d --- /dev/null +++ b/cp/cp-10437.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10437", "name": "LeetCode 0962: Maximum Width Ramp"} +{"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 Ramp (Difficulty: Medium)\nTags: Array, Two Pointers, Stack, Monotonic Stack\n\nA ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i.\nGiven an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0.\n\nExample 1:\nInput: nums = [6,0,8,2,1,5]\nOutput: 4\nExplanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.\n\nExample 2:\nInput: nums = [9,8,1,0,1,9,4,0,4,1]\nOutput: 7\nExplanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.\n\nConstraints:\n- 2 <= nums.length <= 5 * 10^4\n- 0 <= nums[i] <= 5 * 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def maxWidthRamp(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n result = 0\n s = []\n for i in A:\n if not s or A[s[-1]] > A[i]:\n s.append(i)\n for j in reversed(range(len(A))):\n while s and A[s[-1]] <= A[j]:\n result = max(result, j-s.pop())\n return result\n"}} diff --git a/cp/cp-10438.jsonl b/cp/cp-10438.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..816afaa72a1d3dcef2919eeece5c9fb770543592 --- /dev/null +++ b/cp/cp-10438.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10438", "name": "LeetCode 0963: Minimum Area Rectangle 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: Minimum Area Rectangle II (Difficulty: Medium)\nTags: Array, Hash Table, Math, Geometry\n\nYou are given an array of points in the X-Y plane points where points[i] = [xi, yi].\nReturn the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes. If there is not any such rectangle, return 0.\nAnswers within 10-5 of the actual answer will be accepted.\n\nExample 1:\nInput: points = [[1,2],[2,1],[1,0],[0,1]]\nOutput: 2.00000\nExplanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.\n\nExample 2:\nInput: points = [[0,1],[2,1],[1,1],[1,0],[2,0]]\nOutput: 1.00000\nExplanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.\n\nExample 3:\nInput: points = [[0,3],[1,2],[3,1],[1,3],[2,1]]\nOutput: 0\nExplanation: There is no possible rectangle to form from these points.\n\nConstraints:\n- 1 <= points.length <= 50\n- points[i].length == 2\n- 0 <= xi, yi <= 4 * 10^4\n- All the given points are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2) ~ O(n^3)\n# Space: O(n^2)\n\nimport collections\nimport itertools\n\n\nclass Solution(object):\n def minAreaFreeRect(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: float\n \"\"\"\n points.sort()\n points = [complex(*z) for z in points]\n lookup = collections.defaultdict(list)\n for P, Q in itertools.combinations(points, 2):\n lookup[P-Q].append((P+Q) / 2)\n\n result = float(\"inf\")\n for A, candidates in lookup.iteritems():\n for P, Q in itertools.combinations(candidates, 2):\n if A.real * (P-Q).real + A.imag * (P-Q).imag == 0.0:\n result = min(result, abs(A) * abs(P-Q))\n return result if result < float(\"inf\") else 0.0\n"}} diff --git a/cp/cp-10439.jsonl b/cp/cp-10439.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0c98e47ddfcfc1d69c5b57fc57e383f14fc2c52d --- /dev/null +++ b/cp/cp-10439.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10439", "name": "LeetCode 0964: Least Operators To Express 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: Least Operators to Express Number (Difficulty: Hard)\nTags: Math, Dynamic Programming, Memoization\n\nGiven a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3.\nWhen writing such an expression, we adhere to the following conventions:\nWe would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.\n\nExample 1:\nInput: x = 3, target = 19\nOutput: 5\nExplanation: 3 * 3 + 3 * 3 + 3 / 3.\nThe expression contains 5 operations.\n\nExample 2:\nInput: x = 5, target = 501\nOutput: 8\nExplanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.\nThe expression contains 8 operations.\n\nExample 3:\nInput: x = 100, target = 100000000\nOutput: 3\nExplanation: 100 * 100 * 100 * 100.\nThe expression contains 3 operations.\n\nConstraints:\n- 2 <= x <= 100\n- 1 <= target <= 2 * 10^8"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn/logx) = O(1)\n# Space: O(logn) = O(1)\n\nclass Solution(object):\n def leastOpsExpressTarget(self, x, target):\n \"\"\"\n :type x: int\n :type target: int\n :rtype: int\n \"\"\"\n pos, neg, k = 0, 0, 0\n while target:\n target, r = divmod(target, x)\n if k:\n pos, neg = min(r*k + pos, (r+1)*k + neg), \\\n min((x-r)*k + pos, (x-r-1)*k + neg)\n else:\n pos, neg = r*2, (x-r)*2\n k += 1\n return min(pos, k+neg) - 1\n"}} diff --git a/cp/cp-10440.jsonl b/cp/cp-10440.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..663d3e7a23434740d861d80c9a8e5a6a594d934d --- /dev/null +++ b/cp/cp-10440.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10440", "name": "LeetCode 0965: Univalued 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: Univalued Binary Tree (Difficulty: Easy)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nA binary tree is uni-valued if every node in the tree has the same value.\nGiven the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.\n\nExample 1:\nInput: root = [1,1,1,1,1,null,1]\nOutput: true\n\nExample 2:\nInput: root = [2,2,2,5,2]\nOutput: false\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 100].\n- 0 <= Node.val < 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 isUnivalTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n s = [root]\n while s:\n node = s.pop()\n if not node:\n continue\n if node.val != root.val:\n return False\n s.append(node.left)\n s.append(node.right)\n return True\n \n\n# Time: O(n)\n# Space: O(h)\nclass Solution2(object):\n def isUnivalTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n return (not root.left or (root.left.val == root.val and self.isUnivalTree(root.left))) and \\\n (not root.right or (root.right.val == root.val and self.isUnivalTree(root.right)))\n"}} diff --git a/cp/cp-10441.jsonl b/cp/cp-10441.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..afe27a8c3414559cd78109654e20bf96e9dee335 --- /dev/null +++ b/cp/cp-10441.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10441", "name": "LeetCode 0966: Vowel Spellchecker"} +{"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: Vowel Spellchecker (Difficulty: Medium)\nTags: Array, Hash Table, String\n\nGiven a wordlist, we want to implement a spellchecker that converts a query word into a correct word.\nFor a given query word, the spell checker handles two categories of spelling mistakes:\nIn addition, the spell checker operates under the following precedence rules:\nGiven some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].\n\nExample 1:\nInput: wordlist = [\"KiTe\",\"kite\",\"hare\",\"Hare\"], queries = [\"kite\",\"Kite\",\"KiTe\",\"Hare\",\"HARE\",\"Hear\",\"hear\",\"keti\",\"keet\",\"keto\"]\nOutput: [\"kite\",\"KiTe\",\"KiTe\",\"Hare\",\"hare\",\"\",\"\",\"KiTe\",\"\",\"KiTe\"]\n\nExample 2:\nInput: wordlist = [\"yellow\"], queries = [\"YellOw\"]\nOutput: [\"yellow\"]\n\nConstraints:\n- 1 <= wordlist.length, queries.length <= 5000\n- 1 <= wordlist[i].length, queries[i].length <= 7\n- wordlist[i] and queries[i] consist only of only English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(w)\n\nclass Solution(object):\n def spellchecker(self, wordlist, queries):\n \"\"\"\n :type wordlist: List[str]\n :type queries: List[str]\n :rtype: List[str]\n \"\"\"\n vowels = set(['a', 'e', 'i', 'o', 'u'])\n def todev(word):\n return \"\".join('*' if c.lower() in vowels else c.lower()\n for c in word)\n\n words = set(wordlist)\n caps = {}\n vows = {}\n\n for word in wordlist:\n caps.setdefault(word.lower(), word)\n vows.setdefault(todev(word), word)\n\n def check(query):\n if query in words:\n return query\n lower = query.lower()\n if lower in caps:\n return caps[lower]\n devow = todev(lower)\n if devow in vows:\n return vows[devow]\n return \"\"\n return map(check, queries)\n"}} diff --git a/cp/cp-10442.jsonl b/cp/cp-10442.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a2b7f84e9355c1e977b445e8bd301321f9869f26 --- /dev/null +++ b/cp/cp-10442.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10442", "name": "LeetCode 0967: Numbers With Same Consecutive Differences"} +{"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: Numbers With Same Consecutive Differences (Difficulty: Medium)\nTags: Backtracking, Breadth-First Search\n\nGiven two integers n and k, return an array of all the integers of length n where the difference between every two consecutive digits is k. You may return the answer in any order.\nNote that the integers should not have leading zeros. Integers as 02 and 043 are not allowed.\n\nExample 1:\nInput: n = 3, k = 7\nOutput: [181,292,707,818,929]\nExplanation: Note that 070 is not a valid number, because it has leading zeroes.\n\nExample 2:\nInput: n = 2, k = 1\nOutput: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]\n\nConstraints:\n- 2 <= n <= 9\n- 0 <= k <= 9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(2^n)\n# Space: O(2^n)\n\nclass Solution(object):\n def numsSameConsecDiff(self, N, K):\n \"\"\"\n :type N: int\n :type K: int\n :rtype: List[int]\n \"\"\"\n curr = range(10)\n for i in range(N-1):\n curr = [x*10 + y for x in curr for y in set([x%10 + K, x%10 - K]) \n if x and 0 <= y < 10]\n return curr\n"}} diff --git a/cp/cp-10443.jsonl b/cp/cp-10443.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dacd90ccea1bc5d1ed19cbfca7ae4d5da131d8c2 --- /dev/null +++ b/cp/cp-10443.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10443", "name": "LeetCode 0968: Binary Tree Cameras"} +{"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: Binary Tree Cameras (Difficulty: Hard)\nTags: Dynamic Programming, Tree, Depth-First Search, Binary Tree\n\nYou are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.\nReturn the minimum number of cameras needed to monitor all nodes of the tree.\n\nExample 1:\nInput: root = [0,0,null,0,0]\nOutput: 1\nExplanation: One camera is enough to monitor all nodes if placed as shown.\n\nExample 2:\nInput: root = [0,0,null,0,null,0,null,null,0]\nOutput: 2\nExplanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 1000].\n- Node.val == 0"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 minCameraCover(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n UNCOVERED, COVERED, CAMERA = range(3)\n def dfs(root, result):\n left = dfs(root.left, result) if root.left else COVERED\n right = dfs(root.right, result) if root.right else COVERED\n if left == UNCOVERED or right == UNCOVERED:\n result[0] += 1\n return CAMERA\n if left == CAMERA or right == CAMERA:\n return COVERED\n return UNCOVERED\n \n result = [0]\n if dfs(root, result) == UNCOVERED:\n result[0] += 1\n return result[0]\n"}} diff --git a/cp/cp-10444.jsonl b/cp/cp-10444.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4b830b5f8c2c74e954890b83cf2ad549926ae1c7 --- /dev/null +++ b/cp/cp-10444.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10444", "name": "LeetCode 0969: Pancake Sorting"} +{"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: Pancake Sorting (Difficulty: Medium)\nTags: Array, Two Pointers, Greedy, Sorting\n\nGiven an array of integers arr, sort the array by performing a series of pancake flips.\nIn one pancake flip we do the following steps:\nFor example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3.\nReturn an array of the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct.\n\nExample 1:\nInput: arr = [3,2,4,1]\nOutput: [4,2,4,3]\nExplanation: \nWe perform 4 pancake flips, with k values 4, 2, 4, and 3.\nStarting state: arr = [3, 2, 4, 1]\nAfter 1st flip (k = 4): arr = [1, 4, 2, 3]\nAfter 2nd flip (k = 2): arr = [4, 1, 2, 3]\nAfter 3rd flip (k = 4): arr = [3, 2, 1, 4]\nAfter 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted.\n\nExample 2:\nInput: arr = [1,2,3]\nOutput: []\nExplanation: The input is already sorted, so there is no need to flip anything.\nNote that other answers, such as [3, 3], would also be accepted.\n\nConstraints:\n- 1 <= arr.length <= 100\n- 1 <= arr[i] <= arr.length\n- All integers in arr are unique (i.e. arr is a permutation of the integers from 1 to arr.length)."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass BIT(object): # 0-indexed.\n def __init__(self, n):\n self.__bit = [0]*(n+1) # Extra one for dummy node.\n\n def add(self, i, val):\n i += 1 # Extra one for dummy node.\n while i < len(self.__bit):\n self.__bit[i] += val\n i += (i & -i)\n\n def query(self, i):\n i += 1 # Extra one for dummy node.\n ret = 0\n while i > 0:\n ret += self.__bit[i]\n i -= (i & -i)\n return ret\n\n# bit solution\nclass Solution(object):\n def pancakeSort(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: List[int]\n \"\"\"\n bit = BIT(len(arr))\n result = []\n for i in range(len(arr)):\n n = bit.query((arr[i]-1)-1)\n bit.add(arr[i]-1, 1)\n if n == i: # already sorted\n continue\n if n == 0: # (0..i-1)i\n if i > 1:\n result.append(i) # (i-1..0)i\n result.append(i+1) # i(0..i-1)\n else: # (0..n-1)n(n+1..i-1)i\n if n > 1:\n result.append(n) # (n-1..0)n(n+1..i-1)i\n result.append(i) # (i-1..n+1)n(0..n-1)i\n result.append(i+1) # i(n-1..0)n(n+1..i-1)\n result.append(n+1) # (0..n-1)in(n+1..i-1)\n return result\n\n\n# Time: O(nlogn)\n# Space: O(n)\n# merge sort solution\nclass Solution2(object):\n def pancakeSort(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: List[int]\n \"\"\"\n def smallerMergeSort(idxs, start, end, counts):\n if end - start <= 0: # The size of range [start, end] less than 2 is always with count 0.\n return 0\n\n mid = start + (end - start) // 2\n smallerMergeSort(idxs, start, mid, counts)\n smallerMergeSort(idxs, mid + 1, end, counts)\n r = start\n tmp = []\n for i in range(mid+1, end + 1):\n # Merge the two sorted arrays into tmp.\n while r <= mid and idxs[r][0] < idxs[i][0]:\n tmp.append(idxs[r])\n r += 1\n if r <= mid:\n tmp.append(idxs[i])\n counts[idxs[i][1]] += r - start\n while r <= mid:\n tmp.append(idxs[r])\n r += 1\n # Copy tmp back to idxs\n idxs[start:start+len(tmp)] = tmp\n \n idxs = []\n smaller_counts = [0]*len(arr)\n for i, x in enumerate(arr):\n idxs.append((x, i))\n smallerMergeSort(idxs, 0, len(idxs)-1, smaller_counts)\n result = []\n for i, n in enumerate(smaller_counts):\n if n == i: # already sorted\n continue\n if n == 0: # (0..i-1)i\n if i > 1:\n result.append(i) # (i-1..0)i\n result.append(i+1) # i(0..i-1)\n else: # (0..n-1)n(n+1..i-1)i\n if n > 1:\n result.append(n) # (n-1..0)n(n+1..i-1)i\n result.append(i) # (i-1..n+1)n(0..n-1)i\n result.append(i+1) # i(n-1..0)n(n+1..i-1)\n result.append(n+1) # (0..n-1)in(n+1..i-1)\n return result\n\n\n# Time: O(n^2)\n# Space: O(1)\nclass Solution3(object):\n def pancakeSort(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: List[int]\n \"\"\"\n def reverse(l, begin, end):\n for i in range((end-begin) // 2):\n l[begin+i], l[end-1-i] = l[end-1-i], l[begin+i]\n\n result = []\n for n in reversed(range(1, len(A)+1)):\n i = A.index(n)\n reverse(A, 0, i+1)\n result.append(i+1)\n reverse(A, 0, n)\n result.append(n)\n return result\n"}} diff --git a/cp/cp-10445.jsonl b/cp/cp-10445.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5eee28b14da16b160d32c610c4f76eab4c3634c5 --- /dev/null +++ b/cp/cp-10445.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10445", "name": "LeetCode 0970: Powerful Integers"} +{"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: Powerful Integers (Difficulty: Medium)\nTags: Hash Table, Math, Enumeration\n\nGiven three integers x, y, and bound, return a list of all the powerful integers that have a value less than or equal to bound.\nAn integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0.\nYou may return the answer in any order. In your answer, each value should occur at most once.\n\nExample 1:\nInput: x = 2, y = 3, bound = 10\nOutput: [2,3,4,5,7,9,10]\nExplanation:\n2 = 20 + 30\n3 = 21 + 30\n4 = 20 + 31\n5 = 21 + 31\n7 = 22 + 31\n9 = 23 + 30\n10 = 20 + 32\n\nExample 2:\nInput: x = 3, y = 5, bound = 15\nOutput: [2,4,6,8,10,14]\n\nConstraints:\n- 1 <= x, y <= 100\n- 0 <= bound <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((logn)^2), n is the bound\n# Space: O(r), r is the size of the result\n\nimport math\n\n\nclass Solution(object):\n def powerfulIntegers(self, x, y, bound):\n \"\"\"\n :type x: int\n :type y: int\n :type bound: int\n :rtype: List[int]\n \"\"\"\n result = set()\n log_x = int(math.floor(math.log(bound) / math.log(x)))+1 if x != 1 else 1\n log_y = int(math.floor(math.log(bound) / math.log(y)))+1 if y != 1 else 1\n pow_x = 1\n for i in range(log_x):\n pow_y = 1\n for j in range(log_y):\n val = pow_x + pow_y\n if val <= bound:\n result.add(val)\n pow_y *= y\n pow_x *= x\n return list(result)\n"}} diff --git a/cp/cp-10446.jsonl b/cp/cp-10446.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..569f24a5507733f72f8543c4be144b80c3236f82 --- /dev/null +++ b/cp/cp-10446.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10446", "name": "LeetCode 0971: Flip Binary Tree To Match Preorder Traversal"} +{"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: Flip Binary Tree To Match Preorder Traversal (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Tree\n\nYou are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree.\nAny node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:\nFlip the smallest number of nodes so that the pre-order traversal of the tree matches voyage.\nReturn a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage, return the list [-1].\n\nExample 1:\nInput: root = [1,2], voyage = [2,1]\nOutput: [-1]\nExplanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage.\n\nExample 2:\nInput: root = [1,2,3], voyage = [1,3,2]\nOutput: [1]\nExplanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.\n\nExample 3:\nInput: root = [1,2,3], voyage = [1,2,3]\nOutput: []\nExplanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.\n\nConstraints:\n- The number of nodes in the tree is n.\n- n == voyage.length\n- 1 <= n <= 100\n- 1 <= Node.val, voyage[i] <= n\n- All the values in the tree are unique.\n- All the values in voyage are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 flipMatchVoyage(self, root, voyage):\n \"\"\"\n :type root: TreeNode\n :type voyage: List[int]\n :rtype: List[int]\n \"\"\"\n def dfs(root, voyage, i, result):\n if not root:\n return True\n if root.val != voyage[i[0]]:\n return False\n i[0] += 1\n if root.left and root.left.val != voyage[i[0]]:\n result.append(root.val)\n return dfs(root.right, voyage, i, result) and \\\n dfs(root.left, voyage, i, result)\n return dfs(root.left, voyage, i, result) and \\\n dfs(root.right, voyage, i, result)\n \n result = []\n return result if dfs(root, voyage, [0], result) else [-1]\n"}} diff --git a/cp/cp-10447.jsonl b/cp/cp-10447.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4f3e812c3660c9cb261e28ef3fc8b16f62c4839c --- /dev/null +++ b/cp/cp-10447.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10447", "name": "LeetCode 0972: Equal Rational 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: Equal Rational Numbers (Difficulty: Hard)\nTags: Math, String\n\nGiven two strings s and t, each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.\nA rational number can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways:\nThe repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:\n\nExample 1:\nInput: s = \"0.(52)\", t = \"0.5(25)\"\nOutput: true\nExplanation: Because \"0.(52)\" represents 0.52525252..., and \"0.5(25)\" represents 0.52525252525..... , the strings represent the same number.\n\nExample 2:\nInput: s = \"0.1666(6)\", t = \"0.166(66)\"\nOutput: true\n\nExample 3:\nInput: s = \"0.9(9)\", t = \"1.\"\nOutput: true\nExplanation: \"0.9(9)\" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.]\n\"1.\" represents the number 1, which is formed correctly: (IntegerPart) = \"1\" and (NonRepeatingPart) = \"\".\n\nConstraints:\n- Each part consists only of digits.\n- The does not have leading zeros (except for the zero itself).\n- 1 <= .length <= 4\n- 0 <= .length <= 4\n- 1 <= .length <= 4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nfrom fractions import Fraction\n\n\nclass Solution(object):\n def isRationalEqual(self, S, T):\n \"\"\"\n :type S: str\n :type T: str\n :rtype: bool\n \"\"\"\n def frac(S):\n if '.' not in S:\n return Fraction(int(S), 1)\n\n i = S.index('.')\n result = Fraction(int(S[:i]), 1)\n non_int_part = S[i+1:]\n if '(' not in non_int_part:\n if non_int_part:\n result += Fraction(int(non_int_part), 10**len(non_int_part))\n return result\n\n i = non_int_part.index('(')\n if i:\n result += Fraction(int(non_int_part[:i]), 10**i)\n repeat_part = non_int_part[i+1:-1]\n result += Fraction(int(repeat_part), 10**i * (10**len(repeat_part)-1))\n return result\n\n return frac(S) == frac(T)\n"}} diff --git a/cp/cp-10448.jsonl b/cp/cp-10448.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9dbb6fb6ecddb8899cd787baa58d70a31e6fb86a --- /dev/null +++ b/cp/cp-10448.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10448", "name": "LeetCode 0973: K Closest Points 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: K Closest Points to Origin (Difficulty: Medium)\nTags: Array, Math, Divide and Conquer, Geometry, Sorting, Heap (Priority Queue), Quickselect\n\nGiven an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).\nThe distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).\nYou may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).\n\nExample 1:\nInput: points = [[1,3],[-2,2]], k = 1\nOutput: [[-2,2]]\nExplanation:\nThe distance between (1, 3) and the origin is sqrt(10).\nThe distance between (-2, 2) and the origin is sqrt(8).\nSince sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\nWe only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].\n\nExample 2:\nInput: points = [[3,3],[5,-1],[-2,4]], k = 2\nOutput: [[3,3],[-2,4]]\nExplanation: The answer [[-2,4],[3,3]] would also be accepted.\n\nConstraints:\n- 1 <= k <= points.length <= 10^4\n- -10^4 <= xi, yi <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n) on average\n# Space: O(1)\n\n# quick select solution\nfrom random import randint\n\n\nclass Solution(object):\n def kClosest(self, points, K):\n \"\"\"\n :type points: List[List[int]]\n :type K: int\n :rtype: List[List[int]]\n \"\"\"\n def dist(point):\n return point[0]**2 + point[1]**2\n \n def kthElement(nums, k, compare):\n def PartitionAroundPivot(left, right, pivot_idx, nums, compare):\n new_pivot_idx = left\n nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]\n for i in range(left, right):\n if compare(nums[i], nums[right]):\n nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]\n new_pivot_idx += 1\n\n nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]\n return new_pivot_idx\n\n left, right = 0, len(nums) - 1\n while left <= right:\n pivot_idx = randint(left, right)\n new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, nums, compare)\n if new_pivot_idx == k:\n return\n elif new_pivot_idx > k:\n right = new_pivot_idx - 1\n else: # new_pivot_idx < k.\n left = new_pivot_idx + 1\n \n kthElement(points, K-1, lambda a, b: dist(a) < dist(b))\n return points[:K]\n\n \n# Time: O(nlogk)\n# Space: O(k)\nimport heapq\n\n\nclass Solution2(object):\n def kClosest(self, points, K):\n \"\"\"\n :type points: List[List[int]]\n :type K: int\n :rtype: List[List[int]]\n \"\"\"\n def dist(point):\n return point[0]**2 + point[1]**2\n \n max_heap = []\n for point in points:\n heapq.heappush(max_heap, (-dist(point), point))\n if len(max_heap) > K:\n heapq.heappop(max_heap)\n return [heapq.heappop(max_heap)[1] for _ in range(len(max_heap))]\n"}} diff --git a/cp/cp-10449.jsonl b/cp/cp-10449.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2b4071088afb4dbdf0a1f082e6e762c2382d1304 --- /dev/null +++ b/cp/cp-10449.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10449", "name": "LeetCode 0974: Subarray Sums Divisible By K"} +{"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: Subarray Sums Divisible by K (Difficulty: Medium)\nTags: Array, Hash Table, Prefix Sum\n\nGiven an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.\nA subarray is a contiguous part of an array.\n\nExample 1:\nInput: nums = [4,5,0,-2,-3,1], k = 5\nOutput: 7\nExplanation: There are 7 subarrays with a sum divisible by k = 5:\n[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]\n\nExample 2:\nInput: nums = [5], k = 9\nOutput: 0\n\nConstraints:\n- 1 <= nums.length <= 3 * 10^4\n- -10^4 <= nums[i] <= 10^4\n- 2 <= k <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(k)\n\nimport collections\n\n\nclass Solution(object):\n def subarraysDivByK(self, A, K):\n \"\"\"\n :type A: List[int]\n :type K: int\n :rtype: int\n \"\"\"\n count = collections.defaultdict(int)\n count[0] = 1\n result, prefix = 0, 0\n for a in A:\n prefix = (prefix+a) % K\n result += count[prefix]\n count[prefix] += 1\n return result\n"}} diff --git a/cp/cp-10450.jsonl b/cp/cp-10450.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6974dd5099056af7dc91ee7d3ee0753e30ced682 --- /dev/null +++ b/cp/cp-10450.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10450", "name": "LeetCode 0975: Odd Even Jump"} +{"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: Odd Even Jump (Difficulty: Hard)\nTags: Array, Dynamic Programming, Stack, Sorting, Monotonic Stack, Ordered Set\n\nYou are given an integer array arr. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices.\nYou may jump forward from index i to index j (with i < j) in the following way:\nA starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (possibly 0 or more than once).\nReturn the number of good starting indices.\n\nExample 1:\nInput: arr = [10,13,12,14,15]\nOutput: 2\nExplanation: \nFrom starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.\nFrom starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.\nFrom starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.\nFrom starting index i = 4, we have reached the end already.\nIn total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of\njumps.\n\nExample 2:\nInput: arr = [2,3,1,1,4]\nOutput: 3\nExplanation: \nFrom starting index i = 0, we make jumps to i = 1, i = 2, i = 3:\nDuring our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].\nDuring our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3\nDuring our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].\nWe can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.\nIn a similar manner, we can deduce that:\nFrom starting index i = 1, we jump to i = 4, so we reach the end.\nFrom starting index i = 2, we jump to i = 3, and then we can't jump anymore.\nFrom starting index i = 3, we jump to i = 4, so we reach the end.\nFrom starting index i = 4, we are already at the end.\nIn total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some\nnumber of jumps.\n\nExample 3:\nInput: arr = [5,1,3,4,2]\nOutput: 3\nExplanation: We can reach the end from starting indices 1, 2, and 4.\n\nConstraints:\n- 1 <= arr.length <= 2 * 10^4\n- 0 <= arr[i] < 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass Solution(object):\n def oddEvenJumps(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n def findNext(idx):\n result = [None]*len(idx)\n stack = []\n for i in idx:\n while stack and stack[-1] < i:\n result[stack.pop()] = i\n stack.append(i)\n return result\n \n idx = sorted(range(len(A)), key = lambda i: A[i])\n next_higher = findNext(idx)\n idx.sort(key = lambda i: -A[i])\n next_lower = findNext(idx)\n\n odd, even = [False]*len(A), [False]*len(A)\n odd[-1], even[-1] = True, True\n for i in reversed(range(len(A)-1)):\n if next_higher[i]:\n odd[i] = even[next_higher[i]]\n if next_lower[i]:\n even[i] = odd[next_lower[i]]\n return sum(odd)\n"}} diff --git a/cp/cp-10451.jsonl b/cp/cp-10451.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..01ddff1264c579db48eab85c67421e72476f245f --- /dev/null +++ b/cp/cp-10451.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10451", "name": "LeetCode 0976: Largest Perimeter Triangle"} +{"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: Largest Perimeter Triangle (Difficulty: Easy)\nTags: Array, Math, Greedy, Sorting\n\nGiven an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.\n\nExample 1:\nInput: nums = [2,1,2]\nOutput: 5\nExplanation: You can form a triangle with three side lengths: 1, 2, and 2.\n\nExample 2:\nInput: nums = [1,2,1,10]\nOutput: 0\nExplanation: \nYou cannot use the side lengths 1, 1, and 2 to form a triangle.\nYou cannot use the side lengths 1, 1, and 10 to form a triangle.\nYou cannot use the side lengths 1, 2, and 10 to form a triangle.\nAs we cannot use any three side lengths to form a triangle of non-zero area, we return 0.\n\nConstraints:\n- 3 <= nums.length <= 10^4\n- 1 <= nums[i] <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def largestPerimeter(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n A.sort()\n for i in reversed(range(len(A) - 2)):\n if A[i] + A[i+1] > A[i+2]:\n return A[i] + A[i+1] + A[i+2]\n return 0\n"}} diff --git a/cp/cp-10452.jsonl b/cp/cp-10452.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7b9b51da79cd2f97cf47fb881156e2376b7ef48c --- /dev/null +++ b/cp/cp-10452.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10452", "name": "LeetCode 0977: Squares Of A Sorted 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: Squares of a Sorted Array (Difficulty: Easy)\nTags: Array, Two Pointers, Sorting\n\nGiven an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.\n\nExample 1:\nInput: nums = [-4,-1,0,3,10]\nOutput: [0,1,9,16,100]\nExplanation: After squaring, the array becomes [16,1,0,9,100].\nAfter sorting, it becomes [0,1,9,16,100].\n\nExample 2:\nInput: nums = [-7,-3,2,3,11]\nOutput: [4,9,9,49,121]\n\nConstraints:\n- 1 <= nums.length <= 10^4\n- -10^4 <= nums[i] <= 10^4\n- nums is sorted in non-decreasing order."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport bisect\n\n\nclass Solution(object):\n def sortedSquares(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: List[int]\n \"\"\"\n right = bisect.bisect_left(A, 0)\n left = right-1\n result = []\n while 0 <= left or right < len(A):\n if right == len(A) or \\\n (0 <= left and A[left]**2 < A[right]**2):\n result.append(A[left]**2)\n left -= 1\n else:\n result.append(A[right]**2)\n right += 1\n return result\n"}} diff --git a/cp/cp-10453.jsonl b/cp/cp-10453.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f2040ed5b15908af744ed39b766726c529ea208e --- /dev/null +++ b/cp/cp-10453.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10453", "name": "LeetCode 0978: Longest Turbulent Subarray"} +{"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 Turbulent Subarray (Difficulty: Medium)\nTags: Array, Dynamic Programming, Sliding Window\n\nGiven an integer array arr, return the length of a maximum size turbulent subarray of arr.\nA subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.\nMore formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if:\n\nExample 1:\nInput: arr = [9,4,2,10,7,8,8,1,9]\nOutput: 5\nExplanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5]\n\nExample 2:\nInput: arr = [4,8,12,16]\nOutput: 2\n\nExample 3:\nInput: arr = [100]\nOutput: 1\n\nConstraints:\n- 1 <= arr.length <= 4 * 10^4\n- 0 <= arr[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxTurbulenceSize(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n result = 1\n start = 0\n for i in range(1, len(A)):\n if i == len(A)-1 or \\\n cmp(A[i-1], A[i]) * cmp(A[i], A[i+1]) != -1:\n result = max(result, i-start+1)\n start = i\n return result\n"}} diff --git a/cp/cp-10454.jsonl b/cp/cp-10454.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1042f9e4cd31ea38ae9de63997704f0d8f224369 --- /dev/null +++ b/cp/cp-10454.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10454", "name": "LeetCode 0979: Distribute Coins 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: Distribute Coins in Binary Tree (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Tree\n\nYou are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.\nIn one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.\nReturn the minimum number of moves required to make every node have exactly one coin.\n\nExample 1:\nInput: root = [3,0,0]\nOutput: 2\nExplanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.\n\nExample 2:\nInput: root = [0,3,0]\nOutput: 3\nExplanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.\n\nConstraints:\n- The number of nodes in the tree is n.\n- 1 <= n <= 100\n- 0 <= Node.val <= n\n- The sum of all Node.val is n."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 distributeCoins(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def dfs(root, result):\n if not root:\n return 0\n left, right = dfs(root.left, result), dfs(root.right, result)\n result[0] += abs(left) + abs(right)\n return root.val + left + right - 1\n\n result = [0]\n dfs(root, result)\n return result[0]\n"}} diff --git a/cp/cp-10455.jsonl b/cp/cp-10455.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..aa802aeef21c3d59c66497b7dc87bee100889037 --- /dev/null +++ b/cp/cp-10455.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10455", "name": "LeetCode 0980: Unique Paths 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: Unique Paths III (Difficulty: Hard)\nTags: Array, Backtracking, Bit Manipulation, Matrix\n\nYou are given an m x n integer array grid where grid[i][j] could be:\nReturn the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.\n\nExample 1:\nInput: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]\nOutput: 2\nExplanation: We have the following two paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)\n\nExample 2:\nInput: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]\nOutput: 4\nExplanation: We have the following four paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)\n\nExample 3:\nInput: grid = [[0,1],[2,0]]\nOutput: 0\nExplanation: There is no path that walks over every empty square exactly once.\nNote that the starting and ending square can be anywhere in the grid.\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 20\n- 1 <= m * n <= 20\n- -1 <= grid[i][j] <= 2\n- There is exactly one starting cell and one ending cell."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n * 2^(m * n))\n# Space: O(m * n * 2^(m * n))\n\nclass Solution(object):\n def uniquePathsIII(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n \n def index(grid, r, c):\n return 1 << (r*len(grid[0])+c)\n\n def dp(grid, src, dst, todo, lookup):\n if src == dst:\n return int(todo == 0)\n key = (src, todo)\n if key in lookup:\n return lookup[key]\n\n result = 0\n for d in directions:\n r, c = src[0]+d[0], src[1]+d[1]\n if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and \\\n grid[r][c] % 2 == 0 and \\\n todo & index(grid, r, c):\n result += dp(grid, (r, c), dst, todo ^ index(grid, r, c), lookup)\n\n lookup[key] = result\n return lookup[key]\n\n todo = 0\n src, dst = None, None\n for r, row in enumerate(grid):\n for c, val in enumerate(row):\n if val % 2 == 0:\n todo |= index(grid, r, c)\n if val == 1:\n src = (r, c)\n elif val == 2:\n dst = (r, c)\n return dp(grid, src, dst, todo, {})\n"}} diff --git a/cp/cp-10456.jsonl b/cp/cp-10456.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3b1142e482d11e3b00715cbc4ac03655c08ddac8 --- /dev/null +++ b/cp/cp-10456.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10456", "name": "LeetCode 0981: Time Based Key Value Store"} +{"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: Time Based Key-Value Store (Difficulty: Medium)\nTags: Hash Table, String, Binary Search, Design\n\nDesign a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.\nImplement the TimeMap class:\n\nExample 1:\nInput\n[\"TimeMap\", \"set\", \"get\", \"get\", \"set\", \"get\", \"get\"]\n[[], [\"foo\", \"bar\", 1], [\"foo\", 1], [\"foo\", 3], [\"foo\", \"bar2\", 4], [\"foo\", 4], [\"foo\", 5]]\nOutput\n[null, null, \"bar\", \"bar\", null, \"bar2\", \"bar2\"]\n\nExplanation\nTimeMap timeMap = new TimeMap();\ntimeMap.set(\"foo\", \"bar\", 1); // store the key \"foo\" and value \"bar\" along with timestamp = 1.\ntimeMap.get(\"foo\", 1); // return \"bar\"\ntimeMap.get(\"foo\", 3); // return \"bar\", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is \"bar\".\ntimeMap.set(\"foo\", \"bar2\", 4); // store the key \"foo\" and value \"bar2\" along with timestamp = 4.\ntimeMap.get(\"foo\", 4); // return \"bar2\"\ntimeMap.get(\"foo\", 5); // return \"bar2\"\n\nConstraints:\n- 1 <= key.length, value.length <= 100\n- key and value consist of lowercase English letters and digits.\n- 1 <= timestamp <= 10^7\n- All the timestamps timestamp of set are strictly increasing.\n- At most 2 * 10^5 calls will be made to set and get."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: set: O(1)\n# get: O(logn)\n# Space: O(n)\n\nimport collections\nimport bisect\n\n\nclass TimeMap(object):\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.lookup = collections.defaultdict(list)\n\n def set(self, key, value, timestamp):\n \"\"\"\n :type key: str\n :type value: str\n :type timestamp: int\n :rtype: None\n \"\"\"\n self.lookup[key].append((timestamp, value))\n \n\n def get(self, key, timestamp):\n \"\"\"\n :type key: str\n :type timestamp: int\n :rtype: str\n \"\"\"\n A = self.lookup.get(key, None)\n if A is None:\n return \"\"\n i = bisect.bisect_right(A, (timestamp+1, 0))\n return A[i-1][1] if i else \"\"\n\n\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)\n"}} diff --git a/cp/cp-10457.jsonl b/cp/cp-10457.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c3a27286c456e1e9789e30e7954ded225cbb101e --- /dev/null +++ b/cp/cp-10457.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10457", "name": "LeetCode 0982: Triples With Bitwise And Equal To Zero"} +{"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: Triples with Bitwise AND Equal To Zero (Difficulty: Hard)\nTags: Array, Hash Table, Bit Manipulation\n\nGiven an integer array nums, return the number of AND triples.\nAn AND triple is a triple of indices (i, j, k) such that:\n\nExample 1:\nInput: nums = [2,1,3]\nOutput: 12\nExplanation: We could choose the following i, j, k triples:\n(i=0, j=0, k=1) : 2 & 2 & 1\n(i=0, j=1, k=0) : 2 & 1 & 2\n(i=0, j=1, k=1) : 2 & 1 & 1\n(i=0, j=1, k=2) : 2 & 1 & 3\n(i=0, j=2, k=1) : 2 & 3 & 1\n(i=1, j=0, k=0) : 1 & 2 & 2\n(i=1, j=0, k=1) : 1 & 2 & 1\n(i=1, j=0, k=2) : 1 & 2 & 3\n(i=1, j=1, k=0) : 1 & 1 & 2\n(i=1, j=2, k=0) : 1 & 3 & 2\n(i=2, j=0, k=1) : 3 & 2 & 1\n(i=2, j=1, k=0) : 3 & 1 & 2\n\nExample 2:\nInput: nums = [0,0,0]\nOutput: 27\n\nConstraints:\n- 1 <= nums.length <= 1000\n- 0 <= nums[i] < 216"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn), n is the max of A\n# Space: O(n)\n\nimport collections\n\n\n# Reference: https://blog.csdn.net/john123741/article/details/76576925\n# FWT solution\nclass Solution(object):\n def countTriplets(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n def FWT(A, v):\n B = A[:]\n d = 1\n while d < len(B):\n for i in range(0, len(B), d << 1):\n for j in range(d):\n B[i+j] += B[i+j+d] * v\n d <<= 1\n return B\n\n k = 3\n n, max_A = 1, max(A)\n while n <= max_A:\n n *= 2\n count = collections.Counter(A)\n B = [count[i] for i in range(n)]\n C = FWT(map(lambda x : x**k, FWT(B, 1)), -1)\n return C[0]\n\n\n# Time: O(n^3), n is the length of A\n# Space: O(n^2)\nimport collections\n\n\nclass Solution2(object):\n def countTriplets(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n count = collections.defaultdict(int)\n for i in range(len(A)):\n for j in range(len(A)):\n count[A[i]&A[j]] += 1\n result = 0\n for k in range(len(A)):\n for v in count:\n if A[k]&v == 0:\n result += count[v]\n return result\n"}} diff --git a/cp/cp-10458.jsonl b/cp/cp-10458.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8ca37872ca63551c6ad53687278c53a0018336b4 --- /dev/null +++ b/cp/cp-10458.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10458", "name": "LeetCode 0983: Minimum Cost For Tickets"} +{"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: Minimum Cost For Tickets (Difficulty: Medium)\nTags: Array, Dynamic Programming\n\nYou have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365.\nTrain tickets are sold in three different ways:\nThe passes allow that many days of consecutive travel.\nReturn the minimum number of dollars you need to travel every day in the given list of days.\n\nExample 1:\nInput: days = [1,4,6,7,8,20], costs = [2,7,15]\nOutput: 11\nExplanation: For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.\nOn day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.\nOn day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.\nIn total, you spent $11 and covered all the days of your travel.\n\nExample 2:\nInput: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]\nOutput: 17\nExplanation: For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.\nOn day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.\nIn total, you spent $17 and covered all the days of your travel.\n\nConstraints:\n- 1 <= days.length <= 365\n- 1 <= days[i] <= 365\n- days is in strictly increasing order.\n- costs.length == 3\n- 1 <= costs[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# space: O(1)\n\nclass Solution(object):\n def mincostTickets(self, days, costs):\n \"\"\"\n :type days: List[int]\n :type costs: List[int]\n :rtype: int\n \"\"\"\n durations = [1, 7, 30]\n W = durations[-1]\n dp = [float(\"inf\") for i in range(W)]\n dp[0] = 0\n last_buy_days = [0, 0, 0]\n for i in range(1,len(days)+1):\n dp[i%W] = float(\"inf\")\n for j in range(len(durations)):\n while i-1 < len(days) and \\\n days[i-1] > days[last_buy_days[j]]+durations[j]-1:\n last_buy_days[j] += 1 # Time: O(n)\n dp[i%W] = min(dp[i%W], dp[last_buy_days[j]%W]+costs[j])\n return dp[len(days)%W]\n"}} diff --git a/cp/cp-10459.jsonl b/cp/cp-10459.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..686434e5ffdff06c0ee210e8945b526afee43b90 --- /dev/null +++ b/cp/cp-10459.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10459", "name": "LeetCode 0984: String Without Aaa Or Bbb"} +{"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: String Without AAA or BBB (Difficulty: Medium)\nTags: String, Greedy\n\nGiven two integers a and b, return any string s such that:\n\nExample 1:\nInput: a = 1, b = 2\nOutput: \"abb\"\nExplanation: \"abb\", \"bab\" and \"bba\" are all correct answers.\n\nExample 2:\nInput: a = 4, b = 1\nOutput: \"aabaa\"\n\nConstraints:\n- 0 <= a, b <= 100\n- It is guaranteed such an s exists for the given a and b."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(a + b)\n# Space: O(1)\n\nclass Solution(object):\n def strWithout3a3b(self, A, B):\n \"\"\"\n :type A: int\n :type B: int\n :rtype: str\n \"\"\"\n result = []\n put_A = None\n while A or B:\n if len(result) >= 2 and result[-1] == result[-2]:\n put_A = result[-1] == 'b'\n else:\n put_A = A >= B\n\n if put_A:\n A -= 1\n result.append('a')\n else:\n B -= 1\n result.append('b')\n return \"\".join(result)\n"}} diff --git a/cp/cp-10460.jsonl b/cp/cp-10460.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..14ae1d827998a80bcb33dd82a3855cbbfc7de99b --- /dev/null +++ b/cp/cp-10460.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10460", "name": "LeetCode 0985: Sum Of Even Numbers After Queries"} +{"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 Even Numbers After Queries (Difficulty: Medium)\nTags: Array, Simulation\n\nYou are given an integer array nums and an array queries where queries[i] = [vali, indexi].\nFor each query i, first, apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values of nums.\nReturn an integer array answer where answer[i] is the answer to the ith query.\n\nExample 1:\nInput: nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]\nOutput: [8,6,2,4]\nExplanation: At the beginning, the array is [1,2,3,4].\nAfter adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.\nAfter adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.\nAfter adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.\nAfter adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.\n\nExample 2:\nInput: nums = [1], queries = [[4,0]]\nOutput: [0]\n\nConstraints:\n- 1 <= nums.length <= 10^4\n- -10^4 <= nums[i] <= 10^4\n- 1 <= queries.length <= 10^4\n- -10^4 <= vali <= 10^4\n- 0 <= indexi < nums.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + q)\n# Space: O(1)\n\nclass Solution(object):\n def sumEvenAfterQueries(self, A, queries):\n \"\"\"\n :type A: List[int]\n :type queries: List[List[int]]\n :rtype: List[int]\n \"\"\"\n total = sum(v for v in A if v % 2 == 0)\n \n result = []\n for v, i in queries:\n if A[i] % 2 == 0:\n total -= A[i]\n A[i] += v\n if A[i] % 2 == 0:\n total += A[i]\n result.append(total)\n return result\n"}} diff --git a/cp/cp-10461.jsonl b/cp/cp-10461.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..795cf58176bcf88dfd2c2da96c45a644cd76aabc --- /dev/null +++ b/cp/cp-10461.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10461", "name": "LeetCode 0986: Interval List Intersections"} +{"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: Interval List Intersections (Difficulty: Medium)\nTags: Array, Two Pointers, Line Sweep\n\nYou are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.\nReturn the intersection of these two interval lists.\nA closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b.\nThe intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].\n\nExample 1:\nInput: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]\nOutput: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]\n\nExample 2:\nInput: firstList = [[1,3],[5,9]], secondList = []\nOutput: []\n\nConstraints:\n- 0 <= firstList.length, secondList.length <= 1000\n- firstList.length + secondList.length >= 1\n- 0 <= starti < endi <= 10^9\n- endi < starti+1\n- 0 <= startj < endj <= 10^9\n- endj < startj+1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n)\n# Space: O(1)\n\n# Definition for an interval.\nclass Interval(object):\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\n\nclass Solution(object):\n def intervalIntersection(self, A, B):\n \"\"\"\n :type A: List[Interval]\n :type B: List[Interval]\n :rtype: List[Interval]\n \"\"\"\n result = []\n i, j = 0, 0\n while i < len(A) and j < len(B):\n left = max(A[i].start, B[j].start)\n right = min(A[i].end, B[j].end)\n if left <= right:\n result.append(Interval(left, right))\n if A[i].end < B[j].end:\n i += 1\n else:\n j += 1\n return result\n"}} diff --git a/cp/cp-10462.jsonl b/cp/cp-10462.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..998eb48da3929564b30ce94eb0bb7fdbac3feeb0 --- /dev/null +++ b/cp/cp-10462.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10462", "name": "LeetCode 0987: Vertical Order Traversal Of 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: Vertical Order Traversal of a Binary Tree (Difficulty: Hard)\nTags: Hash Table, Tree, Depth-First Search, Breadth-First Search, Sorting, Binary Tree\n\nGiven the root of a binary tree, calculate the vertical order traversal of the binary tree.\nFor each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).\nThe vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.\nReturn the vertical order traversal of the binary tree.\n\nExample 1:\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[9],[3,15],[20],[7]]\nExplanation:\nColumn -1: Only node 9 is in this column.\nColumn 0: Nodes 3 and 15 are in this column in that order from top to bottom.\nColumn 1: Only node 20 is in this column.\nColumn 2: Only node 7 is in this column.\n\nExample 2:\nInput: root = [1,2,3,4,5,6,7]\nOutput: [[4],[2],[1,5,6],[3],[7]]\nExplanation:\nColumn -2: Only node 4 is in this column.\nColumn -1: Only node 2 is in this column.\nColumn 0: Nodes 1, 5, and 6 are in this column.\n 1 is at the top, so it comes first.\n 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.\nColumn 1: Only node 3 is in this column.\nColumn 2: Only node 7 is in this column.\n\nExample 3:\nInput: root = [1,2,3,4,6,5,7]\nOutput: [[4],[2],[1,5,6],[3],[7]]\nExplanation:\nThis case is the exact same as example 2, but with nodes 5 and 6 swapped.\nNote that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 1000].\n- 0 <= Node.val <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport collections\n\n\n# Definition for a binary tree node.\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 verticalTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n def dfs(node, lookup, x, y):\n if not node:\n return\n lookup[x][y].append(node)\n dfs(node.left, lookup, x-1, y+1)\n dfs(node.right, lookup, x+1, y+1)\n \n lookup = collections.defaultdict(lambda: collections.defaultdict(list))\n dfs(root, lookup, 0, 0)\n\n result = []\n for x in sorted(lookup):\n report = []\n for y in sorted(lookup[x]):\n report.extend(sorted(node.val for node in lookup[x][y]))\n result.append(report)\n return result\n"}} diff --git a/cp/cp-10463.jsonl b/cp/cp-10463.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..909807df819810302d7eaa51d1aa0aa76d884f24 --- /dev/null +++ b/cp/cp-10463.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10463", "name": "LeetCode 0988: Smallest String Starting From Leaf"} +{"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: Smallest String Starting From Leaf (Difficulty: Medium)\nTags: String, Backtracking, Tree, Depth-First Search, Binary Tree\n\nYou are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'.\nReturn the lexicographically smallest string that starts at a leaf of this tree and ends at the root.\nAs a reminder, any shorter prefix of a string is lexicographically smaller.\nA leaf of a node is a node that has no children.\n\nExample 1:\nInput: root = [0,1,2,3,4,3,4]\nOutput: \"dba\"\n\nExample 2:\nInput: root = [25,1,3,1,3,0,2]\nOutput: \"adz\"\n\nExample 3:\nInput: root = [2,2,1,null,1,0,null,0]\nOutput: \"abc\"\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 8500].\n- 0 <= Node.val <= 25"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + l * h), l is the number of leaves\n# Space: O(h)\n\n# Definition for a binary tree node.\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 smallestFromLeaf(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: str\n \"\"\"\n def dfs(node, candidate, result):\n if not node:\n return\n\n candidate.append(chr(ord('a') + node.val))\n if not node.left and not node.right:\n result[0] = min(result[0], \"\".join(reversed(candidate)))\n dfs(node.left, candidate, result)\n dfs(node.right, candidate, result)\n candidate.pop()\n\n result = [\"~\"]\n dfs(root, [], result)\n return result[0]\n"}} diff --git a/cp/cp-10464.jsonl b/cp/cp-10464.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3ece1f3eae14d8c3895d9729236f77968167094b --- /dev/null +++ b/cp/cp-10464.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10464", "name": "LeetCode 0989: Add To Array Form Of Integer"} +{"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 to Array-Form of Integer (Difficulty: Easy)\nTags: Array, Math\n\nThe array-form of an integer num is an array representing its digits in left to right order.\nGiven num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.\n\nExample 1:\nInput: num = [1,2,0,0], k = 34\nOutput: [1,2,3,4]\nExplanation: 1200 + 34 = 1234\n\nExample 2:\nInput: num = [2,7,4], k = 181\nOutput: [4,5,5]\nExplanation: 274 + 181 = 455\n\nExample 3:\nInput: num = [2,1,5], k = 806\nOutput: [1,0,2,1]\nExplanation: 215 + 806 = 1021\n\nConstraints:\n- 1 <= num.length <= 10^4\n- 0 <= num[i] <= 9\n- num does not contain any leading zeros except for the zero itself.\n- 1 <= k <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + logk)\n# Space: O(1)\n\nclass Solution(object):\n def addToArrayForm(self, A, K):\n \"\"\"\n :type A: List[int]\n :type K: int\n :rtype: List[int]\n \"\"\"\n A.reverse()\n carry, i = K, 0\n A[i] += carry\n carry, A[i] = divmod(A[i], 10)\n while carry:\n i += 1\n if i < len(A):\n A[i] += carry\n else:\n A.append(carry)\n carry, A[i] = divmod(A[i], 10)\n A.reverse()\n return A\n"}} diff --git a/cp/cp-10465.jsonl b/cp/cp-10465.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0e7f27f1558ac5ed18bbfa903a69dc736d92ca2b --- /dev/null +++ b/cp/cp-10465.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10465", "name": "LeetCode 0990: Satisfiability Of Equality Equations"} +{"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: Satisfiability of Equality Equations (Difficulty: Medium)\nTags: Array, String, Union Find, Graph\n\nYou are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: \"xi==yi\" or \"xi!=yi\".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names.\nReturn true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise.\n\nExample 1:\nInput: equations = [\"a==b\",\"b!=a\"]\nOutput: false\nExplanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.\nThere is no way to assign the variables to satisfy both equations.\n\nExample 2:\nInput: equations = [\"b==a\",\"a==b\"]\nOutput: true\nExplanation: We could assign a = 1 and b = 1 to satisfy both equations.\n\nConstraints:\n- 1 <= equations.length <= 500\n- equations[i].length == 4\n- equations[i][0] is a lowercase letter.\n- equations[i][1] is either '=' or '!'.\n- equations[i][2] is '='.\n- equations[i][3] is a lowercase letter."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n return True\n\n\nclass Solution(object):\n def equationsPossible(self, equations):\n \"\"\"\n :type equations: List[str]\n :rtype: bool\n \"\"\"\n union_find = UnionFind(26)\n for eqn in equations:\n x = ord(eqn[0]) - ord('a')\n y = ord(eqn[3]) - ord('a')\n if eqn[1] == '=':\n union_find.union_set(x, y)\n for eqn in equations:\n x = ord(eqn[0]) - ord('a')\n y = ord(eqn[3]) - ord('a')\n if eqn[1] == '!':\n if union_find.find_set(x) == union_find.find_set(y):\n return False\n return True\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def equationsPossible(self, equations):\n \"\"\"\n :type equations: List[str]\n :rtype: bool\n \"\"\"\n graph = [[] for _ in range(26)]\n\n for eqn in equations:\n x = ord(eqn[0]) - ord('a')\n y = ord(eqn[3]) - ord('a')\n if eqn[1] == '!':\n if x == y:\n return False\n else:\n graph[x].append(y)\n graph[y].append(x)\n\n color = [None]*26\n c = 0\n for i in range(26):\n if color[i] is not None:\n continue\n c += 1\n stack = [i]\n while stack:\n node = stack.pop()\n for nei in graph[node]:\n if color[nei] is not None:\n continue\n color[nei] = c\n stack.append(nei)\n\n for eqn in equations:\n if eqn[1] != '!':\n continue\n x = ord(eqn[0]) - ord('a')\n y = ord(eqn[3]) - ord('a')\n if color[x] is not None and \\\n color[x] == color[y]:\n return False\n return True\n"}} diff --git a/cp/cp-10466.jsonl b/cp/cp-10466.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5538afe5828a1a92a0786eb17fba941f107f69f2 --- /dev/null +++ b/cp/cp-10466.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10466", "name": "LeetCode 0991: Broken Calculator"} +{"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: Broken Calculator (Difficulty: Medium)\nTags: Math, Greedy\n\nThere is a broken calculator that has the integer startValue on its display initially. In one operation, you can:\nGiven two integers startValue and target, return the minimum number of operations needed to display target on the calculator.\n\nExample 1:\nInput: startValue = 2, target = 3\nOutput: 2\nExplanation: Use double operation and then decrement operation {2 -> 4 -> 3}.\n\nExample 2:\nInput: startValue = 5, target = 8\nOutput: 2\nExplanation: Use decrement and then double {5 -> 4 -> 8}.\n\nExample 3:\nInput: startValue = 3, target = 10\nOutput: 3\nExplanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.\n\nConstraints:\n- 1 <= startValue, target <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nclass Solution(object):\n def brokenCalc(self, X, Y):\n \"\"\"\n :type X: int\n :type Y: int\n :rtype: int\n \"\"\"\n result = 0\n while X < Y:\n if Y%2:\n Y += 1\n else:\n Y /= 2\n result += 1\n return result + X-Y\n"}} diff --git a/cp/cp-10467.jsonl b/cp/cp-10467.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ded6f099cb2c7652804e94a1a361aae612f52838 --- /dev/null +++ b/cp/cp-10467.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10467", "name": "LeetCode 0992: Subarrays With K Different Integers"} +{"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: Subarrays with K Different Integers (Difficulty: Hard)\nTags: Array, Hash Table, Sliding Window, Counting\n\nGiven an integer array nums and an integer k, return the number of good subarrays of nums.\nA good array is an array where the number of different integers in that array is exactly k.\nA subarray is a contiguous part of an array.\n\nExample 1:\nInput: nums = [1,2,1,2,3], k = 2\nOutput: 7\nExplanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]\n\nExample 2:\nInput: nums = [1,2,1,3,4], k = 3\nOutput: 3\nExplanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].\n\nConstraints:\n- 1 <= nums.length <= 2 * 10^4\n- 1 <= nums[i], k <= nums.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(k)\n\nimport collections\n\n\nclass Solution(object):\n def subarraysWithKDistinct(self, A, K):\n \"\"\"\n :type A: List[int]\n :type K: int\n :rtype: int\n \"\"\"\n def atMostK(A, K):\n count = collections.defaultdict(int)\n result, left = 0, 0\n for right in range(len(A)):\n count[A[right]] += 1\n while len(count) > K:\n count[A[left]] -= 1\n if count[A[left]] == 0:\n count.pop(A[left])\n left += 1\n result += right-left+1\n return result\n \n return atMostK(A, K) - atMostK(A, K-1)\n\n\n# Time: O(n)\n# Space: O(k)\nclass Window(object):\n def __init__(self):\n self.__count = collections.defaultdict(int)\n\n def add(self, x):\n self.__count[x] += 1\n\n def remove(self, x):\n self.__count[x] -= 1\n if self.__count[x] == 0:\n self.__count.pop(x)\n \n def size(self):\n return len(self.__count)\n\n\nclass Solution2(object):\n def subarraysWithKDistinct(self, A, K):\n \"\"\"\n :type A: List[int]\n :type K: int\n :rtype: int\n \"\"\"\n window1, window2 = Window(), Window()\n result, left1, left2 = 0, 0, 0\n for i in A:\n window1.add(i)\n while window1.size() > K:\n window1.remove(A[left1])\n left1 += 1\n window2.add(i)\n while window2.size() >= K:\n window2.remove(A[left2])\n left2 += 1\n result += left2-left1\n return result\n"}} diff --git a/cp/cp-10468.jsonl b/cp/cp-10468.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b08fc9d9fbb1b56d66a8f124be47695ac596ca71 --- /dev/null +++ b/cp/cp-10468.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10468", "name": "LeetCode 0993: Cousins 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: Cousins in Binary Tree (Difficulty: Easy)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise.\nTwo nodes of a binary tree are cousins if they have the same depth with different parents.\nNote that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1.\n\nExample 1:\nInput: root = [1,2,3,4], x = 4, y = 3\nOutput: false\n\nExample 2:\nInput: root = [1,2,3,null,4,null,5], x = 5, y = 4\nOutput: true\n\nExample 3:\nInput: root = [1,2,3,null,4], x = 2, y = 3\nOutput: false\n\nConstraints:\n- The number of nodes in the tree is in the range [2, 100].\n- 1 <= Node.val <= 100\n- Each node has a unique value.\n- x != y\n- x and y are exist in the tree."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 isCousins(self, root, x, y):\n \"\"\"\n :type root: TreeNode\n :type x: int\n :type y: int\n :rtype: bool\n \"\"\"\n def dfs(root, x, depth, parent):\n if not root:\n return False\n if root.val == x:\n return True\n depth[0] += 1\n prev_parent, parent[0] = parent[0], root\n if dfs(root.left, x, depth, parent):\n return True\n parent[0] = root\n if dfs(root.right, x, depth, parent):\n return True\n parent[0] = prev_parent\n depth[0] -= 1\n return False\n \n depth_x, depth_y = [0], [0]\n parent_x, parent_y = [None], [None]\n return dfs(root, x, depth_x, parent_x) and \\\n dfs(root, y, depth_y, parent_y) and \\\n depth_x[0] == depth_y[0] and \\\n parent_x[0] != parent_y[0]\n \n \n"}} diff --git a/cp/cp-10469.jsonl b/cp/cp-10469.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a89a7eb0f3d3b9ccc7d202ee16d4a4861a59665a --- /dev/null +++ b/cp/cp-10469.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10469", "name": "LeetCode 0994: Rotting Oranges"} +{"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: Rotting Oranges (Difficulty: Medium)\nTags: Array, Breadth-First Search, Matrix\n\nYou are given an m x n grid where each cell can have one of three values:\nEvery minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.\nReturn the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.\n\nExample 1:\nInput: grid = [[2,1,1],[1,1,0],[0,1,1]]\nOutput: 4\n\nExample 2:\nInput: grid = [[2,1,1],[0,1,1],[1,0,1]]\nOutput: -1\nExplanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.\n\nExample 3:\nInput: grid = [[0,2]]\nOutput: 0\nExplanation: Since there are already no fresh oranges at minute 0, the answer is just 0.\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 10\n- grid[i][j] is 0, 1, or 2."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m * n)\n\nimport collections\n\n\nclass Solution(object):\n def orangesRotting(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n\n count = 0\n q = collections.deque()\n for r, row in enumerate(grid):\n for c, val in enumerate(row):\n if val == 2:\n q.append((r, c, 0))\n elif val == 1:\n count += 1\n\n result = 0\n while q:\n r, c, result = q.popleft()\n for d in directions:\n nr, nc = r+d[0], c+d[1]\n if not (0 <= nr < len(grid) and \\\n 0 <= nc < len(grid[r])):\n continue\n if grid[nr][nc] == 1:\n count -= 1\n grid[nr][nc] = 2\n q.append((nr, nc, result+1))\n return result if count == 0 else -1\n"}} diff --git a/cp/cp-10470.jsonl b/cp/cp-10470.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3d61d351ad951838264ca140d4ece0570eb63f51 --- /dev/null +++ b/cp/cp-10470.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10470", "name": "LeetCode 0995: Minimum Number Of K Consecutive Bit Flips"} +{"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: Minimum Number of K Consecutive Bit Flips (Difficulty: Hard)\nTags: Array, Bit Manipulation, Queue, Sliding Window, Prefix Sum\n\nYou are given a binary array nums and an integer k.\nA k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.\nReturn the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1.\nA subarray is a contiguous part of an array.\n\nExample 1:\nInput: nums = [0,1,0], k = 1\nOutput: 2\nExplanation: Flip nums[0], then flip nums[2].\n\nExample 2:\nInput: nums = [1,1,0], k = 2\nOutput: -1\nExplanation: No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].\n\nExample 3:\nInput: nums = [0,0,0,1,0,1,1,0], k = 3\nOutput: 3\nExplanation: \nFlip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]\nFlip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]\nFlip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= k <= nums.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minKBitFlips(self, A, K):\n \"\"\"\n :type A: List[int]\n :type K: int\n :rtype: int\n \"\"\"\n result, curr = 0, 0\n for i in range(len(A)):\n if i >= K:\n curr -= A[i-K]//2\n if curr & 1 ^ A[i] == 0:\n if i+K > len(A):\n return -1\n A[i] += 2\n curr, result = curr+1, result+1\n return result\n"}} diff --git a/cp/cp-10471.jsonl b/cp/cp-10471.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..545dba59a43ed276d752faab5f9d5a0271db9548 --- /dev/null +++ b/cp/cp-10471.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10471", "name": "LeetCode 0996: Number Of Squareful 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: Number of Squareful Arrays (Difficulty: Hard)\nTags: Array, Hash Table, Math, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask\n\nAn array is squareful if the sum of every pair of adjacent elements is a perfect square.\nGiven an integer array nums, return the number of permutations of nums that are squareful.\nTwo permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i].\n\nExample 1:\nInput: nums = [1,17,8]\nOutput: 2\nExplanation: [1,8,17] and [17,8,1] are the valid permutations.\n\nExample 2:\nInput: nums = [2,2,2]\nOutput: 1\n\nConstraints:\n- 1 <= nums.length <= 12\n- 0 <= nums[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n!)\n# Space: O(n^2)\n\nimport collections\n\n\nclass Solution(object):\n def numSquarefulPerms(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n def dfs(candidate, x, left, count, result):\n count[x] -= 1\n if left == 0:\n result[0] += 1\n for y in candidate[x]:\n if count[y]:\n dfs(candidate, y, left-1, count, result)\n count[x] += 1\n\n count = collections.Counter(A)\n candidate = {i: {j for j in count if int((i+j)**0.5) ** 2 == i+j} \n for i in count}\n\n result = [0]\n for x in count:\n dfs(candidate, x, len(A)-1, count, result)\n return result[0]\n"}} diff --git a/cp/cp-10472.jsonl b/cp/cp-10472.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a5fd62efa5d441caaeb3cb0d0d9f574b7359f60c --- /dev/null +++ b/cp/cp-10472.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10472", "name": "LeetCode 0997: Find The Town Judge"} +{"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 the Town Judge (Difficulty: Easy)\nTags: Array, Hash Table, Graph\n\nIn a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.\nIf the town judge exists, then:\nYou are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi. If a trust relationship does not exist in trust array, then such a trust relationship does not exist.\nReturn the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.\n\nExample 1:\nInput: n = 2, trust = [[1,2]]\nOutput: 2\n\nExample 2:\nInput: n = 3, trust = [[1,3],[2,3]]\nOutput: 3\n\nExample 3:\nInput: n = 3, trust = [[1,3],[2,3],[3,1]]\nOutput: -1\n\nConstraints:\n- 1 <= n <= 1000\n- 0 <= trust.length <= 10^4\n- trust[i].length == 2\n- All the pairs of trust are unique.\n- ai != bi\n- 1 <= ai, bi <= n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(t + n)\n# Space: O(n)\n\nclass Solution(object):\n def findJudge(self, N, trust):\n \"\"\"\n :type N: int\n :type trust: List[List[int]]\n :rtype: int\n \"\"\"\n degrees = [0]*N\n for i, j in trust:\n degrees[i-1] -= 1\n degrees[j-1] += 1\n for i in range(len(degrees)):\n if degrees[i] == N-1:\n return i+1\n return -1\n"}} diff --git a/cp/cp-10473.jsonl b/cp/cp-10473.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..db12ba05aeb01bc119ec727c2c77b379358672d0 --- /dev/null +++ b/cp/cp-10473.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10473", "name": "LeetCode 0998: Maximum Binary Tree 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: Maximum Binary Tree II (Difficulty: Medium)\nTags: Tree, Binary Tree\n\nA maximum tree is a tree where every node has a value greater than any other value in its subtree.\nYou are given the root of a maximum binary tree and an integer val.\nJust as in the previous problem, the given tree was constructed from a list a (root = Construct(a)) recursively with the following Construct(a) routine:\nNote that we were not given a directly, only a root node root = Construct(a).\nSuppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values.\nReturn Construct(b).\n\nExample 1:\nInput: root = [4,1,3,null,null,2], val = 5\nOutput: [5,4,null,1,3,null,null,2]\nExplanation: a = [1,4,2,3], b = [1,4,2,3,5]\n\nExample 2:\nInput: root = [5,2,4,null,1], val = 3\nOutput: [5,2,4,null,1,null,3]\nExplanation: a = [2,1,5,4], b = [2,1,5,4,3]\n\nExample 3:\nInput: root = [5,2,3,null,1], val = 4\nOutput: [5,2,4,null,1,3]\nExplanation: a = [2,1,5,3], b = [2,1,5,3,4]\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 100].\n- 1 <= Node.val <= 100\n- All the values of the tree are unique.\n- 1 <= val <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(h)\n# Space: O(1)\n\n# Definition for a binary tree node.\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 insertIntoMaxTree(self, root, val):\n \"\"\"\n :type root: TreeNode\n :type val: int\n :rtype: TreeNode\n \"\"\"\n if not root:\n return TreeNode(val)\n\n if val > root.val:\n node = TreeNode(val)\n node.left = root\n return node\n \n curr = root\n while curr.right and curr.right.val > val:\n curr = curr.right\n node = TreeNode(val)\n curr.right, node.left = node, curr.right\n return root\n"}} diff --git a/cp/cp-10474.jsonl b/cp/cp-10474.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..14621f845a604db7180908bd0ab00907c6f72387 --- /dev/null +++ b/cp/cp-10474.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10474", "name": "LeetCode 0999: Available Captures For Rook"} +{"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: Available Captures for Rook (Difficulty: Easy)\nTags: Array, Matrix, Simulation\n\nYou are given an 8 x 8 matrix representing a chessboard. There is exactly one white rook represented by 'R', some number of white bishops 'B', and some number of black pawns 'p'. Empty squares are represented by '.'.\nA rook can move any number of squares horizontally or vertically (up, down, left, right) until it reaches another piece or the edge of the board. A rook is attacking a pawn if it can move to the pawn's square in one move.\nNote: A rook cannot move through other pieces, such as bishops or pawns. This means a rook cannot attack a pawn if there is another piece blocking the path.\nReturn the number of pawns the white rook is attacking.\n\nExample 1:\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"R\",\".\",\".\",\".\",\"p\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput: 3\nExplanation:\nIn this example, the rook is attacking all the pawns.\n\nExample 2:\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"B\",\"R\",\"B\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput: 0\nExplanation:\nThe bishops are blocking the rook from attacking any of the pawns.\n\nExample 3:\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\"p\",\"p\",\".\",\"R\",\".\",\"p\",\"B\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput: 3\nExplanation:\nThe rook is attacking the pawns at positions b5, d6, and f5.\n\nConstraints:\n- board.length == 8\n- board[i].length == 8\n- board[i][j] is either 'R', '.', 'B', or 'p'\n- There is exactly one cell with board[i][j] == 'R'"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def numRookCaptures(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n\n r, c = None, None\n for i in range(8):\n if r is not None:\n break\n for j in range(8):\n if board[i][j] == 'R':\n r, c = i, j\n break\n\n result = 0\n for d in directions:\n nr, nc = r+d[0], c+d[1]\n while 0 <= nr < 8 and 0 <= nc < 8:\n if board[nr][nc] == 'p':\n result += 1\n if board[nr][nc] != '.':\n break\n nr, nc= nr+d[0], nc+d[1]\n return result\n"}} diff --git a/cp/cp-10475.jsonl b/cp/cp-10475.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..84e79d2a891b578f12f0aff6b7a717c6551b5274 --- /dev/null +++ b/cp/cp-10475.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10475", "name": "LeetCode 1000: Minimum Cost To Merge Stones"} +{"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: Minimum Cost to Merge Stones (Difficulty: Hard)\nTags: Array, Dynamic Programming, Prefix Sum\n\nThere are n piles of stones arranged in a row. The ith pile has stones[i] stones.\nA move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles.\nReturn the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.\n\nExample 1:\nInput: stones = [3,2,4,1], k = 2\nOutput: 20\nExplanation: We start with [3, 2, 4, 1].\nWe merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].\nWe merge [4, 1] for a cost of 5, and we are left with [5, 5].\nWe merge [5, 5] for a cost of 10, and we are left with [10].\nThe total cost was 20, and this is the minimum possible.\n\nExample 2:\nInput: stones = [3,2,4,1], k = 3\nOutput: -1\nExplanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.\n\nExample 3:\nInput: stones = [3,5,1,2,6], k = 3\nOutput: 25\nExplanation: We start with [3, 5, 1, 2, 6].\nWe merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].\nWe merge [3, 8, 6] for a cost of 17, and we are left with [17].\nThe total cost was 25, and this is the minimum possible.\n\nConstraints:\n- n == stones.length\n- 1 <= n <= 30\n- 1 <= stones[i] <= 100\n- 2 <= k <= 30"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3 / k)\n# Space: O(n^2)\n\nclass Solution(object):\n def mergeStones(self, stones, K):\n \"\"\"\n :type stones: List[int]\n :type K: int\n :rtype: int\n \"\"\"\n if (len(stones)-1) % (K-1):\n return -1\n prefix = [0]\n for x in stones:\n prefix.append(prefix[-1]+x)\n dp = [[0]*len(stones) for _ in range(len(stones))]\n for l in range(K-1, len(stones)):\n for i in range(len(stones)-l):\n dp[i][i+l] = min(dp[i][j]+dp[j+1][i+l] for j in range(i, i+l, K-1))\n if l % (K-1) == 0:\n dp[i][i+l] += prefix[i+l+1] - prefix[i]\n return dp[0][len(stones)-1]\n"}} diff --git a/cp/cp-10476.jsonl b/cp/cp-10476.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5039c7fe791bdc10dddac18bcf8e2b7bfac73614 --- /dev/null +++ b/cp/cp-10476.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10476", "name": "LeetCode 1001: Grid Illumination"} +{"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: Grid Illumination (Difficulty: Hard)\nTags: Array, Hash Table\n\nThere is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off.\nYou are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on.\nWhen a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal.\nYou are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj].\nReturn an array of integers ans, where ans[j] should be 1 if the cell in the jth query was illuminated, or 0 if the lamp was not.\n\nExample 1:\nInput: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]\nOutput: [1,0]\nExplanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].\nThe 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.\n\nThe 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.\n\nExample 2:\nInput: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]\nOutput: [1,1]\n\nExample 3:\nInput: n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]\nOutput: [1,1,0]\n\nConstraints:\n- 1 <= n <= 10^9\n- 0 <= lamps.length <= 20000\n- 0 <= queries.length <= 20000\n- lamps[i].length == 2\n- 0 <= rowi, coli < n\n- queries[j].length == 2\n- 0 <= rowj, colj < n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(l + q)\n# Space: O(l)\n\nimport collections\n\n\nclass Solution(object):\n def gridIllumination(self, N, lamps, queries):\n \"\"\"\n :type N: int\n :type lamps: List[List[int]]\n :type queries: List[List[int]]\n :rtype: List[int]\n \"\"\"\n lookup = set()\n row = collections.defaultdict(int)\n col = collections.defaultdict(int)\n diag = collections.defaultdict(int)\n anti = collections.defaultdict(int)\n \n for r, c in lamps:\n if (r, c) in lookup:\n continue\n lookup.add((r, c))\n row[r] += 1\n col[c] += 1\n diag[r-c] += 1\n anti[r+c] += 1\n \n result = []\n for r, c in queries:\n if not (row[r] or col[c] or diag[r-c] or anti[r+c]):\n result.append(0)\n continue\n result.append(1) \n for nr in range(max(r-1, 0), min(r+1, N-1)+1):\n for nc in range(max(c-1, 0), min(c+1, N-1)+1):\n if (nr, nc) not in lookup:\n continue\n lookup.remove((nr, nc))\n row[nr] -= 1\n col[nc] -= 1\n diag[nr-nc] -= 1\n anti[nr+nc] -= 1\n return result\n"}} diff --git a/cp/cp-10477.jsonl b/cp/cp-10477.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a9f844c972157045e51a693839f49ff21d4ae3e0 --- /dev/null +++ b/cp/cp-10477.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10477", "name": "LeetCode 1002: Find Common Characters"} +{"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 Common Characters (Difficulty: Easy)\nTags: Array, Hash Table, String\n\nGiven a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.\n\nExample 1:\nInput: words = [\"bella\",\"label\",\"roller\"]\nOutput: [\"e\",\"l\",\"l\"]\n\nExample 2:\nInput: words = [\"cool\",\"lock\",\"cook\"]\nOutput: [\"c\",\"o\"]\n\nConstraints:\n- 1 <= words.length <= 100\n- 1 <= words[i].length <= 100\n- words[i] consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * l)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def commonChars(self, A):\n \"\"\"\n :type A: List[str]\n :rtype: List[str]\n \"\"\"\n result = collections.Counter(A[0])\n for a in A:\n result &= collections.Counter(a)\n return list(result.elements())\n"}} diff --git a/cp/cp-10478.jsonl b/cp/cp-10478.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..abc466f1fa6000387dfa74ec7495e5097b65d466 --- /dev/null +++ b/cp/cp-10478.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10478", "name": "LeetCode 1003: Check If Word Is Valid After Substitutions"} +{"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: Check If Word Is Valid After Substitutions (Difficulty: Medium)\nTags: String, Stack\n\nGiven a string s, determine if it is valid.\nA string s is valid if, starting with an empty string t = \"\", you can transform t into s after performing the following operation any number of times:\nReturn true if s is a valid string, otherwise, return false.\n\nExample 1:\nInput: s = \"aabcbc\"\nOutput: true\nExplanation:\n\"\" -> \"abc\" -> \"aabcbc\"\nThus, \"aabcbc\" is valid.\n\nExample 2:\nInput: s = \"abcabcababcc\"\nOutput: true\nExplanation:\n\"\" -> \"abc\" -> \"abcabc\" -> \"abcabcabc\" -> \"abcabcababcc\"\nThus, \"abcabcababcc\" is valid.\n\nExample 3:\nInput: s = \"abccba\"\nOutput: false\nExplanation: It is impossible to get \"abccba\" using the operation.\n\nConstraints:\n- 1 <= s.length <= 2 * 10^4\n- s consists of letters 'a', 'b', and 'c'"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def isValid(self, S):\n \"\"\"\n :type S: str\n :rtype: bool\n \"\"\"\n stack = []\n for i in S:\n if i == 'c':\n if stack[-2:] == ['a', 'b']:\n stack.pop()\n stack.pop()\n else:\n return False\n else:\n stack.append(i)\n return not stack\n"}} diff --git a/cp/cp-10479.jsonl b/cp/cp-10479.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fa5ed8633eba16bbbad4a0f3b923c09ea69da49c --- /dev/null +++ b/cp/cp-10479.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10479", "name": "LeetCode 1004: Max Consecutive Ones 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: Max Consecutive Ones III (Difficulty: Medium)\nTags: Array, Binary Search, Sliding Window, Prefix Sum\n\nGiven a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.\n\nExample 1:\nInput: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2\nOutput: 6\nExplanation: [1,1,1,0,0,1,1,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.\n\nExample 2:\nInput: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3\nOutput: 10\nExplanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- nums[i] is either 0 or 1.\n- 0 <= k <= nums.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def longestOnes(self, A, K):\n \"\"\"\n :type A: List[int]\n :type K: int\n :rtype: int\n \"\"\"\n result, i = 0, 0\n for j in range(len(A)):\n K -= int(A[j] == 0)\n while K < 0:\n K += int(A[i] == 0)\n i += 1\n result = max(result, j-i+1)\n return result\n"}} diff --git a/cp/cp-10480.jsonl b/cp/cp-10480.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8a0aa9be78bdbad1bd6ec7967cab8d0ea2ef7ba4 --- /dev/null +++ b/cp/cp-10480.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10480", "name": "LeetCode 1005: Maximize Sum Of Array After K Negations"} +{"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: Maximize Sum Of Array After K Negations (Difficulty: Easy)\nTags: Array, Greedy, Sorting\n\nGiven an integer array nums and an integer k, modify the array in the following way:\nYou should apply this process exactly k times. You may choose the same index i multiple times.\nReturn the largest possible sum of the array after modifying it in this way.\n\nExample 1:\nInput: nums = [4,2,3], k = 1\nOutput: 5\nExplanation: Choose index 1 and nums becomes [4,-2,3].\n\nExample 2:\nInput: nums = [3,-1,0,2], k = 3\nOutput: 6\nExplanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].\n\nExample 3:\nInput: nums = [2,-3,-1,5,-4], k = 2\nOutput: 13\nExplanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4].\n\nConstraints:\n- 1 <= nums.length <= 10^4\n- -100 <= nums[i] <= 100\n- 1 <= k <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n) ~ O(n^2), O(n) on average.\n# Space: O(1)\n\nimport random\n\n\n# quick select solution\nclass Solution(object):\n def largestSumAfterKNegations(self, A, K):\n \"\"\"\n :type A: List[int]\n :type K: int\n :rtype: int\n \"\"\"\n def kthElement(nums, k, compare):\n def PartitionAroundPivot(left, right, pivot_idx, nums, compare):\n new_pivot_idx = left\n nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]\n for i in range(left, right):\n if compare(nums[i], nums[right]):\n nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]\n new_pivot_idx += 1\n\n nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]\n return new_pivot_idx\n\n left, right = 0, len(nums) - 1\n while left <= right:\n pivot_idx = random.randint(left, right)\n new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, nums, compare)\n if new_pivot_idx == k:\n return\n elif new_pivot_idx > k:\n right = new_pivot_idx - 1\n else: # new_pivot_idx < k.\n left = new_pivot_idx + 1\n \n kthElement(A, K, lambda a, b: a < b)\n remain = K\n for i in range(K):\n if A[i] < 0:\n A[i] = -A[i]\n remain -= 1\n return sum(A) - ((remain)%2)*min(A)*2\n\n\n# Time: O(nlogn)\n# Space: O(1)\nclass Solution2(object):\n def largestSumAfterKNegations(self, A, K):\n \"\"\"\n :type A: List[int]\n :type K: int\n :rtype: int\n \"\"\"\n A.sort()\n remain = K\n for i in range(K):\n if A[i] >= 0:\n break\n A[i] = -A[i]\n remain -= 1\n return sum(A) - (remain%2)*min(A)*2\n"}} diff --git a/cp/cp-10481.jsonl b/cp/cp-10481.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a5c95140c4ebbd64716051b817b841ab0deba1c1 --- /dev/null +++ b/cp/cp-10481.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10481", "name": "LeetCode 1006: Clumsy Factorial"} +{"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: Clumsy Factorial (Difficulty: Medium)\nTags: Math, Stack, Simulation\n\nThe factorial of a positive integer n is the product of all positive integers less than or equal to n.\nWe make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*', divide '/', add '+', and subtract '-' in this order.\nHowever, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.\nAdditionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11.\nGiven an integer n, return the clumsy factorial of n.\n\nExample 1:\nInput: n = 4\nOutput: 7\nExplanation: 7 = 4 * 3 / 2 + 1\n\nExample 2:\nInput: n = 10\nOutput: 12\nExplanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1\n\nConstraints:\n- 1 <= n <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\n# observation:\n# i*(i-1)/(i-2) = i+1+2/(i-2)\n# if i = 3 => i*(i-1)/(i-2) = i + 3\n# if i = 4 => i*(i-1)/(i-2) = i + 2\n# if i >= 5 => i*(i-1)/(i-2) = i + 1\n#\n# clumsy(N):\n# if N = 1 => N\n# if N = 2 => N\n# if N = 3 => N + 3\n# if N = 4 => N + 2 + 1 = N + 3\n# if N > 4 and N % 4 == 1 => N + 1 + (... = 0) + 2 - 1 = N + 2\n# if N > 4 and N % 4 == 2 => N + 1 + (... = 0) + 3 - 2 * 1 = N + 2\n# if N > 4 and N % 4 == 3 => N + 1 + (... = 0) + 4 - 3 * 2 / 1 = N - 1\n# if N > 4 and N % 4 == 0 => N + 1 + (... = 0) + 5 - (4*3/2) + 1 = N + 1\n\nclass Solution(object):\n def clumsy(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n if N <= 2:\n return N\n if N <= 4:\n return N+3\n \n if N % 4 == 0:\n return N+1\n elif N % 4 <= 2:\n return N+2\n return N-1\n"}} diff --git a/cp/cp-10482.jsonl b/cp/cp-10482.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2a03cda2b20f6028a949c89f724c0d0de4176113 --- /dev/null +++ b/cp/cp-10482.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10482", "name": "LeetCode 1007: Minimum Domino Rotations For Equal Row"} +{"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: Minimum Domino Rotations For Equal Row (Difficulty: Medium)\nTags: Array, Greedy\n\nIn a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)\nWe may rotate the ith domino, so that tops[i] and bottoms[i] swap values.\nReturn the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same.\nIf it cannot be done, return -1.\n\nExample 1:\nInput: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]\nOutput: 2\nExplanation: \nThe first figure represents the dominoes as given by tops and bottoms: before we do any rotations.\nIf we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.\n\nExample 2:\nInput: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]\nOutput: -1\nExplanation: \nIn this case, it is not possible to rotate the dominoes to make one row of values equal.\n\nConstraints:\n- 2 <= tops.length <= 2 * 10^4\n- bottoms.length == tops.length\n- 1 <= tops[i], bottoms[i] <= 6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def minDominoRotations(self, A, B):\n \"\"\"\n :type A: List[int]\n :type B: List[int]\n :rtype: int\n \"\"\"\n intersect = reduce(set.__and__, [set(d) for d in itertools.izip(A, B)])\n if not intersect:\n return -1\n x = intersect.pop()\n return min(len(A)-A.count(x), len(B)-B.count(x))\n"}} diff --git a/cp/cp-10483.jsonl b/cp/cp-10483.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2f82ca521643005fa198a28075b6396d1333eb87 --- /dev/null +++ b/cp/cp-10483.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10483", "name": "LeetCode 1008: Construct Binary Search Tree From Preorder Traversal"} +{"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 Binary Search Tree from Preorder Traversal (Difficulty: Medium)\nTags: Array, Stack, Tree, Binary Search Tree, Monotonic Stack, Binary Tree\n\nGiven an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.\nIt is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.\nA binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.\nA preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.\n\nExample 1:\nInput: preorder = [8,5,1,7,10,12]\nOutput: [8,5,10,1,7,null,12]\n\nExample 2:\nInput: preorder = [1,3]\nOutput: [1,null,3]\n\nConstraints:\n- 1 <= preorder.length <= 100\n- 1 <= preorder[i] <= 1000\n- All the values of preorder are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 bstFromPreorder(self, preorder):\n \"\"\"\n :type preorder: List[int]\n :rtype: TreeNode\n \"\"\"\n def bstFromPreorderHelper(preorder, left, right, index):\n if index[0] == len(preorder) or \\\n preorder[index[0]] < left or \\\n preorder[index[0]] > right:\n return None\n\n root = TreeNode(preorder[index[0]])\n index[0] += 1\n root.left = bstFromPreorderHelper(preorder, left, root.val, index)\n root.right = bstFromPreorderHelper(preorder, root.val, right, index)\n return root\n \n return bstFromPreorderHelper(preorder, float(\"-inf\"), float(\"inf\"), [0])\n"}} diff --git a/cp/cp-10485.jsonl b/cp/cp-10485.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9198a3ce80710660a0ea0f243bdcd52d25c92bbc --- /dev/null +++ b/cp/cp-10485.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10485", "name": "LeetCode 1010: Pairs Of Songs With Total Durations Divisible By 60"} +{"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: Pairs of Songs With Total Durations Divisible by 60 (Difficulty: Medium)\nTags: Array, Hash Table, Counting\n\nYou are given a list of songs where the ith song has a duration of time[i] seconds.\nReturn the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.\n\nExample 1:\nInput: time = [30,20,150,100,40]\nOutput: 3\nExplanation: Three pairs have a total duration divisible by 60:\n(time[0] = 30, time[2] = 150): total duration 180\n(time[1] = 20, time[3] = 100): total duration 120\n(time[1] = 20, time[4] = 40): total duration 60\n\nExample 2:\nInput: time = [60,60,60]\nOutput: 3\nExplanation: All three pairs have a total duration of 120, which is divisible by 60.\n\nConstraints:\n- 1 <= time.length <= 6 * 10^4\n- 1 <= time[i] <= 500"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def numPairsDivisibleBy60(self, time):\n \"\"\"\n :type time: List[int]\n :rtype: int\n \"\"\"\n result = 0\n count = collections.Counter()\n for t in time:\n result += count[-t%60]\n count[t%60] += 1\n return result\n"}} diff --git a/cp/cp-10486.jsonl b/cp/cp-10486.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..673dc927ef3534e5ead1a08fadb764616012b033 --- /dev/null +++ b/cp/cp-10486.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10486", "name": "LeetCode 1011: Capacity To Ship Packages Within D Days"} +{"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: Capacity To Ship Packages Within D Days (Difficulty: Medium)\nTags: Array, Binary Search\n\nA conveyor belt has packages that must be shipped from one port to another within days days.\nThe ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.\nReturn the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.\n\nExample 1:\nInput: weights = [1,2,3,4,5,6,7,8,9,10], days = 5\nOutput: 15\nExplanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:\n1st day: 1, 2, 3, 4, 5\n2nd day: 6, 7\n3rd day: 8\n4th day: 9\n5th day: 10\n\nNote that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.\n\nExample 2:\nInput: weights = [3,2,2,4,1,4], days = 3\nOutput: 6\nExplanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:\n1st day: 3, 2\n2nd day: 2, 4\n3rd day: 1, 4\n\nExample 3:\nInput: weights = [1,2,3,1,1], days = 4\nOutput: 3\nExplanation:\n1st day: 1\n2nd day: 2\n3rd day: 3\n4th day: 1, 1\n\nConstraints:\n- 1 <= days <= weights.length <= 5 * 10^4\n- 1 <= weights[i] <= 500"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogr)\n# Space: O(1)\n\nclass Solution(object):\n def shipWithinDays(self, weights, D):\n \"\"\"\n :type weights: List[int]\n :type D: int\n :rtype: int\n \"\"\"\n def possible(weights, D, mid):\n result, curr = 1, 0\n for w in weights:\n if curr+w > mid:\n result += 1\n curr = 0\n curr += w\n return result <= D\n \n left, right = max(weights), sum(weights)\n while left <= right:\n mid = left + (right-left)//2\n if possible(weights, D, mid):\n right = mid-1\n else:\n left = mid+1\n return left\n"}} diff --git a/cp/cp-10487.jsonl b/cp/cp-10487.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eeb1953cc3afca2aad2489c98b9fef09df1e7f5d --- /dev/null +++ b/cp/cp-10487.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10487", "name": "LeetCode 1012: Numbers With Repeated Digits"} +{"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: Numbers With Repeated Digits (Difficulty: Hard)\nTags: Math, Dynamic Programming\n\nGiven an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit.\n\nExample 1:\nInput: n = 20\nOutput: 1\nExplanation: The only positive number (<= 20) with at least 1 repeated digit is 11.\n\nExample 2:\nInput: n = 100\nOutput: 10\nExplanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.\n\nExample 3:\nInput: n = 1000\nOutput: 262\n\nConstraints:\n- 1 <= n <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(logn)\n\nclass Solution(object):\n def numDupDigitsAtMostN(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n def P(m, n):\n result = 1\n for _ in range(n):\n result *= m\n m -= 1\n return result\n\n digits = map(int, str(N+1))\n result = 0\n\n # Given 321\n #\n # 1. count numbers without repeated digits:\n # - X\n # - XX\n for i in range(1, len(digits)):\n result += P(9, 1)*P(9, i-1)\n \n # 2. count numbers without repeated digits:\n # - 1XX ~ 3XX\n # - 30X ~ 32X\n # - 320 ~ 321\n prefix_set = set()\n for i, x in enumerate(digits):\n for y in range(1 if i == 0 else 0, x):\n if y in prefix_set:\n continue\n result += P(9-i, len(digits)-i-1)\n if x in prefix_set:\n break\n prefix_set.add(x)\n return N-result\n"}} diff --git a/cp/cp-10488.jsonl b/cp/cp-10488.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..879d57ddf3e42d868c6f8bf7aa7cd4d5e45a1ae9 --- /dev/null +++ b/cp/cp-10488.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10488", "name": "LeetCode 1013: Partition Array Into Three Parts With Equal Sum"} +{"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: Partition Array Into Three Parts With Equal Sum (Difficulty: Easy)\nTags: Array, Greedy\n\nGiven an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums.\nFormally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])\n\nExample 1:\nInput: arr = [0,2,1,-6,6,-7,9,1,2,0,1]\nOutput: true\nExplanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1\n\nExample 2:\nInput: arr = [0,2,1,-6,6,7,9,-1,2,0,1]\nOutput: false\n\nExample 3:\nInput: arr = [3,3,6,5,-2,2,5,1,-9,4]\nOutput: true\nExplanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4\n\nConstraints:\n- 3 <= arr.length <= 5 * 10^4\n- -10^4 <= arr[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def canThreePartsEqualSum(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: bool\n \"\"\"\n total = sum(A)\n if total % 3 != 0:\n return False\n parts, curr = 0, 0\n for x in A:\n curr += x\n if curr == total//3:\n parts += 1\n curr = 0\n return parts >= 3\n"}} diff --git a/cp/cp-10489.jsonl b/cp/cp-10489.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3e58e4fc95de57f5ce3ae9b10b4e7bf414f79021 --- /dev/null +++ b/cp/cp-10489.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10489", "name": "LeetCode 1014: Best Sightseeing Pair"} +{"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: Best Sightseeing Pair (Difficulty: Medium)\nTags: Array, Dynamic Programming\n\nYou are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.\nThe score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them.\nReturn the maximum score of a pair of sightseeing spots.\n\nExample 1:\nInput: values = [8,1,5,2,6]\nOutput: 11\nExplanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11\n\nExample 2:\nInput: values = [1,2]\nOutput: 2\n\nConstraints:\n- 2 <= values.length <= 5 * 10^4\n- 1 <= values[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxScoreSightseeingPair(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n result, curr = 0, 0\n for x in A:\n result = max(result, curr+x)\n curr = max(curr, x)-1\n return result\n"}} diff --git a/cp/cp-10490.jsonl b/cp/cp-10490.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cdb850f120bc637365daf5562a14d30740157860 --- /dev/null +++ b/cp/cp-10490.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10490", "name": "LeetCode 1015: Smallest Integer Divisible By K"} +{"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: Smallest Integer Divisible by K (Difficulty: Medium)\nTags: Hash Table, Math\n\nGiven a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1.\nReturn the length of n. If there is no such n, return -1.\nNote: n may not fit in a 64-bit signed integer.\n\nExample 1:\nInput: k = 1\nOutput: 1\nExplanation: The smallest answer is n = 1, which has length 1.\n\nExample 2:\nInput: k = 2\nOutput: -1\nExplanation: There is no such positive integer n divisible by 2.\n\nExample 3:\nInput: k = 3\nOutput: 3\nExplanation: The smallest answer is n = 111, which has length 3.\n\nConstraints:\n- 1 <= k <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(k)\n# Space: O(1)\n\nclass Solution(object):\n def smallestRepunitDivByK(self, K):\n \"\"\"\n :type K: int\n :rtype: int\n \"\"\"\n # by observation, K % 2 = 0 or K % 5 = 0, it is impossible\n if K % 2 == 0 or K % 5 == 0:\n return -1\n\n # let f(N) is a N-length integer only containing digit 1\n # if there is no N in range (1..K) s.t. f(N) % K = 0\n # => there must be K remainders of f(N) % K in range (1..K-1) excluding 0\n # => due to pigeonhole principle, there must be at least 2 same remainders\n # => there must be some x, y in range (1..K) and x > y s.t. f(x) % K = f(y) % K\n # => (f(x) - f(y)) % K = 0\n # => (f(x-y) * 10^y) % K = 0\n # => due to (x-y) in range (1..K)\n # => f(x-y) % K != 0\n # => 10^y % K = 0\n # => K % 2 = 0 or K % 5 = 0\n # => -><-\n # it proves that there must be some N in range (1..K) s.t. f(N) % K = 0\n result = 0\n for N in range(1, K+1):\n result = (result*10+1) % K\n if not result:\n return N\n assert(False)\n return -1 # never reach\n"}} diff --git a/cp/cp-10491.jsonl b/cp/cp-10491.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1d1ee383d13c5e82a8ae94ec2a1f1d207e38eca7 --- /dev/null +++ b/cp/cp-10491.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10491", "name": "LeetCode 1016: Binary String With Substrings Representing 1 To N"} +{"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: Binary String With Substrings Representing 1 To N (Difficulty: Medium)\nTags: Hash Table, String, Bit Manipulation, Sliding Window\n\nGiven a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise.\nA substring is a contiguous sequence of characters within a string.\n\nExample 1:\nInput: s = \"0110\", n = 3\nOutput: true\n\nExample 2:\nInput: s = \"0110\", n = 4\nOutput: false\n\nConstraints:\n- 1 <= s.length <= 1000\n- s[i] is either '0' or '1'.\n- 1 <= n <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2), n is the length of S\n# Space: O(1)\n\nclass Solution(object):\n def queryString(self, S, N):\n \"\"\"\n :type S: str\n :type N: int\n :rtype: bool\n \"\"\"\n # since S with length n has at most different n-k+1 k-digit numbers\n # => given S with length n, valid N is at most 2(n-k+1)\n # => valid N <= 2(n-k+1) < 2n = 2 * S.length\n return all(bin(i)[2:] in S for i in reversed(range(N//2, N+1)))\n"}} diff --git a/cp/cp-10492.jsonl b/cp/cp-10492.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..57397fe9a367a8389d51b1b2763e146913d16579 --- /dev/null +++ b/cp/cp-10492.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10492", "name": "LeetCode 1017: Convert To Base 2"} +{"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: Convert to Base -2 (Difficulty: Medium)\nTags: Math\n\nGiven an integer n, return a binary string representing its representation in base -2.\nNote that the returned string should not have leading zeros unless the string is \"0\".\n\nExample 1:\nInput: n = 2\nOutput: \"110\"\nExplantion: (-2)2 + (-2)1 = 2\n\nExample 2:\nInput: n = 3\nOutput: \"111\"\nExplantion: (-2)2 + (-2)1 + (-2)0 = 3\n\nExample 3:\nInput: n = 4\nOutput: \"100\"\nExplantion: (-2)2 = 4\n\nConstraints:\n- 0 <= n <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nclass Solution(object):\n def baseNeg2(self, N):\n \"\"\"\n :type N: int\n :rtype: str\n \"\"\"\n result = []\n while N:\n result.append(str(-N & 1)) # N % -2\n N = -(N >> 1) # N //= -2\n result.reverse()\n return \"\".join(result) if result else \"0\"\n\n\n# Time: O(logn)\n# Space: O(1)\nclass Solution2(object):\n def baseNeg2(self, N):\n \"\"\"\n :type N: int\n :rtype: str\n \"\"\"\n BASE = -2\n result = []\n while N:\n N, r = divmod(N, BASE)\n if r < 0:\n r -= BASE\n N += 1\n result.append(str(r))\n result.reverse()\n return \"\".join(result) if result else \"0\"\n"}} diff --git a/cp/cp-10494.jsonl b/cp/cp-10494.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6ca64524cbbd97433c6f95339de4e737d238c8d7 --- /dev/null +++ b/cp/cp-10494.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10494", "name": "LeetCode 1019: Next Greater Node In Linked List"} +{"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: Next Greater Node In Linked List (Difficulty: Medium)\nTags: Array, Linked List, Stack, Monotonic Stack\n\nYou are given the head of a linked list with n nodes.\nFor each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.\nReturn an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.\n\nExample 1:\nInput: head = [2,1,5]\nOutput: [5,5,0]\n\nExample 2:\nInput: head = [2,7,4,3,5]\nOutput: [7,0,5,5,0]\n\nConstraints:\n- The number of nodes in the list is n.\n- 1 <= n <= 10^4\n- 1 <= Node.val <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def nextLargerNodes(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: List[int]\n \"\"\"\n result, stk = [], []\n while head:\n while stk and stk[-1][1] < head.val:\n result[stk.pop()[0]] = head.val\n stk.append([len(result), head.val])\n result.append(0)\n head = head.next\n return result\n"}} diff --git a/cp/cp-10495.jsonl b/cp/cp-10495.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..030b705aa2bc1788979958bd37d3edd5bf361f6f --- /dev/null +++ b/cp/cp-10495.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10495", "name": "LeetCode 1020: Number Of Enclaves"} +{"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 Enclaves (Difficulty: Medium)\nTags: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix\n\nYou are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.\nA move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.\nReturn the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.\n\nExample 1:\nInput: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]\nOutput: 3\nExplanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.\n\nExample 2:\nInput: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]\nOutput: 0\nExplanation: All 1s are either on the boundary or can reach the boundary.\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 500\n- grid[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m * n)\n\nclass Solution(object):\n def numEnclaves(self, A):\n \"\"\"\n :type A: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n def dfs(A, i, j):\n if not (0 <= i < len(A) and 0 <= j < len(A[0]) and A[i][j]):\n return\n A[i][j] = 0\n for d in directions:\n dfs(A, i+d[0], j+d[1])\n \n for i in range(len(A)):\n dfs(A, i, 0)\n dfs(A, i, len(A[0])-1)\n for j in range(1, len(A[0])-1):\n dfs(A, 0, j)\n dfs(A, len(A)-1, j)\n return sum(sum(row) for row in A)\n \n"}} diff --git a/cp/cp-10496.jsonl b/cp/cp-10496.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..44c9d5729485db1bcc703c51162039166dc8605d --- /dev/null +++ b/cp/cp-10496.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10496", "name": "LeetCode 1021: Remove Outermost Parentheses"} +{"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: Remove Outermost Parentheses (Difficulty: Easy)\nTags: String, Stack\n\nA valid parentheses string is either empty \"\", \"(\" + A + \")\", or A + B, where A and B are valid parentheses strings, and + represents string concatenation.\nA valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B, with A and B nonempty valid parentheses strings.\nGiven a valid parentheses string s, consider its primitive decomposition: s = P1 + P2 + ... + Pk, where Pi are primitive valid parentheses strings.\nReturn s after removing the outermost parentheses of every primitive string in the primitive decomposition of s.\n\nExample 1:\nInput: s = \"(()())(())\"\nOutput: \"()()()\"\nExplanation: \nThe input string is \"(()())(())\", with primitive decomposition \"(()())\" + \"(())\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" = \"()()()\".\n\nExample 2:\nInput: s = \"(()())(())(()(()))\"\nOutput: \"()()()()(())\"\nExplanation: \nThe input string is \"(()())(())(()(()))\", with primitive decomposition \"(()())\" + \"(())\" + \"(()(()))\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" + \"()(())\" = \"()()()()(())\".\n\nExample 3:\nInput: s = \"()()\"\nOutput: \"\"\nExplanation: \nThe input string is \"()()\", with primitive decomposition \"()\" + \"()\".\nAfter removing outer parentheses of each part, this is \"\" + \"\" = \"\".\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s[i] is either '(' or ')'.\n- s is a valid parentheses string."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def removeOuterParentheses(self, S):\n \"\"\"\n :type S: str\n :rtype: str\n \"\"\"\n deep = 1\n result, cnt = [], 0\n for c in S:\n if c == '(' and cnt >= deep:\n result.append(c)\n if c == ')' and cnt > deep:\n result.append(c)\n cnt += 1 if c == '(' else -1\n return \"\".join(result)\n"}} diff --git a/cp/cp-10497.jsonl b/cp/cp-10497.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6e18685391cd58d51d52010a613de1d3114138d5 --- /dev/null +++ b/cp/cp-10497.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10497", "name": "LeetCode 1022: Sum Of Root To Leaf Binary 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 Root To Leaf Binary Numbers (Difficulty: Easy)\nTags: Tree, Depth-First Search, Binary Tree\n\nYou are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit.\nFor all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers.\nThe test cases are generated so that the answer fits in a 32-bits integer.\n\nExample 1:\nInput: root = [1,0,1,0,1,0,1]\nOutput: 22\nExplanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22\n\nExample 2:\nInput: root = [0]\nOutput: 0\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 1000].\n- Node.val is 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 sumRootToLeaf(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n M = 10**9 + 7\n def sumRootToLeafHelper(root, val):\n if not root:\n return 0\n val = (val*2 + root.val) % M\n if not root.left and not root.right:\n return val\n return (sumRootToLeafHelper(root.left, val) +\n sumRootToLeafHelper(root.right, val)) % M\n \n return sumRootToLeafHelper(root, 0)\n"}} diff --git a/cp/cp-10498.jsonl b/cp/cp-10498.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e153f95ee1d3809a11753c8aa9b39cc01ddf0d4d --- /dev/null +++ b/cp/cp-10498.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10498", "name": "LeetCode 1023: Camelcase Matching"} +{"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: Camelcase Matching (Difficulty: Medium)\nTags: Array, Two Pointers, String, Trie, String Matching\n\nGiven an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise.\nA query word queries[i] matches pattern if you can insert lowercase English letters into the pattern so that it equals the query. You may insert a character at any position in pattern or you may choose not to insert any characters at all.\n\nExample 1:\nInput: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FB\"\nOutput: [true,false,true,true,false]\nExplanation: \"FooBar\" can be generated like this \"F\" + \"oo\" + \"B\" + \"ar\".\n\"FootBall\" can be generated like this \"F\" + \"oot\" + \"B\" + \"all\".\n\"FrameBuffer\" can be generated like this \"F\" + \"rame\" + \"B\" + \"uffer\".\n\nExample 2:\nInput: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBa\"\nOutput: [true,false,true,false,false]\nExplanation: \"FooBar\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\".\n\"FootBall\" can be generated like this \"Fo\" + \"ot\" + \"Ba\" + \"ll\".\n\nExample 3:\nInput: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBaT\"\nOutput: [false,true,false,false,false]\nExplanation: \"FooBarTest\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\" + \"T\" + \"est\".\n\nConstraints:\n- 1 <= pattern.length, queries.length <= 100\n- 1 <= queries[i].length <= 100\n- queries[i] and pattern consist of English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * l), n is number of quries\n# , l is length of query\n# Space: O(1)\n\nclass Solution(object):\n def camelMatch(self, queries, pattern):\n \"\"\"\n :type queries: List[str]\n :type pattern: str\n :rtype: List[bool]\n \"\"\"\n def is_matched(query, pattern):\n i = 0\n for c in query:\n if i < len(pattern) and pattern[i] == c:\n i += 1\n elif c.isupper():\n return False\n return i == len(pattern)\n \n result = []\n for query in queries:\n result.append(is_matched(query, pattern))\n return result\n"}} diff --git a/cp/cp-10499.jsonl b/cp/cp-10499.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1ea5b32a8e20ac1400cd3ded5e106f13a8c7e55c --- /dev/null +++ b/cp/cp-10499.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10499", "name": "LeetCode 1024: Video Stitching"} +{"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: Video Stitching (Difficulty: Medium)\nTags: Array, Dynamic Programming, Greedy\n\nYou are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths.\nEach video clip is described by an array clips where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi.\nWe can cut these clips into segments freely.\nReturn the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1.\n\nExample 1:\nInput: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10\nOutput: 3\nExplanation: We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.\nThen, we can reconstruct the sporting event as follows:\nWe cut [1,9] into segments [1,2] + [2,8] + [8,9].\nNow we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].\n\nExample 2:\nInput: clips = [[0,1],[1,2]], time = 5\nOutput: -1\nExplanation: We cannot cover [0,5] with only [0,1] and [1,2].\n\nExample 3:\nInput: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9\nOutput: 3\nExplanation: We can take clips [0,4], [4,7], and [6,9].\n\nConstraints:\n- 1 <= clips.length <= 100\n- 0 <= starti <= endi <= 100\n- 1 <= time <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def videoStitching(self, clips, T):\n \"\"\"\n :type clips: List[List[int]]\n :type T: int\n :rtype: int\n \"\"\"\n if T == 0:\n return 0\n result = 1\n curr_reachable, reachable = 0, 0\n clips.sort()\n for left, right in clips:\n if left > reachable:\n break\n elif left > curr_reachable:\n curr_reachable = reachable\n result += 1\n reachable = max(reachable, right)\n if reachable >= T:\n return result\n return -1\n"}} diff --git a/cp/cp-10500.jsonl b/cp/cp-10500.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5dc9a69f1df6c9957ce3412d2207dc4cf4947015 --- /dev/null +++ b/cp/cp-10500.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10500", "name": "LeetCode 1025: Divisor Game"} +{"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: Divisor Game (Difficulty: Easy)\nTags: Math, Dynamic Programming, Brainteaser, Game Theory\n\nAlice and Bob take turns playing a game, with Alice starting first.\nInitially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of:\nAlso, if a player cannot make a move, they lose the game.\nReturn true if and only if Alice wins the game, assuming both players play optimally.\n\nExample 1:\nInput: n = 2\nOutput: true\nExplanation: Alice chooses 1, and Bob has no more moves.\n\nExample 2:\nInput: n = 3\nOutput: false\nExplanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.\n\nConstraints:\n- 1 <= n <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\n# math\nclass Solution(object):\n def divisorGame(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n # 1. if we get an even, we can choose x = 1\n # to make the opponent always get an odd\n # 2. if the opponent gets an odd, he can only choose x = 1 or other odds\n # and we can still get an even\n # 3. at the end, the opponent can only choose x = 1 and we win\n # 4. in summary, we win if only if we get an even and \n # keeps even until the opponent loses\n return n % 2 == 0\n\n\n# Time: O(nlogn)\n# Space: O(nlogn)\n# dp, number theory\nclass Solution2(object):\n def divisorGame(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n def factors(n):\n result = [[] for _ in range(n+1)]\n for i in range(1, n+1):\n for j in range(i, n+1, i):\n result[j].append(i)\n return result\n\n FACTORS = factors(n)\n dp = [False]*(n+1)\n for i in range(2, n+1):\n dp[i] = any(not dp[i-j] for j in FACTORS[i] if j != i)\n return dp[-1]\n\n\n# Time: O(nlogn)\n# Space: O(nlogn)\n# memoization, number theory\nclass Solution3(object):\n def divisorGame(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n def factors(n):\n result = [[] for _ in range(n+1)]\n for i in range(1, n+1):\n for j in range(i, n+1, i):\n result[j].append(i)\n return result\n \n def memoization(n):\n if lookup[n] is None:\n lookup[n] = any(not memoization(n-i) for i in FACTORS[n] if i != n)\n return lookup[n]\n\n FACTORS = factors(n)\n lookup = [None]*(n+1)\n return memoization(n)\n\n\n# Time: O(n^(3/2))\n# Space: O(n)\n# memoization\nclass Solution4(object):\n def divisorGame(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n def factors(n):\n for i in range(1, n+1):\n if i*i > n:\n break\n if n%i:\n continue\n yield i\n if n//i != i:\n yield n//i\n \n def memoization(n):\n if lookup[n] is None:\n lookup[n] = any(not memoization(n-i) for i in factors(n) if i != n)\n return lookup[n]\n\n lookup = [None]*(n+1)\n return memoization(n)\n\n\n# Time: O(n^2)\n# Space: O(n)\n# memoization\nclass Solution5(object):\n def divisorGame(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n def factors(n):\n for i in range(1, n+1):\n if n%i:\n continue\n yield i\n \n def memoization(n):\n if lookup[n] is None:\n lookup[n] = any(not memoization(n-i) for i in factors(n) if i != n)\n return lookup[n]\n\n lookup = [None]*(n+1)\n return memoization(n)\n"}} diff --git a/cp/cp-10501.jsonl b/cp/cp-10501.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0234d7f702b20598c00e6031c84a9dce6821626a --- /dev/null +++ b/cp/cp-10501.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10501", "name": "LeetCode 1026: Maximum Difference Between Node And Ancestor"} +{"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 Difference Between Node and Ancestor (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Tree\n\nGiven the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.\nA node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.\n\nExample 1:\nInput: root = [8,3,10,1,6,null,14,null,null,4,7,13]\nOutput: 7\nExplanation: We have various ancestor-node differences, some of which are given below :\n|8 - 3| = 5\n|3 - 7| = 4\n|8 - 1| = 7\n|10 - 13| = 3\nAmong all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.\n\nExample 2:\nInput: root = [1,null,2,null,0,3]\nOutput: 3\n\nConstraints:\n- The number of nodes in the tree is in the range [2, 5000].\n- 0 <= Node.val <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\n# iterative stack solution\nclass Solution(object):\n def maxAncestorDiff(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n result = 0\n stack = [(root, 0, float(\"inf\"))]\n while stack:\n node, mx, mn = stack.pop()\n if not node:\n continue\n result = max(result, mx-node.val, node.val-mn)\n mx = max(mx, node.val)\n mn = min(mn, node.val)\n stack.append((node.left, mx, mn))\n stack.append((node.right, mx, mn))\n return result\n\n\n# Time: O(n)\n# Space: O(h)\n# recursive solution\nclass Solution2(object):\n def maxAncestorDiff(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def maxAncestorDiffHelper(node, mx, mn): \n if not node:\n return 0\n result = max(mx-node.val, node.val-mn)\n mx = max(mx, node.val)\n mn = min(mn, node.val)\n result = max(result, maxAncestorDiffHelper(node.left, mx, mn))\n result = max(result, maxAncestorDiffHelper(node.right, mx, mn))\n return result\n\n return maxAncestorDiffHelper(root, 0, float(\"inf\"))\n"}} diff --git a/cp/cp-10502.jsonl b/cp/cp-10502.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..274e2549c8c4bfe85ba6200a5c43db49af0fbd0a --- /dev/null +++ b/cp/cp-10502.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10502", "name": "LeetCode 1027: Longest Arithmetic Sequence"} +{"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 Arithmetic Subsequence (Difficulty: Medium)\nTags: Array, Hash Table, Binary Search, Dynamic Programming\n\nGiven an array nums of integers, return the length of the longest arithmetic subsequence in nums.\nNote that:\n\nExample 1:\nInput: nums = [3,6,9,12]\nOutput: 4\nExplanation: The whole array is an arithmetic sequence with steps of length = 3.\n\nExample 2:\nInput: nums = [9,4,7,2,10]\nOutput: 3\nExplanation: The longest arithmetic subsequence is [4,7,10].\n\nExample 3:\nInput: nums = [20,1,15,3,10,5,8]\nOutput: 4\nExplanation: The longest arithmetic subsequence is [20,15,10,5].\n\nConstraints:\n- 2 <= nums.length <= 1000\n- 0 <= nums[i] <= 500"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2)\n\nimport collections\n\nclass Solution(object):\n def longestArithSeqLength(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n dp = collections.defaultdict(int)\n for i in range(len(A)-1):\n for j in range(i+1, len(A)):\n v = A[j]-A[i]\n dp[v, j] = max(dp[v, j], dp[v, i]+1)\n return max(dp.values())+1\n"}} diff --git a/cp/cp-10503.jsonl b/cp/cp-10503.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e9b5ae20f9c0c2786d038e47158d67ce2a446974 --- /dev/null +++ b/cp/cp-10503.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10503", "name": "LeetCode 1028: Recover A Tree From Preorder Traversal"} +{"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: Recover a Tree From Preorder Traversal (Difficulty: Hard)\nTags: String, Tree, Depth-First Search, Binary Tree\n\nWe run a preorder depth-first search (DFS) on the root of a binary tree.\nAt each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.  If the depth of a node is D, the depth of its immediate child is D + 1.  The depth of the root node is 0.\nIf a node has only one child, that child is guaranteed to be the left child.\nGiven the output traversal of this traversal, recover the tree and return its root.\n\nExample 1:\nInput: traversal = \"1-2--3--4-5--6--7\"\nOutput: [1,2,5,3,4,6,7]\n\nExample 2:\nInput: traversal = \"1-2--3---4-5--6---7\"\nOutput: [1,2,5,3,null,6,null,4,null,7]\n\nExample 3:\nInput: traversal = \"1-401--349---90--88\"\nOutput: [1,401,null,349,88,90]\n\nConstraints:\n- The number of nodes in the original tree is in the range [1, 1000].\n- 1 <= Node.val <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\n# iterative stack solution\nclass Solution(object):\n def recoverFromPreorder(self, S):\n \"\"\"\n :type S: str\n :rtype: TreeNode\n \"\"\"\n i = 0\n stack = []\n while i < len(S):\n level = 0\n while i < len(S) and S[i] == '-':\n level += 1\n i += 1\n while len(stack) > level:\n stack.pop()\n val = []\n while i < len(S) and S[i] != '-':\n val.append(S[i])\n i += 1\n node = TreeNode(int(\"\".join(val)))\n if stack:\n if stack[-1].left is None:\n stack[-1].left = node\n else:\n stack[-1].right = node\n stack.append(node)\n return stack[0]\n\n\n# Time: O(n)\n# Space: O(h)\n# recursive solution\nclass Solution2(object):\n def recoverFromPreorder(self, S):\n \"\"\"\n :type S: str\n :rtype: TreeNode\n \"\"\"\n def recoverFromPreorderHelper(S, level, i):\n j = i[0]\n while j < len(S) and S[j] == '-':\n j += 1 \n if level != j - i[0]:\n return None\n i[0] = j\n while j < len(S) and S[j] != '-':\n j += 1\n node = TreeNode(int(S[i[0]:j]))\n i[0] = j\n node.left = recoverFromPreorderHelper(S, level+1, i)\n node.right = recoverFromPreorderHelper(S, level+1, i)\n return node\n\n return recoverFromPreorderHelper(S, 0, [0])\n"}} diff --git a/cp/cp-10504.jsonl b/cp/cp-10504.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4497270432a61eb513a44caf344f4a2d981a8164 --- /dev/null +++ b/cp/cp-10504.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10504", "name": "LeetCode 1029: Two City Scheduling"} +{"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 City Scheduling (Difficulty: Medium)\nTags: Array, Greedy, Sorting\n\nA company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.\nReturn the minimum cost to fly every person to a city such that exactly n people arrive in each city.\n\nExample 1:\nInput: costs = [[10,20],[30,200],[400,50],[30,20]]\nOutput: 110\nExplanation: \nThe first person goes to city A for a cost of 10.\nThe second person goes to city A for a cost of 30.\nThe third person goes to city B for a cost of 50.\nThe fourth person goes to city B for a cost of 20.\n\nThe total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.\n\nExample 2:\nInput: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]\nOutput: 1859\n\nExample 3:\nInput: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]\nOutput: 3086\n\nConstraints:\n- 2 * n == costs.length\n- 2 <= costs.length <= 100\n- costs.length is even.\n- 1 <= aCosti, bCosti <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n) ~ O(n^2), O(n) on average.\n# Space: O(1)\n\nimport random\n\n\n# quick select solution\nclass Solution(object):\n def twoCitySchedCost(self, costs):\n \"\"\"\n :type costs: List[List[int]]\n :rtype: int\n \"\"\"\n def kthElement(nums, k, compare):\n def PartitionAroundPivot(left, right, pivot_idx, nums, compare):\n new_pivot_idx = left\n nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]\n for i in range(left, right):\n if compare(nums[i], nums[right]):\n nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]\n new_pivot_idx += 1\n\n nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]\n return new_pivot_idx\n\n left, right = 0, len(nums) - 1\n while left <= right:\n pivot_idx = random.randint(left, right)\n new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, nums, compare)\n if new_pivot_idx == k:\n return\n elif new_pivot_idx > k:\n right = new_pivot_idx - 1\n else: # new_pivot_idx < k.\n left = new_pivot_idx + 1\n \n kthElement(costs, len(costs)//2, lambda a, b: a[0]-a[1] < b[0]-b[1])\n result = 0\n for i in range(len(costs)):\n result += costs[i][0] if i < len(costs)//2 else costs[i][1]\n return result\n"}} diff --git a/cp/cp-10505.jsonl b/cp/cp-10505.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ca849fd13eb58d4c4fe8f11a1d0d3f0d7d722eb1 --- /dev/null +++ b/cp/cp-10505.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10505", "name": "LeetCode 1030: Matrix Cells In Distance Order"} +{"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: Matrix Cells in Distance Order (Difficulty: Easy)\nTags: Array, Math, Geometry, Sorting, Matrix\n\nYou are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter).\nReturn the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition.\nThe distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|.\n\nExample 1:\nInput: rows = 1, cols = 2, rCenter = 0, cCenter = 0\nOutput: [[0,0],[0,1]]\nExplanation: The distances from (0, 0) to other cells are: [0,1]\n\nExample 2:\nInput: rows = 2, cols = 2, rCenter = 0, cCenter = 1\nOutput: [[0,1],[0,0],[1,1],[1,0]]\nExplanation: The distances from (0, 1) to other cells are: [0,1,1,2]\nThe answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.\n\nExample 3:\nInput: rows = 2, cols = 3, rCenter = 1, cCenter = 2\nOutput: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]\nExplanation: The distances from (1, 2) to other cells are: [0,1,1,2,2,3]\nThere are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].\n\nConstraints:\n- 1 <= rows, cols <= 100\n- 0 <= rCenter < rows\n- 0 <= cCenter < cols"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def allCellsDistOrder(self, R, C, r0, c0):\n \"\"\"\n :type R: int\n :type C: int\n :type r0: int\n :type c0: int\n :rtype: List[List[int]]\n \"\"\"\n def append(R, C, r, c, result):\n if 0 <= r < R and 0 <= c < C:\n result.append([r, c])\n \n result = [[r0, c0]]\n for d in range(1, R+C):\n append(R, C, r0-d, c0, result)\n for x in range(-d+1, d):\n append(R, C, r0+x, c0+abs(x)-d, result)\n append(R, C, r0+x, c0+d-abs(x), result)\n append(R, C, r0+d, c0, result)\n return result\n"}} diff --git a/cp/cp-10506.jsonl b/cp/cp-10506.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3804949955d01316fbc69f76ec7758dda04122ea --- /dev/null +++ b/cp/cp-10506.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10506", "name": "LeetCode 1031: Maximum Sum Of Two Non Overlapping Subarrays"} +{"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 Sum of Two Non-Overlapping Subarrays (Difficulty: Medium)\nTags: Array, Dynamic Programming, Sliding Window\n\nGiven an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen.\nThe array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping.\nA subarray is a contiguous part of an array.\n\nExample 1:\nInput: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2\nOutput: 20\nExplanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.\n\nExample 2:\nInput: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2\nOutput: 29\nExplanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.\n\nExample 3:\nInput: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3\nOutput: 31\nExplanation: One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.\n\nConstraints:\n- 1 <= firstLen, secondLen <= 1000\n- 2 <= firstLen + secondLen <= 1000\n- firstLen + secondLen <= nums.length <= 1000\n- 0 <= nums[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxSumTwoNoOverlap(self, A, L, M):\n \"\"\"\n :type A: List[int]\n :type L: int\n :type M: int\n :rtype: int\n \"\"\"\n for i in range(1, len(A)):\n A[i] += A[i-1]\n result, L_max, M_max = A[L+M-1], A[L-1], A[M-1]\n for i in range(L+M, len(A)):\n L_max = max(L_max, A[i-M] - A[i-L-M])\n M_max = max(M_max, A[i-L] - A[i-L-M])\n result = max(result,\n L_max + A[i] - A[i-M],\n M_max + A[i] - A[i-L])\n return result\n"}} diff --git a/cp/cp-10507.jsonl b/cp/cp-10507.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c6541bd6fc25d8fd67c6b7b3b0815a00d8aad109 --- /dev/null +++ b/cp/cp-10507.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10507", "name": "LeetCode 1032: Stream Of Characters"} +{"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: Stream of Characters (Difficulty: Hard)\nTags: Array, String, Design, Trie, Data Stream\n\nDesign an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words.\nFor example, if words = [\"abc\", \"xyz\"] and the stream added the four characters (one by one) 'a', 'x', 'y', and 'z', your algorithm should detect that the suffix \"xyz\" of the characters \"axyz\" matches \"xyz\" from words.\nImplement the StreamChecker class:\n\nExample 1:\nInput\n[\"StreamChecker\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\"]\n[[[\"cd\", \"f\", \"kl\"]], [\"a\"], [\"b\"], [\"c\"], [\"d\"], [\"e\"], [\"f\"], [\"g\"], [\"h\"], [\"i\"], [\"j\"], [\"k\"], [\"l\"]]\nOutput\n[null, false, false, false, true, false, true, false, false, false, false, false, true]\n\nExplanation\nStreamChecker streamChecker = new StreamChecker([\"cd\", \"f\", \"kl\"]);\nstreamChecker.query(\"a\"); // return False\nstreamChecker.query(\"b\"); // return False\nstreamChecker.query(\"c\"); // return False\nstreamChecker.query(\"d\"); // return True, because 'cd' is in the wordlist\nstreamChecker.query(\"e\"); // return False\nstreamChecker.query(\"f\"); // return True, because 'f' is in the wordlist\nstreamChecker.query(\"g\"); // return False\nstreamChecker.query(\"h\"); // return False\nstreamChecker.query(\"i\"); // return False\nstreamChecker.query(\"j\"); // return False\nstreamChecker.query(\"k\"); // return False\nstreamChecker.query(\"l\"); // return True, because 'kl' is in the wordlist\n\nConstraints:\n- 1 <= words.length <= 2000\n- 1 <= words[i].length <= 200\n- words[i] consists of lowercase English letters.\n- letter is a lowercase English letter.\n- At most 4 * 10^4 calls will be made to query."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(n) , n is the total size of patterns\n# query: O(m + z), m is the total size of query string\n# , z is the number of all matched strings\n# , query time could be further improved to O(m) if we don't return all matched patterns\n# Space: O(t), t is the total size of ac automata trie\n# , space could be further improved by DAT (double-array trie)\n\n# Aho–Corasick automata\n# reference:\n# 1. http://web.stanford.edu/class/archive/cs/cs166/cs166.1166/lectures/02/Small02.pdf\n# 2. http://algo.pw/algo/64/python\n\nimport collections\n\n\nclass AhoNode(object):\n def __init__(self):\n self.children = collections.defaultdict(AhoNode)\n self.indices = []\n self.suffix = None\n self.output = None\n\n\nclass AhoTrie(object):\n\n def step(self, letter):\n while self.__node and letter not in self.__node.children:\n self.__node = self.__node.suffix\n self.__node = self.__node.children[letter] if self.__node else self.__root\n return self.__get_ac_node_outputs(self.__node)\n \n def __init__(self, patterns):\n self.__root = self.__create_ac_trie(patterns)\n self.__node = self.__create_ac_suffix_and_output_links(self.__root)\n \n def __create_ac_trie(self, patterns): # Time: O(n), Space: O(t)\n root = AhoNode()\n for i, pattern in enumerate(patterns):\n node = root\n for c in pattern:\n node = node.children[c]\n node.indices.append(i)\n return root\n\n def __create_ac_suffix_and_output_links(self, root): # Time: O(n), Space: O(t)\n queue = collections.deque()\n for node in root.children.itervalues():\n queue.append(node)\n node.suffix = root\n\n while queue:\n node = queue.popleft()\n for c, child in node.children.iteritems():\n queue.append(child)\n suffix = node.suffix\n while suffix and c not in suffix.children:\n suffix = suffix.suffix\n child.suffix = suffix.children[c] if suffix else root\n child.output = child.suffix if child.suffix.indices else child.suffix.output\n \n return root\n\n def __get_ac_node_outputs(self, node): # Time: O(z), in this question, it could be improved to O(1)\n # if we only return a matched pattern without all matched ones\n result = []\n for i in node.indices:\n result.append(i)\n # return result\n output = node.output\n while output:\n for i in output.indices:\n result.append(i)\n # return result\n output = output.output\n return result\n\n\nclass StreamChecker(object):\n\n def __init__(self, words):\n \"\"\"\n :type words: List[str]\n \"\"\"\n self.__trie = AhoTrie(words)\n\n def query(self, letter): # O(m) times\n \"\"\"\n :type letter: str\n :rtype: bool\n \"\"\"\n return len(self.__trie.step(letter)) > 0\n \n\n# Your StreamChecker object will be instantiated and called as such:\n# obj = StreamChecker(words)\n# param_1 = obj.query(letter)\n"}} diff --git a/cp/cp-10508.jsonl b/cp/cp-10508.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..264d7c7c3f444bacfb14f6f577b910b198c1588c --- /dev/null +++ b/cp/cp-10508.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10508", "name": "LeetCode 1033: Moving Stones Until Consecutive"} +{"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: Moving Stones Until Consecutive (Difficulty: Medium)\nTags: Math, Brainteaser\n\nThere are three stones in different positions on the X-axis. You are given three integers a, b, and c, the positions of the stones.\nIn one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x, y, and z with x < y < z. You pick up the stone at either position x or position z, and move that stone to an integer position k, with x < k < z and k != y.\nThe game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).\nReturn an integer array answer of length 2 where:\n\nExample 1:\nInput: a = 1, b = 2, c = 5\nOutput: [1,2]\nExplanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.\n\nExample 2:\nInput: a = 4, b = 3, c = 2\nOutput: [0,0]\nExplanation: We cannot make any moves.\n\nExample 3:\nInput: a = 3, b = 5, c = 1\nOutput: [1,2]\nExplanation: Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.\n\nConstraints:\n- 1 <= a, b, c <= 100\n- a, b, and c have different values."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def numMovesStones(self, a, b, c):\n \"\"\"\n :type a: int\n :type b: int\n :type c: int\n :rtype: List[int]\n \"\"\"\n s = [a, b, c]\n s.sort()\n if s[0]+1 == s[1] and s[1]+1 == s[2]:\n return [0, 0]\n return [1 if s[0]+2 >= s[1] or s[1]+2 >= s[2] else 2, s[2]-s[0]-2]\n\n\n# Time: O(1)\n# Space: O(1)\nclass Solution2(object):\n def numMovesStones(self, a, b, c):\n \"\"\"\n :type a: int\n :type b: int\n :type c: int\n :rtype: List[int]\n \"\"\"\n stones = [a, b, c]\n stones.sort()\n left, min_moves = 0, float(\"inf\")\n max_moves = (stones[-1]-stones[0]) - (len(stones)-1)\n for right in range(len(stones)):\n while stones[right]-stones[left]+1 > len(stones): # find window size <= len(stones)\n left += 1\n min_moves = min(min_moves, len(stones)-(right-left+1)) # move stones not in this window\n return [min_moves, max_moves]\n"}} diff --git a/cp/cp-10509.jsonl b/cp/cp-10509.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ee70f02c99afb80a98967adeed7d96149f4946c3 --- /dev/null +++ b/cp/cp-10509.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10509", "name": "LeetCode 1034: Coloring A Border"} +{"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: Coloring A Border (Difficulty: Medium)\nTags: Array, Depth-First Search, Breadth-First Search, Matrix\n\nYou are given an m x n integer matrix grid, and three integers row, col, and color. Each value in the grid represents the color of the grid square at that location.\nTwo squares are called adjacent if they are next to each other in any of the 4 directions.\nTwo squares belong to the same connected component if they have the same color and they are adjacent.\nThe border of a connected component is all the squares in the connected component that are either adjacent to (at least) a square not in the component, or on the boundary of the grid (the first or last row or column).\nYou should color the border of the connected component that contains the square grid[row][col] with color.\nReturn the final grid.\n\nExample 1:\nInput: grid = [[1,1],[1,2]], row = 0, col = 0, color = 3\nOutput: [[3,3],[3,2]]\n\nExample 2:\nInput: grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3\nOutput: [[1,3,3],[2,3,3]]\n\nExample 3:\nInput: grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2\nOutput: [[2,2,2],[2,1,2],[2,2,2]]\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 50\n- 1 <= grid[i][j], color <= 1000\n- 0 <= row < m\n- 0 <= col < n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m + n)\n\nimport collections\n\n\nclass Solution(object):\n def colorBorder(self, grid, r0, c0, color):\n \"\"\"\n :type grid: List[List[int]]\n :type r0: int\n :type c0: int\n :type color: int\n :rtype: List[List[int]]\n \"\"\"\n directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n\n lookup, q, borders = set([(r0, c0)]), collections.deque([(r0, c0)]), []\n while q:\n r, c = q.popleft()\n is_border = False\n\n for direction in directions:\n nr, nc = r+direction[0], c+direction[1]\n if not ((0 <= nr < len(grid)) and \\\n (0 <= nc < len(grid[0])) and \\\n grid[nr][nc] == grid[r][c]):\n is_border = True\n continue\n if (nr, nc) in lookup:\n continue\n lookup.add((nr, nc))\n q.append((nr, nc))\n\n if is_border:\n borders.append((r, c))\n\n for r, c in borders:\n grid[r][c] = color\n return grid\n \n"}} diff --git a/cp/cp-10510.jsonl b/cp/cp-10510.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3b83ab4f5076a7316e828b7759eef1b73662714a --- /dev/null +++ b/cp/cp-10510.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10510", "name": "LeetCode 1035: Uncrossed Lines"} +{"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: Uncrossed Lines (Difficulty: Medium)\nTags: Array, Dynamic Programming\n\nYou are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.\nWe may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that:\nNote that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).\nReturn the maximum number of connecting lines we can draw in this way.\n\nExample 1:\nInput: nums1 = [1,4,2], nums2 = [1,2,4]\nOutput: 2\nExplanation: We can draw 2 uncrossed lines as in the diagram.\nWe cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.\n\nExample 2:\nInput: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]\nOutput: 3\n\nExample 3:\nInput: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]\nOutput: 2\n\nConstraints:\n- 1 <= nums1.length, nums2.length <= 500\n- 1 <= nums1[i], nums2[j] <= 2000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(min(m, n))\n\nclass Solution(object):\n def maxUncrossedLines(self, A, B):\n \"\"\"\n :type A: List[int]\n :type B: List[int]\n :rtype: int\n \"\"\"\n if len(A) < len(B):\n return self.maxUncrossedLines(B, A)\n\n dp = [[0 for _ in range(len(B)+1)] for _ in range(2)]\n for i in range(len(A)):\n for j in range(len(B)):\n dp[(i+1)%2][j+1] = max(dp[i%2][j] + int(A[i] == B[j]),\n dp[i%2][j+1],\n dp[(i+1)%2][j])\n return dp[len(A)%2][len(B)]\n"}} diff --git a/cp/cp-10511.jsonl b/cp/cp-10511.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..aaa0d4f388a7c4e6850f138ca6da0c93d6732d5b --- /dev/null +++ b/cp/cp-10511.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10511", "name": "LeetCode 1036: Escape A Large Maze"} +{"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: Escape a Large Maze (Difficulty: Hard)\nTags: Array, Hash Table, Depth-First Search, Breadth-First Search\n\nThere is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y).\nWe start at the source = [sx, sy] square and want to reach the target = [tx, ty] square. There is also an array of blocked squares, where each blocked[i] = [xi, yi] represents a blocked square with coordinates (xi, yi).\nEach move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid.\nReturn true if and only if it is possible to reach the target square from the source square through a sequence of valid moves.\n\nExample 1:\nInput: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]\nOutput: false\nExplanation: The target square is inaccessible starting from the source square because we cannot move.\nWe cannot move north or east because those squares are blocked.\nWe cannot move south or west because we cannot go outside of the grid.\n\nExample 2:\nInput: blocked = [], source = [0,0], target = [999999,999999]\nOutput: true\nExplanation: Because there are no blocked cells, it is possible to reach the target square.\n\nConstraints:\n- 0 <= blocked.length <= 200\n- blocked[i].length == 2\n- 0 <= xi, yi < 10^6\n- source.length == target.length == 2\n- 0 <= sx, sy, tx, ty < 10^6\n- source != target\n- It is guaranteed that source and target are not blocked."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2), n is the number of blocked\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def isEscapePossible(self, blocked, source, target):\n \"\"\"\n :type blocked: List[List[int]]\n :type source: List[int]\n :type target: List[int]\n :rtype: bool\n \"\"\"\n R, C = 10**6, 10**6\n directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n\n def bfs(blocks, source, target):\n max_area_surrounded_by_blocks = len(blocks)*(len(blocks)-1)//2\n lookup = set([source])\n if len(lookup) > max_area_surrounded_by_blocks:\n return True\n q = collections.deque([source])\n while q:\n source = q.popleft()\n if source == target:\n return True\n for direction in directions:\n nr, nc = source[0]+direction[0], source[1]+direction[1]\n if not ((0 <= nr < R) and\n (0 <= nc < C) and \n (nr, nc) not in lookup and\n (nr, nc) not in blocks):\n continue\n lookup.add((nr, nc))\n if len(lookup) > max_area_surrounded_by_blocks:\n return True\n q.append((nr, nc))\n return False\n \n return bfs(set(map(tuple, blocked)), tuple(source), tuple(target)) and \\\n bfs(set(map(tuple, blocked)), tuple(target), tuple(source))\n"}} diff --git a/cp/cp-10512.jsonl b/cp/cp-10512.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..289ca8b713c9e73ea24f0d828ba507732a8f6b65 --- /dev/null +++ b/cp/cp-10512.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10512", "name": "LeetCode 1037: Valid Boomerang"} +{"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 Boomerang (Difficulty: Easy)\nTags: Array, Math, Geometry\n\nGiven an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang.\nA boomerang is a set of three points that are all distinct and not in a straight line.\n\nExample 1:\nInput: points = [[1,1],[2,3],[3,2]]\nOutput: true\n\nExample 2:\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: false\n\nConstraints:\n- points.length == 3\n- points[i].length == 2\n- 0 <= xi, yi <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def isBoomerang(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: bool\n \"\"\"\n return (points[0][0] - points[1][0]) * (points[0][1] - points[2][1]) - \\\n (points[0][0] - points[2][0]) * (points[0][1] - points[1][1]) != 0\n"}} diff --git a/cp/cp-10513.jsonl b/cp/cp-10513.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..62686d0dbb35e5b8f361d92289185ef9bc527759 --- /dev/null +++ b/cp/cp-10513.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10513", "name": "LeetCode 1038: Binary Search Tree To Greater Sum 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: Binary Search Tree to Greater Sum Tree (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Search Tree, Binary Tree\n\nGiven the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.\nAs a reminder, a binary search tree is a tree that satisfies these constraints:\nNote: This question is the same as 538: https://leetcode.com/problems/convert-bst-to-greater-tree/\n\nExample 1:\nInput: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\nOutput: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\n\nExample 2:\nInput: root = [0,null,1]\nOutput: [1,null,1]\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 100].\n- 0 <= Node.val <= 100\n- All the values in the tree are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 bstToGst(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n def bstToGstHelper(root, prev):\n if not root:\n return root\n bstToGstHelper(root.right, prev)\n root.val += prev[0]\n prev[0] = root.val\n bstToGstHelper(root.left, prev)\n return root\n \n prev = [0]\n return bstToGstHelper(root, prev)\n"}} diff --git a/cp/cp-10514.jsonl b/cp/cp-10514.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..373cf7423d909b33e929a50d2e87fdca82e22c0b --- /dev/null +++ b/cp/cp-10514.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10514", "name": "LeetCode 1039: Minimum Score Triangulation Of Polygon"} +{"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: Minimum Score Triangulation of Polygon (Difficulty: Medium)\nTags: Array, Dynamic Programming\n\nYou have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex in clockwise order.\nPolygon triangulation is a process where you divide a polygon into a set of triangles and the vertices of each triangle must also be vertices of the original polygon. Note that no other shapes other than triangles are allowed in the division. This process will result in n - 2 triangles.\nYou will triangulate the polygon. For each triangle, the weight of that triangle is the product of the values at its vertices. The total score of the triangulation is the sum of these weights over all n - 2 triangles.\nReturn the minimum possible score that you can achieve with some triangulation of the polygon.\n\nExample 1:\nInput: values = [1,2,3]\nOutput: 6\nExplanation: The polygon is already triangulated, and the score of the only triangle is 6.\n\nExample 2:\nInput: values = [3,7,4,5]\nOutput: 144\nExplanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144. The minimum score is 144.\n\nExample 3:\nInput: values = [1,3,1,4,1,5]\nOutput: 13\nExplanation: The minimum score triangulation is 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.\n\nConstraints:\n- n == values.length\n- 3 <= n <= 50\n- 1 <= values[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(n^2)\n\nclass Solution(object):\n def minScoreTriangulation(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n dp = [[0 for _ in range(len(A))] for _ in range(len(A))]\n for p in range(3, len(A)+1):\n for i in range(len(A)-p+1):\n j = i+p-1\n dp[i][j] = float(\"inf\")\n for k in range(i+1, j):\n dp[i][j] = min(dp[i][j], dp[i][k]+dp[k][j] + A[i]*A[j]*A[k])\n return dp[0][-1]\n"}} diff --git a/cp/cp-10515.jsonl b/cp/cp-10515.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9cab755a127e9cc2e1477ac053def6c08ddcf01c --- /dev/null +++ b/cp/cp-10515.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10515", "name": "LeetCode 1040: Moving Stones Until Consecutive 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: Moving Stones Until Consecutive II (Difficulty: Medium)\nTags: Array, Math, Sliding Window, Sorting\n\nThere are some stones in different positions on the X-axis. You are given an integer array stones, the positions of the stones.\nCall a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone.\nThe game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).\nReturn an integer array answer of length 2 where:\n\nExample 1:\nInput: stones = [7,4,9]\nOutput: [1,2]\nExplanation: We can move 4 -> 8 for one move to finish the game.\nOr, we can move 9 -> 5, 4 -> 6 for two moves to finish the game.\n\nExample 2:\nInput: stones = [6,5,4,3,10]\nOutput: [2,3]\nExplanation: We can move 3 -> 8 then 10 -> 7 to finish the game.\nOr, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game.\nNotice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.\n\nConstraints:\n- 3 <= stones.length <= 10^4\n- 1 <= stones[i] <= 10^9\n- All the values of stones are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def numMovesStonesII(self, stones):\n \"\"\"\n :type stones: List[int]\n :rtype: List[int]\n \"\"\"\n stones.sort()\n left, min_moves = 0, float(\"inf\")\n max_moves = max(stones[-1]-stones[1], stones[-2]-stones[0]) - (len(stones)-2)\n for right in range(len(stones)):\n while stones[right]-stones[left]+1 > len(stones): # find window size <= len(stones)\n left += 1\n if len(stones)-(right-left+1) == 1 and stones[right]-stones[left]+1 == len(stones)-1:\n min_moves = min(min_moves, 2) # case (1, 2, 3, 4), 7\n else:\n min_moves = min(min_moves, len(stones)-(right-left+1)) # move stones not in this window\n return [min_moves, max_moves]\n"}} diff --git a/cp/cp-10516.jsonl b/cp/cp-10516.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a2899b7af02e7aa0059a4c8ba1b44ccc6d3 --- /dev/null +++ b/cp/cp-10516.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10516", "name": "LeetCode 1041: Robot Bounded In Circle"} +{"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 Bounded In Circle (Difficulty: Medium)\nTags: Math, String, Simulation\n\nOn an infinite plane, a robot initially stands at (0, 0) and faces north. Note that:\nThe robot can receive one of three instructions:\nThe robot performs the instructions given in order, and repeats them forever.\nReturn true if and only if there exists a circle in the plane such that the robot never leaves the circle.\n\nExample 1:\nInput: instructions = \"GGLLGG\"\nOutput: true\nExplanation: The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South.\n\"G\": move one step. Position: (0, 1). Direction: South.\n\"G\": move one step. Position: (0, 0). Direction: South.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0).\nBased on that, we return true.\n\nExample 2:\nInput: instructions = \"GG\"\nOutput: false\nExplanation: The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\nRepeating the instructions, keeps advancing in the north direction and does not go into cycles.\nBased on that, we return false.\n\nExample 3:\nInput: instructions = \"GL\"\nOutput: true\nExplanation: The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West.\n\"G\": move one step. Position: (-1, 1). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South.\n\"G\": move one step. Position: (-1, 0). Direction: South.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East.\n\"G\": move one step. Position: (0, 0). Direction: East.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0).\nBased on that, we return true.\n\nConstraints:\n- 1 <= instructions.length <= 100\n- instructions[i] is 'G', 'L' or, 'R'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def isRobotBounded(self, instructions):\n \"\"\"\n :type instructions: str\n :rtype: bool\n \"\"\"\n directions = [[ 1, 0], [0, -1], [-1, 0], [0, 1]]\n x, y, i = 0, 0, 0\n for instruction in instructions:\n if instruction == 'R':\n i = (i+1) % 4\n elif instruction == 'L':\n i = (i-1) % 4\n else:\n x += directions[i][0]\n y += directions[i][1]\n return (x == 0 and y == 0) or i > 0\n"}} diff --git a/cp/cp-10517.jsonl b/cp/cp-10517.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..714ab3ac57c315cf91c2478231cf76ef5f90df2d --- /dev/null +++ b/cp/cp-10517.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10517", "name": "LeetCode 1042: Flower Planting With No Adjacent"} +{"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: Flower Planting With No Adjacent (Difficulty: Medium)\nTags: Depth-First Search, Breadth-First Search, Graph\n\nYou have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers.\nAll gardens have at most 3 paths coming into or leaving it.\nYour task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.\nReturn any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists.\n\nExample 1:\nInput: n = 3, paths = [[1,2],[2,3],[3,1]]\nOutput: [1,2,3]\nExplanation:\nGardens 1 and 2 have different types.\nGardens 2 and 3 have different types.\nGardens 3 and 1 have different types.\nHence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].\n\nExample 2:\nInput: n = 4, paths = [[1,2],[3,4]]\nOutput: [1,2,1,2]\n\nExample 3:\nInput: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]\nOutput: [1,2,3,4]\n\nConstraints:\n- 1 <= n <= 10^4\n- 0 <= paths.length <= 2 * 10^4\n- paths[i].length == 2\n- 1 <= xi, yi <= n\n- xi != yi\n- Every garden has at most 3 paths coming into or leaving it."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def gardenNoAdj(self, N, paths):\n \"\"\"\n :type N: int\n :type paths: List[List[int]]\n :rtype: List[int]\n \"\"\"\n result = [0]*N\n G = [[] for i in range(N)]\n for x, y in paths:\n G[x-1].append(y-1)\n G[y-1].append(x-1)\n for i in range(N):\n result[i] = ({1, 2, 3, 4} - {result[j] for j in G[i]}).pop()\n return result\n"}} diff --git a/cp/cp-10518.jsonl b/cp/cp-10518.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..13bbf3fdef5da59a7db0982c1e98fd1babd4e0b1 --- /dev/null +++ b/cp/cp-10518.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10518", "name": "LeetCode 1043: Partition Array For Maximum Sum"} +{"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: Partition Array for Maximum Sum (Difficulty: Medium)\nTags: Array, Dynamic Programming\n\nGiven an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.\nReturn the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.\n\nExample 1:\nInput: arr = [1,15,7,9,2,5,10], k = 3\nOutput: 84\nExplanation: arr becomes [15,15,15,9,10,10,10]\n\nExample 2:\nInput: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4\nOutput: 83\n\nExample 3:\nInput: arr = [1], k = 1\nOutput: 1\n\nConstraints:\n- 1 <= arr.length <= 500\n- 0 <= arr[i] <= 10^9\n- 1 <= k <= arr.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * k)\n# Space: O(k)\n\nclass Solution(object):\n def maxSumAfterPartitioning(self, A, K):\n \"\"\"\n :type A: List[int]\n :type K: int\n :rtype: int\n \"\"\"\n W = K+1\n dp = [0]*W\n for i in range(len(A)):\n curr_max = 0\n # dp[i % W] = 0; # no need in this problem\n for k in range(1, min(K, i+1) + 1):\n curr_max = max(curr_max, A[i-k+1])\n dp[i % W] = max(dp[i % W], (dp[(i-k) % W] if i >= k else 0) + curr_max*k)\n return dp[(len(A)-1) % W]\n"}} diff --git a/cp/cp-10519.jsonl b/cp/cp-10519.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3e66c80717e20794d677692f0315064fe03793b2 --- /dev/null +++ b/cp/cp-10519.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10519", "name": "LeetCode 1044: Longest Duplicate Substring"} +{"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 Duplicate Substring (Difficulty: Hard)\nTags: String, Binary Search, Sliding Window, Rolling Hash, Suffix Array, Hash Function\n\nGiven a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.\nReturn any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is \"\".\n\nExample 1:\nInput: s = \"banana\"\nOutput: \"ana\"\n\nExample 2:\nInput: s = \"abcd\"\nOutput: \"\"\n\nConstraints:\n- 2 <= s.length <= 3 * 10^4\n- s consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\n# 1. other solution is to apply kasai's algorithm, refer to the link below:\n# - https://leetcode.com/problems/longest-duplicate-substring/discuss/290852/Suffix-array-clear-solution\n# 2. the best solution is to apply ukkonen's algorithm, refer to the link below:\n# - https://leetcode.com/problems/longest-duplicate-substring/discuss/312999/best-java-on-complexity-and-on-space-solution-suffix-tree-67ms\n\nimport collections\n\n\nclass Solution(object):\n def longestDupSubstring(self, S):\n \"\"\"\n :type S: str\n :rtype: str\n \"\"\"\n M = 10**9+7\n D = 26\n\n def check(S, L):\n p = pow(D, L, M)\n curr = reduce(lambda x, y: (D*x+ord(y)-ord('a')) % M, S[:L], 0)\n lookup = collections.defaultdict(list)\n lookup[curr].append(L-1)\n for i in range(L, len(S)):\n curr = ((D*curr) % M + ord(S[i])-ord('a') -\n ((ord(S[i-L])-ord('a'))*p) % M) % M\n if curr in lookup:\n for j in lookup[curr]: # check if string is the same when hash is the same\n if S[j-L+1:j+1] == S[i-L+1:i+1]:\n return i-L+1\n lookup[curr].append(i)\n return 0\n\n left, right = 1, len(S)-1\n while left <= right:\n mid = left + (right-left)//2\n if not check(S, mid):\n right = mid-1\n else:\n left = mid+1\n result = check(S, right)\n return S[result:result + right]\n"}} diff --git a/cp/cp-10520.jsonl b/cp/cp-10520.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5e9dd4d4784c4f7d33af4ae19102243f3f371a1c --- /dev/null +++ b/cp/cp-10520.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10520", "name": "LeetCode 1046: Last Stone Weight"} +{"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: Last Stone Weight (Difficulty: Easy)\nTags: Array, Heap (Priority Queue)\n\nYou are given an array of integers stones where stones[i] is the weight of the ith stone.\nWe are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:\nAt the end of the game, there is at most one stone left.\nReturn the weight of the last remaining stone. If there are no stones left, return 0.\n\nExample 1:\nInput: stones = [2,7,4,1,8,1]\nOutput: 1\nExplanation: \nWe combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,\nwe combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,\nwe combine 2 and 1 to get 1 so the array converts to [1,1,1] then,\nwe combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.\n\nExample 2:\nInput: stones = [1]\nOutput: 1\n\nConstraints:\n- 1 <= stones.length <= 30\n- 1 <= stones[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport heapq\n\n\nclass Solution(object):\n def lastStoneWeight(self, stones):\n \"\"\"\n :type stones: List[int]\n :rtype: int\n \"\"\"\n max_heap = [-x for x in stones]\n heapq.heapify(max_heap)\n for i in range(len(stones)-1):\n x, y = -heapq.heappop(max_heap), -heapq.heappop(max_heap)\n heapq.heappush(max_heap, -abs(x-y))\n return -max_heap[0]\n"}} diff --git a/cp/cp-10521.jsonl b/cp/cp-10521.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..75ce765d42c4421caf14e32715cfb1c057f2928f --- /dev/null +++ b/cp/cp-10521.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10521", "name": "LeetCode 1047: Remove All Adjacent Duplicates In 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: Remove All Adjacent Duplicates In String (Difficulty: Easy)\nTags: String, Stack\n\nYou are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.\nWe repeatedly make duplicate removals on s until we no longer can.\nReturn the final string after all such duplicate removals have been made. It can be proven that the answer is unique.\n\nExample 1:\nInput: s = \"abbaca\"\nOutput: \"ca\"\nExplanation: \nFor example, in \"abbaca\" we could remove \"bb\" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is \"aaca\", of which only \"aa\" is possible, so the final string is \"ca\".\n\nExample 2:\nInput: s = \"azxxzy\"\nOutput: \"ay\"\n\nConstraints:\n- 1 <= s.length <= 10^5\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 removeDuplicates(self, S):\n \"\"\"\n :type S: str\n :rtype: str\n \"\"\"\n result = []\n for c in S:\n if result and result[-1] == c:\n result.pop()\n else:\n result.append(c)\n return \"\".join(result)\n"}} diff --git a/cp/cp-10522.jsonl b/cp/cp-10522.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9b2473cfe09d1017ba2a6144b9ebe8ba6aca38df --- /dev/null +++ b/cp/cp-10522.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10522", "name": "LeetCode 1048: Longest String 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: Longest String Chain (Difficulty: Medium)\nTags: Array, Hash Table, Two Pointers, String, Dynamic Programming, Sorting\n\nYou are given an array of words where each word consists of lowercase English letters.\nwordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.\nA word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.\nReturn the length of the longest possible word chain with words chosen from the given list of words.\n\nExample 1:\nInput: words = [\"a\",\"b\",\"ba\",\"bca\",\"bda\",\"bdca\"]\nOutput: 4\nExplanation: One of the longest word chains is [\"a\",\"ba\",\"bda\",\"bdca\"].\n\nExample 2:\nInput: words = [\"xbc\",\"pcxbcf\",\"xb\",\"cxbc\",\"pcxbc\"]\nOutput: 5\nExplanation: All the words can be put in a word chain [\"xb\", \"xbc\", \"cxbc\", \"pcxbc\", \"pcxbcf\"].\n\nExample 3:\nInput: words = [\"abcd\",\"dbqca\"]\nOutput: 1\nExplanation: The trivial word chain [\"abcd\"] is one of the longest word chains.\n[\"abcd\",\"dbqca\"] is not a valid word chain because the ordering of the letters is changed.\n\nConstraints:\n- 1 <= words.length <= 1000\n- 1 <= words[i].length <= 16\n- words[i] only consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * l^2)\n# Space: O(n * l)\n\nimport collections\n\n\nclass Solution(object):\n def longestStrChain(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: int\n \"\"\"\n words.sort(key=len)\n dp = collections.defaultdict(int)\n for w in words:\n for i in range(len(w)):\n dp[w] = max(dp[w], dp[w[:i]+w[i+1:]]+1)\n return max(dp.itervalues())\n"}} diff --git a/cp/cp-10523.jsonl b/cp/cp-10523.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..44fe143e2d238decae59cbb06f355181d6d79a02 --- /dev/null +++ b/cp/cp-10523.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10523", "name": "LeetCode 1049: Last Stone Weight 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: Last Stone Weight II (Difficulty: Medium)\nTags: Array, Dynamic Programming\n\nYou are given an array of integers stones where stones[i] is the weight of the ith stone.\nWe are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:\nAt the end of the game, there is at most one stone left.\nReturn the smallest possible weight of the left stone. If there are no stones left, return 0.\n\nExample 1:\nInput: stones = [2,7,4,1,8,1]\nOutput: 1\nExplanation:\nWe can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then,\nwe can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then,\nwe can combine 2 and 1 to get 1, so the array converts to [1,1,1] then,\nwe can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value.\n\nExample 2:\nInput: stones = [31,26,33,21,40]\nOutput: 5\n\nConstraints:\n- 1 <= stones.length <= 30\n- 1 <= stones[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(2^n)\n# Space: O(2^n)\n\nclass Solution(object):\n def lastStoneWeightII(self, stones):\n \"\"\"\n :type stones: List[int]\n :rtype: int\n \"\"\"\n dp = {0}\n for stone in stones:\n dp |= {stone+i for i in dp}\n S = sum(stones)\n return min(abs(i-(S-i)) for i in dp)\n"}} diff --git a/cp/cp-10525.jsonl b/cp/cp-10525.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..37640238564151a0c9d8c3999730a2a0d2a458e8 --- /dev/null +++ b/cp/cp-10525.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10525", "name": "LeetCode 1052: Grumpy Bookstore Owner"} +{"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: Grumpy Bookstore Owner (Difficulty: Medium)\nTags: Array, Sliding Window\n\nThere is a bookstore owner that has a store open for n minutes. You are given an integer array customers of length n where customers[i] is the number of the customers that enter the store at the start of the ith minute and all those customers leave after the end of that minute.\nDuring certain minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise.\nWhen the bookstore owner is grumpy, the customers entering during that minute are not satisfied. Otherwise, they are satisfied.\nThe bookstore owner knows a secret technique to remain not grumpy for minutes consecutive minutes, but this technique can only be used once.\nReturn the maximum number of customers that can be satisfied throughout the day.\n\nExample 1:\nInput: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3\nOutput: 16\nExplanation:\nThe bookstore owner keeps themselves not grumpy for the last 3 minutes.\nThe maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.\n\nExample 2:\nInput: customers = [1], grumpy = [0], minutes = 1\nOutput: 1\n\nConstraints:\n- n == customers.length == grumpy.length\n- 1 <= minutes <= n <= 2 * 10^4\n- 0 <= customers[i] <= 1000\n- grumpy[i] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxSatisfied(self, customers, grumpy, X):\n \"\"\"\n :type customers: List[int]\n :type grumpy: List[int]\n :type X: int\n :rtype: int\n \"\"\"\n result, max_extra, extra = 0, 0, 0\n for i in range(len(customers)):\n result += 0 if grumpy[i] else customers[i]\n extra += customers[i] if grumpy[i] else 0\n if i >= X:\n extra -= customers[i-X] if grumpy[i-X] else 0\n max_extra = max(max_extra, extra)\n return result + max_extra\n"}} diff --git a/cp/cp-10526.jsonl b/cp/cp-10526.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c4871df8151555f57c811a2070b08de2e29400cc --- /dev/null +++ b/cp/cp-10526.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10526", "name": "LeetCode 1053: Previous Permutation With One 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: Previous Permutation With One Swap (Difficulty: Medium)\nTags: Array, Greedy\n\nGiven an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap. If it cannot be done, then return the same array.\nNote that a swap exchanges the positions of two numbers arr[i] and arr[j]\n\nExample 1:\nInput: arr = [3,2,1]\nOutput: [3,1,2]\nExplanation: Swapping 2 and 1.\n\nExample 2:\nInput: arr = [1,1,5]\nOutput: [1,1,5]\nExplanation: This is already the smallest permutation.\n\nExample 3:\nInput: arr = [1,9,4,6,7]\nOutput: [1,7,4,6,9]\nExplanation: Swapping 9 and 7.\n\nConstraints:\n- 1 <= arr.length <= 10^4\n- 1 <= arr[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def prevPermOpt1(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: List[int]\n \"\"\"\n for left in reversed(range(len(A)-1)):\n if A[left] > A[left+1]:\n break\n else:\n return A\n right = len(A)-1\n while A[left] <= A[right]:\n right -= 1\n while A[right-1] == A[right]:\n right -= 1\n A[left], A[right] = A[right], A[left]\n return A\n"}} diff --git a/cp/cp-10527.jsonl b/cp/cp-10527.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cfb70cb96b6b5a1805931019ef3323944c4ab983 --- /dev/null +++ b/cp/cp-10527.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10527", "name": "LeetCode 1054: Distant Barcodes"} +{"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: Distant Barcodes (Difficulty: Medium)\nTags: Array, Hash Table, Greedy, Sorting, Heap (Priority Queue), Counting\n\nIn a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i].\nRearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.\n\nExample 1:\nInput: barcodes = [1,1,1,2,2,2]\nOutput: [2,1,2,1,2,1]\n\nExample 2:\nInput: barcodes = [1,1,1,1,2,2,3,3]\nOutput: [1,3,1,3,1,2,1,2]\n\nConstraints:\n- 1 <= barcodes.length <= 10000\n- 1 <= barcodes[i] <= 10000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n), k is the number of distinct barcodes\n# Space: O(k)\n\nimport collections\nimport itertools\n\n\nclass Solution(object):\n def rearrangeBarcodes(self, barcodes):\n \"\"\"\n :type barcodes: List[int]\n :rtype: List[int]\n \"\"\"\n k = 2\n cnts = collections.Counter(barcodes)\n bucket_cnt = max(cnts.itervalues())\n result = [0]*len(barcodes)\n i = (len(barcodes)-1)%k\n for c in itertools.chain((c for c, v in cnts.iteritems() if v == bucket_cnt), (c for c, v in cnts.iteritems() if v != bucket_cnt)):\n for _ in range(cnts[c]):\n result[i] = c\n i += k\n if i >= len(result):\n i = (i-1)%k\n return result\n\n \n# Time: O(n + klogk), k is the number of distinct barcodes\n# Space: O(k)\nimport collections\n\n\nclass Solution2(object):\n def rearrangeBarcodes(self, barcodes):\n \"\"\"\n :type barcodes: List[int]\n :rtype: List[int]\n \"\"\"\n cnts = collections.Counter(barcodes)\n sorted_cnts = [[v, k] for k, v in cnts.iteritems()]\n sorted_cnts.sort(reverse=True)\n\n i = 0\n for v, k in sorted_cnts:\n for _ in range(v):\n barcodes[i] = k\n i += 2\n if i >= len(barcodes):\n i = 1\n return barcodes\n"}} diff --git a/cp/cp-10534.jsonl b/cp/cp-10534.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a61c53970359259de79a68bfa90c8e656062c003 --- /dev/null +++ b/cp/cp-10534.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10534", "name": "LeetCode 1061: Lexicographically Smallest Equivalent 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: Lexicographically Smallest Equivalent String (Difficulty: Medium)\nTags: String, Union Find\n\nYou are given two strings of the same length s1 and s2 and a string baseStr.\nWe say s1[i] and s2[i] are equivalent characters.\nEquivalent characters follow the usual rules of any equivalence relation:\nFor example, given the equivalency information from s1 = \"abc\" and s2 = \"cde\", \"acd\" and \"aab\" are equivalent strings of baseStr = \"eed\", and \"aab\" is the lexicographically smallest equivalent string of baseStr.\nReturn the lexicographically smallest equivalent string of baseStr by using the equivalency information from s1 and s2.\n\nExample 1:\nInput: s1 = \"parker\", s2 = \"morris\", baseStr = \"parser\"\nOutput: \"makkek\"\nExplanation: Based on the equivalency information in s1 and s2, we can group their characters as [m,p], [a,o], [k,r,s], [e,i].\nThe characters in each group are equivalent and sorted in lexicographical order.\nSo the answer is \"makkek\".\n\nExample 2:\nInput: s1 = \"hello\", s2 = \"world\", baseStr = \"hold\"\nOutput: \"hdld\"\nExplanation: Based on the equivalency information in s1 and s2, we can group their characters as [h,w], [d,e,o], [l,r].\nSo only the second letter 'o' in baseStr is changed to 'd', the answer is \"hdld\".\n\nExample 3:\nInput: s1 = \"leetcode\", s2 = \"programs\", baseStr = \"sourcecode\"\nOutput: \"aauaaaaada\"\nExplanation: We group the equivalent characters in s1 and s2 as [a,o,e,r,s,c], [l,p], [g,t] and [d,m], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is \"aauaaaaada\".\n\nConstraints:\n- 1 <= s1.length, s2.length, baseStr <= 1000\n- s1.length == s2.length\n- s1, s2, and baseStr consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlog*n) ~= O(n), n is the length of S\n# Space: O(n)\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[max(x_root, y_root)] = min(x_root, y_root)\n return True\n \n\nclass Solution(object):\n def smallestEquivalentString(self, A, B, S):\n \"\"\"\n :type A: str\n :type B: str\n :type S: str\n :rtype: str\n \"\"\"\n union_find = UnionFind(26)\n for i in range(len(A)):\n union_find.union_set(ord(A[i])-ord('a'), ord(B[i])-ord('a'))\n result = []\n for i in range(len(S)):\n parent = union_find.find_set(ord(S[i])-ord('a'))\n result.append(chr(parent+ord('a')))\n return \"\".join(result)\n"}} diff --git a/cp/cp-10541.jsonl b/cp/cp-10541.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1c05c0b75346c19bff3123f3933faa1dfef0308a --- /dev/null +++ b/cp/cp-10541.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10541", "name": "LeetCode 1071: Greatest Common Divisor Of Strings"} +{"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: Greatest Common Divisor of Strings (Difficulty: Easy)\nTags: Math, String\n\nFor two strings s and t, we say \"t divides s\" if and only if s = t + t + t + ... + t + t (i.e., t is concatenated with itself one or more times).\nGiven two strings str1 and str2, return the largest string x such that x divides both str1 and str2.\n\nExample 1:\nInput: str1 = \"ABCABC\", str2 = \"ABC\"\nOutput: \"ABC\"\n\nExample 2:\nInput: str1 = \"ABABAB\", str2 = \"ABAB\"\nOutput: \"AB\"\n\nExample 3:\nInput: str1 = \"LEET\", str2 = \"CODE\"\nOutput: \"\"\n\nConstraints:\n- 1 <= str1.length, str2.length <= 1000\n- str1 and str2 consist of English uppercase letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n)\n# Space: O(1)\n\nclass Solution(object):\n def gcdOfStrings(self, str1, str2):\n \"\"\"\n :type str1: str\n :type str2: str\n :rtype: str\n \"\"\"\n def check(s, common):\n i = 0\n for c in s:\n if c != common[i]:\n return False\n i = (i+1)%len(common)\n return True\n \n def gcd(a, b): # Time: O(log(min(a, b)))\n while b:\n a, b = b, a % b\n return a\n \n if not str1 or not str2:\n return \"\"\n c = gcd(len(str1), len(str2))\n result = str1[:c]\n return result if check(str1, result) and check(str2, result) else \"\"\n"}} diff --git a/cp/cp-10542.jsonl b/cp/cp-10542.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c77912a9d4645fc19702c0f2821dce333f3d0269 --- /dev/null +++ b/cp/cp-10542.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10542", "name": "LeetCode 1072: Flip Columns For Maximum Number Of Equal Rows"} +{"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: Flip Columns For Maximum Number of Equal Rows (Difficulty: Medium)\nTags: Array, Hash Table, Matrix\n\nYou are given an m x n binary matrix matrix.\nYou can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa).\nReturn the maximum number of rows that have all values equal after some number of flips.\n\nExample 1:\nInput: matrix = [[0,1],[1,1]]\nOutput: 1\nExplanation: After flipping no values, 1 row has all values equal.\n\nExample 2:\nInput: matrix = [[0,1],[1,0]]\nOutput: 2\nExplanation: After flipping values in the first column, both rows have equal values.\n\nExample 3:\nInput: matrix = [[0,0,0],[0,0,1],[1,1,0]]\nOutput: 2\nExplanation: After flipping values in the first two columns, the last two rows have equal values.\n\nConstraints:\n- m == matrix.length\n- n == matrix[i].length\n- 1 <= m, n <= 300\n- matrix[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m * n)\n\nimport collections\n\n\nclass Solution(object):\n def maxEqualRowsAfterFlips(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: int\n \"\"\"\n count = collections.Counter(tuple(x^row[0] for x in row)\n for row in matrix)\n return max(count.itervalues())\n"}} diff --git a/cp/cp-10543.jsonl b/cp/cp-10543.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b5966da31dbb777aefc86863080f46429f23d23f --- /dev/null +++ b/cp/cp-10543.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10543", "name": "LeetCode 1073: Adding Two Negabinary 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: Adding Two Negabinary Numbers (Difficulty: Medium)\nTags: Array, Math\n\nGiven two numbers arr1 and arr2 in base -2, return the result of adding them together.\nEach number is given in array format:  as an array of 0s and 1s, from most significant bit to least significant bit.  For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3.  A number arr in array, format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1.\nReturn the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.\n\nExample 1:\nInput: arr1 = [1,1,1,1,1], arr2 = [1,0,1]\nOutput: [1,0,0,0,0]\nExplanation: arr1 represents 11, arr2 represents 5, the output represents 16.\n\nExample 2:\nInput: arr1 = [0], arr2 = [0]\nOutput: [0]\n\nExample 3:\nInput: arr1 = [0], arr2 = [1]\nOutput: [1]\n\nConstraints:\n- 1 <= arr1.length, arr2.length <= 1000\n- arr1[i] and arr2[i] are 0 or 1\n- arr1 and arr2 have no leading zeros"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def addNegabinary(self, arr1, arr2):\n \"\"\"\n :type arr1: List[int]\n :type arr2: List[int]\n :rtype: List[int]\n \"\"\"\n result = []\n carry = 0\n while arr1 or arr2 or carry:\n if arr1:\n carry += arr1.pop()\n if arr2:\n carry += arr2.pop()\n result.append(carry & 1)\n carry = -(carry >> 1)\n while len(result) > 1 and result[-1] == 0:\n result.pop()\n result.reverse()\n return result\n"}} diff --git a/cp/cp-10544.jsonl b/cp/cp-10544.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..65df5c1f7d9044359f0ac3875c86196e110c3a73 --- /dev/null +++ b/cp/cp-10544.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10544", "name": "LeetCode 1074: Number Of Submatrices That Sum To Target"} +{"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 Submatrices That Sum to Target (Difficulty: Hard)\nTags: Array, Hash Table, Matrix, Prefix Sum\n\nGiven a matrix and a target, return the number of non-empty submatrices that sum to target.\nA submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.\nTwo submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.\n\nExample 1:\nInput: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0\nOutput: 4\nExplanation: The four 1x1 submatrices that only contain 0.\n\nExample 2:\nInput: matrix = [[1,-1],[-1,1]], target = 0\nOutput: 5\nExplanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.\n\nExample 3:\nInput: matrix = [[904]], target = 0\nOutput: 0\n\nConstraints:\n- 1 <= matrix.length <= 100\n- 1 <= matrix[0].length <= 100\n- -1000 <= matrix[i][j] <= 1000\n- -10^8 <= target <= 10^8"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m^2*n), m is min(r, c), n is max(r, c)\n# Space: O(n), which doesn't include transposed space\n\nimport collections\n\n\nclass Solution(object):\n def numSubmatrixSumTarget(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: int\n \"\"\"\n if len(matrix) > len(matrix[0]):\n return self.numSubmatrixSumTarget(map(list, zip(*matrix)), target)\n \n for i in range(len(matrix)):\n for j in range(len(matrix[i])-1):\n matrix[i][j+1] += matrix[i][j]\n\n result = 0\n for i in range(len(matrix)):\n prefix_sum = [0]*len(matrix[i])\n for j in range(i, len(matrix)):\n lookup = collections.defaultdict(int)\n lookup[0] = 1\n for k in range(len(matrix[j])):\n prefix_sum[k] += matrix[j][k]\n if prefix_sum[k]-target in lookup:\n result += lookup[prefix_sum[k]-target]\n lookup[prefix_sum[k]] += 1\n return result\n"}} diff --git a/cp/cp-10545.jsonl b/cp/cp-10545.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a453a9cb6d9718df3fdb3c25b9c662fb59fef9e4 --- /dev/null +++ b/cp/cp-10545.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10545", "name": "LeetCode 1078: Occurrences After Bigram"} +{"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: Occurrences After Bigram (Difficulty: Easy)\nTags: String\n\nGiven two strings first and second, consider occurrences in some text of the form \"first second third\", where second comes immediately after first, and third comes immediately after second.\nReturn an array of all the words third for each occurrence of \"first second third\".\n\nExample 1:\nInput: text = \"alice is a good girl she is a good student\", first = \"a\", second = \"good\"\nOutput: [\"girl\",\"student\"]\n\nExample 2:\nInput: text = \"we will we will rock you\", first = \"we\", second = \"will\"\nOutput: [\"we\",\"rock\"]\n\nConstraints:\n- 1 <= text.length <= 1000\n- text consists of lowercase English letters and spaces.\n- All the words in text are separated by a single space.\n- 1 <= first.length, second.length <= 10\n- first and second consist of lowercase English letters.\n- text will not have any leading or trailing spaces."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def findOcurrences(self, text, first, second):\n \"\"\"\n :type text: str\n :type first: str\n :type second: str\n :rtype: List[str]\n \"\"\"\n result = []\n first += ' '\n second += ' '\n third = []\n i, j, k = 0, 0, 0\n while k < len(text):\n c = text[k]\n k += 1\n if i != len(first):\n if c == first[i]:\n i += 1\n else:\n i = 0\n continue\n if j != len(second):\n if c == second[j]:\n j += 1\n else:\n k -= j+1\n i, j = 0, 0\n continue\n if c != ' ':\n third.append(c)\n continue\n k -= len(second) + len(third) + 1\n i, j = 0, 0\n result.append(\"\".join(third))\n third = []\n if third:\n result.append(\"\".join(third))\n return result\n"}} diff --git a/cp/cp-10546.jsonl b/cp/cp-10546.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..780b6e4e2cc3b57bb9a7682dd499b6d0128b084f --- /dev/null +++ b/cp/cp-10546.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10546", "name": "LeetCode 1079: Letter Tile Possibilities"} +{"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: Letter Tile Possibilities (Difficulty: Medium)\nTags: Hash Table, String, Backtracking, Counting\n\nYou have n  tiles, where each tile has one letter tiles[i] printed on it.\nReturn the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.\n\nExample 1:\nInput: tiles = \"AAB\"\nOutput: 8\nExplanation: The possible sequences are \"A\", \"B\", \"AA\", \"AB\", \"BA\", \"AAB\", \"ABA\", \"BAA\".\n\nExample 2:\nInput: tiles = \"AAABBC\"\nOutput: 188\n\nExample 3:\nInput: tiles = \"V\"\nOutput: 1\n\nConstraints:\n- 1 <= tiles.length <= 7\n- tiles consists of uppercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def numTilePossibilities(self, tiles):\n \"\"\"\n :type tiles: str\n :rtype: int\n \"\"\"\n fact = [0.0]*(len(tiles)+1)\n fact[0] = 1.0\n for i in range(1, len(tiles)+1):\n fact[i] = fact[i-1]*i\n count = collections.Counter(tiles)\n\n # 1. we can represent each alphabet 1..26 as generating functions:\n # G1(x) = 1 + x^1/1! + x^2/2! + x^3/3! + ... + x^count1/count1!\n # G2(x) = 1 + x^1/1! + x^2/2! + x^3/3! + ... + x^count2/count2!\n # ...\n # G26(x) = 1 + x^1/1! + x^2/2! + x^3/3! + ... + x^count26/count26!\n #\n # 2. let G1(x)*G2(x)*...*G26(x) = c0 + c1*x1 + ... + ck*x^k, k is the max number s.t. ck != 0\n # => ci (1 <= i <= k) is the number we need to divide when permuting i letters\n # => the answer will be : c1*1! + c2*2! + ... + ck*k!\n \n coeff = [0.0]*(len(tiles)+1)\n coeff[0] = 1.0\n for i in count.itervalues():\n new_coeff = [0.0]*(len(tiles)+1)\n for j in range(len(coeff)):\n for k in range(i+1):\n if k+j >= len(new_coeff):\n break\n new_coeff[j+k] += coeff[j]*1.0/fact[k]\n coeff = new_coeff\n\n result = 0\n for i in range(1, len(coeff)):\n result += int(round(coeff[i]*fact[i]))\n return result\n\n\n# Time: O(r), r is the value of result\n# Space: O(n)\nclass Solution2(object):\n def numTilePossibilities(self, tiles):\n \"\"\"\n :type tiles: str\n :rtype: int\n \"\"\"\n def backtracking(counter):\n total = 0\n for k, v in counter.iteritems():\n if not v:\n continue\n counter[k] -= 1\n total += 1+backtracking(counter)\n counter[k] += 1\n return total\n\n return backtracking(collections.Counter(tiles))\n"}} diff --git a/cp/cp-10547.jsonl b/cp/cp-10547.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ca724a20a03ef635832576196318ccc8506cedad --- /dev/null +++ b/cp/cp-10547.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10547", "name": "LeetCode 1080: Insufficient Nodes In Root To Leaf Paths"} +{"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: Insufficient Nodes in Root to Leaf Paths (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Tree\n\nGiven the root of a binary tree and an integer limit, delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree.\nA node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit.\nA leaf is a node with no children.\n\nExample 1:\nInput: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1\nOutput: [1,2,3,4,null,null,7,8,9,null,14]\n\nExample 2:\nInput: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22\nOutput: [5,4,8,11,null,17,4,7,null,null,null,5]\n\nExample 3:\nInput: root = [1,2,-3,-5,null,4,null], limit = -1\nOutput: [1,null,-3,4]\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 5000].\n- -10^5 <= Node.val <= 10^5\n- -10^9 <= limit <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 sufficientSubset(self, root, limit):\n \"\"\"\n :type root: TreeNode\n :type limit: int\n :rtype: TreeNode\n \"\"\"\n if not root:\n return None\n if not root.left and not root.right:\n return None if root.val < limit else root\n root.left = self.sufficientSubset(root.left, limit-root.val)\n root.right = self.sufficientSubset(root.right, limit-root.val)\n if not root.left and not root.right:\n return None\n return root\n"}} diff --git a/cp/cp-10548.jsonl b/cp/cp-10548.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ae31a4ca95414f733333b0b6f62a9fa369f8604f --- /dev/null +++ b/cp/cp-10548.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10548", "name": "LeetCode 1081: Smallest Subsequence Of Distinct Characters"} +{"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: Smallest Subsequence of Distinct Characters (Difficulty: Medium)\nTags: String, Stack, Greedy, Monotonic Stack\n\nGiven a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.\n\nExample 1:\nInput: s = \"bcabc\"\nOutput: \"abc\"\n\nExample 2:\nInput: s = \"cbacdcbc\"\nOutput: \"acdb\"\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(1)\n\nimport collections\n\n\nclass Solution(object):\n def smallestSubsequence(self, text):\n \"\"\"\n :type text: str\n :rtype: str\n \"\"\"\n count = collections.Counter(text)\n\n lookup, stk = set(), []\n for c in text:\n if c not in lookup:\n while stk and stk[-1] > c and count[stk[-1]]:\n lookup.remove(stk.pop())\n stk += c\n lookup.add(c)\n count[c] -= 1\n return \"\".join(stk)\n"}} diff --git a/cp/cp-10553.jsonl b/cp/cp-10553.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..44d6b8352e609555ee12a5b5a2eb419bfeb6fc03 --- /dev/null +++ b/cp/cp-10553.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10553", "name": "LeetCode 1089: Duplicate Zeros"} +{"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: Duplicate Zeros (Difficulty: Easy)\nTags: Array, Two Pointers\n\nGiven a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.\nNote that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.\n\nExample 1:\nInput: arr = [1,0,2,3,0,4,5,0]\nOutput: [1,0,0,2,3,0,0,4]\nExplanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]\n\nExample 2:\nInput: arr = [1,2,3]\nOutput: [1,2,3]\nExplanation: After calling your function, the input array is modified to: [1,2,3]\n\nConstraints:\n- 1 <= arr.length <= 10^4\n- 0 <= arr[i] <= 9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def duplicateZeros(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: None Do not return anything, modify arr in-place instead.\n \"\"\"\n shift, i = 0, 0\n while i+shift < len(arr):\n shift += int(arr[i] == 0)\n i += 1\n i -= 1\n while shift:\n if i+shift < len(arr):\n arr[i+shift] = arr[i]\n if arr[i] == 0:\n shift -= 1\n arr[i+shift] = arr[i]\n i -= 1\n"}} diff --git a/cp/cp-10554.jsonl b/cp/cp-10554.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e917788c04cef369fdff3662aa567d6561512a21 --- /dev/null +++ b/cp/cp-10554.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10554", "name": "LeetCode 1090: Largest Values From Labels"} +{"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: Largest Values From Labels (Difficulty: Medium)\nTags: Array, Hash Table, Greedy, Sorting, Counting\n\nYou are given n item's value and label as two integer arrays values and labels. You are also given two integers numWanted and useLimit.\nYour task is to find a subset of items with the maximum sum of their values such that:\nReturn the maximum sum.\n\nExample 1:\nInput: values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1\nOutput: 9\nExplanation:\nThe subset chosen is the first, third, and fifth items with the sum of values 5 + 3 + 1.\n\nExample 2:\nInput: values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2\nOutput: 12\nExplanation:\nThe subset chosen is the first, second, and third items with the sum of values 5 + 4 + 3.\n\nExample 3:\nInput: values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1\nOutput: 16\nExplanation:\nThe subset chosen is the first and fourth items with the sum of values 9 + 7.\n\nConstraints:\n- n == values.length == labels.length\n- 1 <= n <= 2 * 10^4\n- 0 <= values[i], labels[i] <= 2 * 10^4\n- 1 <= numWanted, useLimit <= n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def largestValsFromLabels(self, values, labels, num_wanted, use_limit):\n \"\"\"\n :type values: List[int]\n :type labels: List[int]\n :type num_wanted: int\n :type use_limit: int\n :rtype: int\n \"\"\"\n counts = collections.defaultdict(int)\n val_labs = zip(values,labels)\n val_labs.sort(reverse=True)\n result = 0\n for val, lab in val_labs:\n if counts[lab] >= use_limit:\n continue\n result += val\n counts[lab] += 1\n num_wanted -= 1\n if num_wanted == 0:\n break\n return result\n"}} diff --git a/cp/cp-10555.jsonl b/cp/cp-10555.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..548de6be49156cae96d5489e08c11ac74ab9e5b0 --- /dev/null +++ b/cp/cp-10555.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10555", "name": "LeetCode 1091: Shortest Path In Binary Matrix"} +{"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: Shortest Path in Binary Matrix (Difficulty: Medium)\nTags: Array, Breadth-First Search, Matrix\n\nGiven an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.\nA clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:\nThe length of a clear path is the number of visited cells of this path.\n\nExample 1:\nInput: grid = [[0,1],[1,0]]\nOutput: 2\n\nExample 2:\nInput: grid = [[0,0,0],[1,1,0],[1,1,0]]\nOutput: 4\n\nExample 3:\nInput: grid = [[1,0,0],[1,1,0],[1,1,0]]\nOutput: -1\n\nConstraints:\n- n == grid.length\n- n == grid[i].length\n- 1 <= n <= 100\n- grid[i][j] is 0 or 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def shortestPathBinaryMatrix(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(-1, -1), (-1, 0), (-1, 1), \\\n ( 0, -1), ( 0, 1), \\\n ( 1, -1), ( 1, 0), ( 1, 1)]\n result = 0\n q = collections.deque([(0, 0)])\n while q:\n result += 1\n next_depth = collections.deque()\n while q:\n i, j = q.popleft()\n if 0 <= i < len(grid) and \\\n 0 <= j < len(grid[0]) and \\\n not grid[i][j]:\n grid[i][j] = 1\n if i == len(grid)-1 and j == len(grid)-1:\n return result\n for d in directions:\n next_depth.append((i+d[0], j+d[1]))\n q = next_depth\n return -1\n"}} diff --git a/cp/cp-10556.jsonl b/cp/cp-10556.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0e96d7d4744ec26eba7b8a8f20b6b635085b8951 --- /dev/null +++ b/cp/cp-10556.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10556", "name": "LeetCode 1092: Shortest Common Supersequence"} +{"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: Shortest Common Supersequence (Difficulty: Hard)\nTags: String, Dynamic Programming\n\nGiven two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them.\nA string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.\n\nExample 1:\nInput: str1 = \"abac\", str2 = \"cab\"\nOutput: \"cabac\"\nExplanation: \nstr1 = \"abac\" is a subsequence of \"cabac\" because we can delete the first \"c\".\nstr2 = \"cab\" is a subsequence of \"cabac\" because we can delete the last \"ac\".\nThe answer provided is the shortest such string that satisfies these properties.\n\nExample 2:\nInput: str1 = \"aaaaaaaa\", str2 = \"aaaaaaaa\"\nOutput: \"aaaaaaaa\"\n\nConstraints:\n- 1 <= str1.length, str2.length <= 1000\n- str1 and str2 consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m * n)\n\nclass Solution(object):\n def shortestCommonSupersequence(self, str1, str2):\n \"\"\"\n :type str1: str\n :type str2: str\n :rtype: str\n \"\"\"\n dp = [[0 for _ in range(len(str2)+1)] for _ in range(2)]\n bt = [[None for _ in range(len(str2)+1)] for _ in range(len(str1)+1)]\n for i, c in enumerate(str1):\n bt[i+1][0] = (i, 0, c)\n for j, c in enumerate(str2):\n bt[0][j+1] = (0, j, c)\n for i in range(len(str1)):\n for j in range(len(str2)):\n if dp[i % 2][j+1] > dp[(i+1) % 2][j]:\n dp[(i+1) % 2][j+1] = dp[i % 2][j+1]\n bt[i+1][j+1] = (i, j+1, str1[i])\n else:\n dp[(i+1) % 2][j+1] = dp[(i+1) % 2][j]\n bt[i+1][j+1] = (i+1, j, str2[j])\n if str1[i] != str2[j]:\n continue\n if dp[i % 2][j]+1 > dp[(i+1) % 2][j+1]:\n dp[(i+1) % 2][j+1] = dp[i % 2][j]+1\n bt[i+1][j+1] = (i, j, str1[i])\n \n i, j = len(str1), len(str2)\n result = []\n while i != 0 or j != 0:\n i, j, c = bt[i][j]\n result.append(c)\n result.reverse()\n return \"\".join(result)\n"}} diff --git a/cp/cp-10557.jsonl b/cp/cp-10557.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..03c52df795a52e3b50c7f7aaf51daff763043093 --- /dev/null +++ b/cp/cp-10557.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10557", "name": "LeetCode 1093: Statistics From A Large Sample"} +{"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: Statistics from a Large Sample (Difficulty: Medium)\nTags: Array, Math, Probability and Statistics\n\nYou are given a large sample of integers in the range [0, 255]. Since the sample is so large, it is represented by an array count where count[k] is the number of times that k appears in the sample.\nCalculate the following statistics:\nReturn the statistics of the sample as an array of floating-point numbers [minimum, maximum, mean, median, mode]. Answers within 10-5 of the actual answer will be accepted.\n\nExample 1:\nInput: count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: [1.00000,3.00000,2.37500,2.50000,3.00000]\nExplanation: The sample represented by count is [1,2,2,2,3,3,3,3].\nThe minimum and maximum are 1 and 3 respectively.\nThe mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375.\nSince the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5.\nThe mode is 3 as it appears the most in the sample.\n\nExample 2:\nInput: count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: [1.00000,4.00000,2.18182,2.00000,1.00000]\nExplanation: The sample represented by count is [1,1,1,1,2,2,2,3,3,4,4].\nThe minimum and maximum are 1 and 4 respectively.\nThe mean is (1+1+1+1+2+2+2+3+3+4+4) / 11 = 24 / 11 = 2.18181818... (for display purposes, the output shows the rounded number 2.18182).\nSince the size of the sample is odd, the median is the middle element 2.\nThe mode is 1 as it appears the most in the sample.\n\nConstraints:\n- count.length == 256\n- 0 <= count[i] <= 10^9\n- 1 <= sum(count) <= 10^9\n- The mode of the sample that count represents is unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport bisect\n\n\nclass Solution(object):\n def sampleStats(self, count):\n \"\"\"\n :type count: List[int]\n :rtype: List[float]\n \"\"\"\n n = sum(count)\n mi = next(i for i in range(len(count)) if count[i]) * 1.0\n ma = next(i for i in reversed(range(len(count))) if count[i]) * 1.0\n mean = sum(i * v for i, v in enumerate(count)) * 1.0 / n\n mode = count.index(max(count)) * 1.0\n for i in range(1, len(count)):\n count[i] += count[i-1]\n median1 = bisect.bisect_left(count, (n+1) // 2)\n median2 = bisect.bisect_left(count, (n+2) // 2)\n median = (median1+median2) / 2.0\n return [mi, ma, mean, median, mode]\n"}} diff --git a/cp/cp-10558.jsonl b/cp/cp-10558.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..66de86ae303b17c9d9c8eb4121a746ebe3699d28 --- /dev/null +++ b/cp/cp-10558.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10558", "name": "LeetCode 1094: Car Pooling"} +{"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: Car Pooling (Difficulty: Medium)\nTags: Array, Sorting, Heap (Priority Queue), Simulation, Prefix Sum\n\nThere is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).\nYou are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location.\nReturn true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.\n\nExample 1:\nInput: trips = [[2,1,5],[3,3,7]], capacity = 4\nOutput: false\n\nExample 2:\nInput: trips = [[2,1,5],[3,3,7]], capacity = 5\nOutput: true\n\nConstraints:\n- 1 <= trips.length <= 1000\n- trips[i].length == 3\n- 1 <= numPassengersi <= 100\n- 0 <= fromi < toi <= 1000\n- 1 <= capacity <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass Solution(object):\n def carPooling(self, trips, capacity):\n \"\"\"\n :type trips: List[List[int]]\n :type capacity: int\n :rtype: bool\n \"\"\"\n line = [x for num, start, end in trips for x in [[start, num], [end, -num]]]\n line.sort()\n for _, num in line:\n capacity -= num\n if capacity < 0:\n return False\n return True\n"}} diff --git a/cp/cp-10559.jsonl b/cp/cp-10559.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b5ed0e3b212ab35f679a3fa228162e2c983cac97 --- /dev/null +++ b/cp/cp-10559.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10559", "name": "LeetCode 1095: Find In Mountain 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: Find in Mountain Array (Difficulty: Hard)\nTags: Array, Binary Search, Interactive\n\n(This problem is an interactive problem.)\nYou may recall that an array arr is a mountain array if and only if:\nGiven a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1.\nYou cannot access the mountain array directly. You may only access the array using a MountainArray interface:\nSubmissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.\n\nExample 1:\nInput: mountainArr = [1,2,3,4,5,3,1], target = 3\nOutput: 2\nExplanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.\n\nExample 2:\nInput: mountainArr = [0,1,2,4,2,1], target = 3\nOutput: -1\nExplanation: 3 does not exist in the array, so we return -1.\n\nConstraints:\n- 3 <= mountainArr.length() <= 10^4\n- 0 <= target <= 10^9\n- 0 <= mountainArr.get(index) <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\n# \"\"\"\n# This is MountainArray's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\nclass MountainArray(object):\n def get(self, index):\n \"\"\"\n :type index: int\n :rtype int\n \"\"\"\n pass\n\n def length(self):\n \"\"\"\n :rtype int\n \"\"\"\n pass\n\n\nclass Solution(object):\n def findInMountainArray(self, target, mountain_arr):\n \"\"\"\n :type target: integer\n :type mountain_arr: MountainArray\n :rtype: integer\n \"\"\"\n def binarySearch(A, left, right, check):\n while left <= right:\n mid = left + (right-left)//2\n if check(mid):\n right = mid-1\n else:\n left = mid+1\n return left\n \n peak = binarySearch(mountain_arr, 0, mountain_arr.length()-1,\n lambda x: mountain_arr.get(x) >= mountain_arr.get(x+1))\n left = binarySearch(mountain_arr, 0, peak,\n lambda x: mountain_arr.get(x) >= target)\n if left <= peak and mountain_arr.get(left) == target:\n return left\n right = binarySearch(mountain_arr, peak, mountain_arr.length()-1,\n lambda x: mountain_arr.get(x) <= target)\n if right <= mountain_arr.length()-1 and mountain_arr.get(right) == target:\n return right\n return -1\n"}} diff --git a/cp/cp-10560.jsonl b/cp/cp-10560.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..57d6da93249abde1b8b5f9f959b564e234309330 --- /dev/null +++ b/cp/cp-10560.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10560", "name": "LeetCode 1096: Brace Expansion 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: Brace Expansion II (Difficulty: Hard)\nTags: String, Backtracking, Stack, Breadth-First Search\n\nUnder the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents.\nThe grammar can best be understood through simple examples:\nFormally, the three rules for our grammar:\nGiven an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.\n\nExample 1:\nInput: expression = \"{a,b}{c,{d,e}}\"\nOutput: [\"ac\",\"ad\",\"ae\",\"bc\",\"bd\",\"be\"]\n\nExample 2:\nInput: expression = \"{{a,z},a{b,c},{ab,z}}\"\nOutput: [\"a\",\"ab\",\"ac\",\"z\"]\nExplanation: Each distinct word is written only once in the final answer.\n\nConstraints:\n- 1 <= expression.length <= 60\n- expression[i] consists of '{', '}', ','or lowercase English letters.\n- The given expression represents a set of words based on the grammar given in the description."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(p*l * log(p*l)), p is the production of all number of options\n# , l is the length of a word\n# Space: O(p*l)\n\nimport itertools\n\n\nclass Solution(object):\n def braceExpansionII(self, expression):\n \"\"\"\n :type expression: str\n :rtype: List[str]\n \"\"\"\n def form_words(options):\n words = map(\"\".join, itertools.product(*options))\n words.sort()\n return words\n\n def generate_option(expr, i):\n option_set = set()\n while i[0] != len(expr) and expr[i[0]] != \"}\":\n i[0] += 1 # { or ,\n for option in generate_words(expr, i):\n option_set.add(option)\n i[0] += 1 # }\n option = list(option_set)\n option.sort()\n return option\n\n def generate_words(expr, i):\n options = []\n while i[0] != len(expr) and expr[i[0]] not in \",}\":\n tmp = []\n if expr[i[0]] not in \"{,}\":\n tmp.append(expr[i[0]])\n i[0] += 1 # a-z\n elif expr[i[0]] == \"{\":\n tmp = generate_option(expr, i)\n options.append(tmp)\n return form_words(options)\n\n return generate_words(expression, [0])\n\n\nclass Solution2(object):\n def braceExpansionII(self, expression):\n \"\"\"\n :type expression: str\n :rtype: List[str]\n \"\"\"\n def form_words(options):\n words = []\n total = 1\n for opt in options:\n total *= len(opt)\n for i in range(total):\n tmp = []\n for opt in reversed(options):\n i, c = divmod(i, len(opt))\n tmp.append(opt[c])\n tmp.reverse()\n words.append(\"\".join(tmp))\n words.sort()\n return words\n\n def generate_option(expr, i):\n option_set = set()\n while i[0] != len(expr) and expr[i[0]] != \"}\":\n i[0] += 1 # { or ,\n for option in generate_words(expr, i):\n option_set.add(option)\n i[0] += 1 # }\n option = list(option_set)\n option.sort()\n return option\n\n def generate_words(expr, i):\n options = []\n while i[0] != len(expr) and expr[i[0]] not in \",}\":\n tmp = []\n if expr[i[0]] not in \"{,}\":\n tmp.append(expr[i[0]])\n i[0] += 1 # a-z\n elif expr[i[0]] == \"{\":\n tmp = generate_option(expr, i)\n options.append(tmp)\n return form_words(options)\n\n return generate_words(expression, [0])\n"}} diff --git a/cp/cp-10565.jsonl b/cp/cp-10565.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..27cb5c84ba9d953c9a140dcf3712d592a28002a6 --- /dev/null +++ b/cp/cp-10565.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10565", "name": "LeetCode 1103: Distribute Candies To People"} +{"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: Distribute Candies to People (Difficulty: Easy)\nTags: Math, Simulation\n\nWe distribute some number of candies, to a row of n = num_people people in the following way:\nWe then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person.\nThen, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person.\nThis process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies.  The last person will receive all of our remaining candies (not necessarily one more than the previous gift).\nReturn an array (of length num_people and sum candies) that represents the final distribution of candies.\n\nExample 1:\nInput: candies = 7, num_people = 4\nOutput: [1,2,3,1]\nExplanation:\nOn the first turn, ans[0] += 1, and the array is [1,0,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3,0].\nOn the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].\n\nExample 2:\nInput: candies = 10, num_people = 3\nOutput: [5,2,3]\nExplanation: \nOn the first turn, ans[0] += 1, and the array is [1,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3].\nOn the fourth turn, ans[0] += 4, and the final array is [5,2,3].\n\nConstraints:\n- 1 <= candies <= 10^9\n- 1 <= num_people <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + logc), c is the number of candies\n# Space: O(1)\n\nclass Solution(object):\n def distributeCandies(self, candies, num_people):\n \"\"\"\n :type candies: int\n :type num_people: int\n :rtype: List[int]\n \"\"\"\n # find max integer p s.t. sum(1 + 2 + ... + p) <= C\n # => remaining : 0 <= C-(1+p)*p/2 < p+1\n # => -2p-2 < p^2+p-2C <= 0\n # => 2C+1/4 < (p+3/2)^2 and (p+1/2)^2 <= 2C+1/4\n # => sqrt(2C+1/4)-3/2 < p <= sqrt(2C+1/4)-1/2\n # => p = floor(sqrt(2C+1/4)-1/2)\n p = int((2*candies + 0.25)**0.5 - 0.5) \n remaining = candies - (p+1)*p//2\n rows, cols = divmod(p, num_people)\n \n result = [0]*num_people\n for i in range(num_people):\n result[i] = (i+1)*(rows+1) + (rows*(rows+1)//2)*num_people if i < cols else \\\n (i+1)*rows + ((rows-1)*rows//2)*num_people\n result[cols] += remaining\n return result\n\n\n# Time: O(n + logc), c is the number of candies\n# Space: O(1)\nclass Solution2(object):\n def distributeCandies(self, candies, num_people):\n \"\"\"\n :type candies: int\n :type num_people: int\n :rtype: List[int]\n \"\"\"\n # find max integer p s.t. sum(1 + 2 + ... + p) <= C\n left, right = 1, candies\n while left <= right:\n mid = left + (right-left)//2\n if not ((mid <= candies*2 // (mid+1))):\n right = mid-1\n else:\n left = mid+1\n p = right\n remaining = candies - (p+1)*p//2\n rows, cols = divmod(p, num_people)\n \n result = [0]*num_people\n for i in range(num_people):\n result[i] = (i+1)*(rows+1) + (rows*(rows+1)//2)*num_people if i < cols else \\\n (i+1)*rows + ((rows-1)*rows//2)*num_people\n result[cols] += remaining\n return result\n\n\n# Time: O(sqrt(c)), c is the number of candies\n# Space: O(1)\nclass Solution3(object):\n def distributeCandies(self, candies, num_people):\n \"\"\"\n :type candies: int\n :type num_people: int\n :rtype: List[int]\n \"\"\"\n result = [0]*num_people\n i = 0\n while candies != 0:\n result[i % num_people] += min(candies, i+1)\n candies -= min(candies, i+1)\n i += 1\n return result\n"}} diff --git a/cp/cp-10566.jsonl b/cp/cp-10566.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a8731976e367b237332533b3eaaec71d5572c643 --- /dev/null +++ b/cp/cp-10566.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10566", "name": "LeetCode 1104: Path In Zigzag Labelled 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: Path In Zigzag Labelled Binary Tree (Difficulty: Medium)\nTags: Math, Tree, Binary Tree\n\nIn an infinite binary tree where every node has two children, the nodes are labelled in row order.\nIn the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.\nGiven the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label.\n\nExample 1:\nInput: label = 14\nOutput: [1,3,4,14]\n\nExample 2:\nInput: label = 26\nOutput: [1,2,6,10,26]\n\nConstraints:\n- 1 <= label <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(logn)\n\nclass Solution(object):\n def pathInZigZagTree(self, label):\n \"\"\"\n :type label: int\n :rtype: List[int]\n \"\"\"\n count = 2**label.bit_length()\n result = []\n while label >= 1:\n result.append(label)\n label = ((count//2) + ((count-1)-label)) // 2\n count //= 2\n result.reverse()\n return result\n"}} diff --git a/cp/cp-10567.jsonl b/cp/cp-10567.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ac8777f53339b89ee539e497ad7f96fc1ea5f81d --- /dev/null +++ b/cp/cp-10567.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10567", "name": "LeetCode 1105: Filling Bookcase Shelves"} +{"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: Filling Bookcase Shelves (Difficulty: Medium)\nTags: Array, Dynamic Programming\n\nYou are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth.\nWe want to place these books in order onto bookcase shelves that have a total width shelfWidth.\nWe choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place.\nNote that at each step of the above process, the order of the books we place is the same order as the given sequence of books.\nReturn the minimum possible height that the total bookshelf can be after placing shelves in this manner.\n\nExample 1:\nInput: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4\nOutput: 6\nExplanation:\nThe sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.\nNotice that book number 2 does not have to be on the first shelf.\n\nExample 2:\nInput: books = [[1,3],[2,4],[3,2]], shelfWidth = 6\nOutput: 4\n\nConstraints:\n- 1 <= books.length <= 1000\n- 1 <= thicknessi <= shelfWidth <= 1000\n- 1 <= heighti <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def minHeightShelves(self, books, shelf_width):\n \"\"\"\n :type books: List[List[int]]\n :type shelf_width: int\n :rtype: int\n \"\"\"\n dp = [float(\"inf\") for _ in range(len(books)+1)]\n dp[0] = 0\n for i in range(1, len(books)+1):\n max_width = shelf_width\n max_height = 0\n for j in reversed(range(i)):\n if max_width-books[j][0] < 0:\n break\n max_width -= books[j][0]\n max_height = max(max_height, books[j][1])\n dp[i] = min(dp[i], dp[j]+max_height)\n return dp[len(books)]\n"}} diff --git a/cp/cp-10568.jsonl b/cp/cp-10568.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5999370312e6833ec0b73de81ce92d38c1cfa351 --- /dev/null +++ b/cp/cp-10568.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10568", "name": "LeetCode 1106: Parsing A Boolean Expression"} +{"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: Parsing A Boolean Expression (Difficulty: Hard)\nTags: String, Stack, Recursion\n\nA boolean expression is an expression that evaluates to either true or false. It can be in one of the following shapes:\nGiven a string expression that represents a boolean expression, return the evaluation of that expression.\nIt is guaranteed that the given expression is valid and follows the given rules.\n\nExample 1:\nInput: expression = \"&(|(f))\"\nOutput: false\nExplanation: \nFirst, evaluate |(f) --> f. The expression is now \"&(f)\".\nThen, evaluate &(f) --> f. The expression is now \"f\".\nFinally, return false.\n\nExample 2:\nInput: expression = \"|(f,f,f,t)\"\nOutput: true\nExplanation: The evaluation of (false OR false OR false OR true) is true.\n\nExample 3:\nInput: expression = \"!(&(f,t))\"\nOutput: true\nExplanation: \nFirst, evaluate &(f,t) --> (false AND true) --> false --> f. The expression is now \"!(f)\".\nThen, evaluate !(f) --> NOT false --> true. We return true.\n\nConstraints:\n- 1 <= expression.length <= 2 * 10^4\n- expression[i] is one following characters: '(', ')', '&', '|', '!', 't', 'f', and ','."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def parseBoolExpr(self, expression):\n \"\"\"\n :type expression: str\n :rtype: bool\n \"\"\"\n def parse(expression, i):\n if expression[i[0]] not in \"&|!\":\n result = expression[i[0]] == 't'\n i[0] += 1\n return result\n op = expression[i[0]]\n i[0] += 2\n stk = []\n while expression[i[0]] != ')':\n if expression[i[0]] == ',': \n i[0] += 1\n continue\n stk.append(parse(expression, i))\n i[0] += 1\n if op == '&':\n return all(stk)\n if op == '|':\n return any(stk)\n return not stk[0]\n\n return parse(expression, [0])\n"}} diff --git a/cp/cp-10569.jsonl b/cp/cp-10569.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f61da42964e503d45bcff1c4afdc41dff8d7d65b --- /dev/null +++ b/cp/cp-10569.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10569", "name": "LeetCode 1108: Defanging An Ip Address"} +{"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: Defanging an IP Address (Difficulty: Easy)\nTags: String\n\nGiven a valid (IPv4) IP address, return a defanged version of that IP address.\nA defanged IP address replaces every period \".\" with \"[.]\".\n\nExample 1:\nInput: address = \"1.1.1.1\"\r\nOutput: \"1[.]1[.]1[.]1\"\n\nExample 2:\nInput: address = \"255.100.50.0\"\r\nOutput: \"255[.]100[.]50[.]0\"\n\nConstraints:\n- The given address is a valid IPv4 address."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def defangIPaddr(self, address):\n \"\"\"\n :type address: str\n :rtype: str\n \"\"\"\n result = []\n for c in address:\n if c == '.':\n result.append(\"[.]\")\n else:\n result.append(c)\n return \"\".join(result)\n"}} diff --git a/cp/cp-10570.jsonl b/cp/cp-10570.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0aacc31ed3f19e22c139c70b12578f025fe96511 --- /dev/null +++ b/cp/cp-10570.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10570", "name": "LeetCode 1109: Corporate Flight Bookings"} +{"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: Corporate Flight Bookings (Difficulty: Medium)\nTags: Array, Prefix Sum\n\nThere are n flights that are labeled from 1 to n.\nYou are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range.\nReturn an array answer of length n, where answer[i] is the total number of seats reserved for flight i.\n\nExample 1:\nInput: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5\nOutput: [10,55,45,25,25]\nExplanation:\nFlight labels: 1 2 3 4 5\nBooking 1 reserved: 10 10\nBooking 2 reserved: 20 20\nBooking 3 reserved: 25 25 25 25\nTotal seats: 10 55 45 25 25\nHence, answer = [10,55,45,25,25]\n\nExample 2:\nInput: bookings = [[1,2,10],[2,2,15]], n = 2\nOutput: [10,25]\nExplanation:\nFlight labels: 1 2\nBooking 1 reserved: 10 10\nBooking 2 reserved: 15\nTotal seats: 10 25\nHence, answer = [10,25]\n\nConstraints:\n- 1 <= n <= 2 * 10^4\n- 1 <= bookings.length <= 2 * 10^4\n- bookings[i].length == 3\n- 1 <= firsti <= lasti <= n\n- 1 <= seatsi <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def corpFlightBookings(self, bookings, n):\n \"\"\"\n :type bookings: List[List[int]]\n :type n: int\n :rtype: List[int]\n \"\"\"\n result = [0]*(n+1)\n for i, j, k in bookings:\n result[i-1] += k\n result[j] -= k\n for i in range(1, len(result)):\n result[i] += result[i-1]\n result.pop()\n return result\n"}} diff --git a/cp/cp-10571.jsonl b/cp/cp-10571.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..62b3fe497ada8cd2da24a7559ae5833b867af62b --- /dev/null +++ b/cp/cp-10571.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10571", "name": "LeetCode 1110: Delete Nodes And Return Forest"} +{"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: Delete Nodes And Return Forest (Difficulty: Medium)\nTags: Array, Hash Table, Tree, Depth-First Search, Binary Tree\n\nGiven the root of a binary tree, each node in the tree has a distinct value.\nAfter deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).\nReturn the roots of the trees in the remaining forest. You may return the result in any order.\n\nExample 1:\nInput: root = [1,2,3,4,5,6,7], to_delete = [3,5]\nOutput: [[1,2,null,4],[6],[7]]\n\nExample 2:\nInput: root = [1,2,4,null,3], to_delete = [3]\nOutput: [[1,2,4]]\n\nConstraints:\n- The number of nodes in the given tree is at most 1000.\n- Each node has a distinct value between 1 and 1000.\n- to_delete.length <= 1000\n- to_delete contains distinct values between 1 and 1000."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h + d), d is the number of to_delete\n\n# Definition for a binary tree node.\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 delNodes(self, root, to_delete):\n \"\"\"\n :type root: TreeNode\n :type to_delete: List[int]\n :rtype: List[TreeNode]\n \"\"\"\n def delNodesHelper(to_delete_set, root, is_root, result):\n if not root:\n return None\n is_deleted = root.val in to_delete_set\n if is_root and not is_deleted:\n result.append(root)\n root.left = delNodesHelper(to_delete_set, root.left, is_deleted, result)\n root.right = delNodesHelper(to_delete_set, root.right, is_deleted, result)\n return None if is_deleted else root\n \n result = []\n to_delete_set = set(to_delete)\n delNodesHelper(to_delete_set, root, True, result)\n return result\n"}} diff --git a/cp/cp-10572.jsonl b/cp/cp-10572.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..12697d483f752d870c18b4155ae4067dc46464cc --- /dev/null +++ b/cp/cp-10572.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10572", "name": "LeetCode 1111: Maximum Nesting Depth Of Two Valid Parentheses Strings"} +{"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 Nesting Depth of Two Valid Parentheses Strings (Difficulty: Medium)\nTags: String, Stack\n\nA string is a valid parentheses string (denoted VPS) if and only if it consists of \"(\" and \")\" characters only, and:\nWe can similarly define the nesting depth depth(S) of any VPS S as follows:\nFor example,  \"\", \"()()\", and \"()(()())\" are VPS's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS's.\nGiven a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length).\nNow choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value.\nReturn an answer array (of length seq.length) that encodes such a choice of A and B:  answer[i] = 0 if seq[i] is part of A, else answer[i] = 1.  Note that even though multiple answers may exist, you may return any of them.\n\nExample 1:\nInput: seq = \"(()())\"\nOutput: [0,1,1,1,1,0]\n\nExample 2:\nInput: seq = \"()(())()\"\nOutput: [0,0,0,1,1,0,1,1]\n\nConstraints:\n- 1 <= seq.size <= 10000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxDepthAfterSplit(self, seq):\n \"\"\"\n :type seq: str\n :rtype: List[int]\n \"\"\"\n return [(i & 1) ^ (seq[i] == '(') for i, c in enumerate(seq)]\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def maxDepthAfterSplit(self, seq):\n \"\"\"\n :type seq: str\n :rtype: List[int]\n \"\"\"\n A, B = 0, 0\n result = [0]*len(seq)\n for i, c in enumerate(seq):\n point = 1 if c == '(' else -1\n if (point == 1 and A <= B) or \\\n (point == -1 and A >= B):\n A += point\n else:\n B += point\n result[i] = 1\n return result\n"}} diff --git a/cp/cp-10573.jsonl b/cp/cp-10573.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1774e9c1ab0d76dea7dc3be2356e69ba36a629f8 --- /dev/null +++ b/cp/cp-10573.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10573", "name": "LeetCode 1114: Print In Order"} +{"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 in Order (Difficulty: Easy)\nTags: Concurrency\n\nSuppose we have a class:\nThe same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().\nNote:\nWe do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.\n\nExample 1:\npublic class Foo {\n public void first() { print(\"first\"); }\n public void second() { print(\"second\"); }\n public void third() { print(\"third\"); }\n}\n\nExample 2:\nInput: nums = [1,2,3]\nOutput: \"firstsecondthird\"\nExplanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). \"firstsecondthird\" is the correct output.\n\nExample 3:\nInput: nums = [1,3,2]\nOutput: \"firstsecondthird\"\nExplanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). \"firstsecondthird\" is the correct output.\n\nConstraints:\n- nums is a permutation of [1, 2, 3]."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport threading\n\n\nclass Foo(object):\n def __init__(self):\n self.__cv = threading.Condition()\n self.__has_first = False\n self.__has_second = False\n\n def first(self, printFirst):\n \"\"\"\n :type printFirst: method\n :rtype: void\n \"\"\"\n with self.__cv:\n # printFirst() outputs \"first\". Do not change or remove this line.\n printFirst() \n self.__has_first = True\n self.__cv.notifyAll()\n\n def second(self, printSecond):\n \"\"\"\n :type printSecond: method\n :rtype: void\n \"\"\"\n with self.__cv:\n while not self.__has_first:\n self.__cv.wait()\n # printSecond() outputs \"second\". Do not change or remove this line.\n printSecond()\n self.__has_second = True\n self.__cv.notifyAll()\n \n def third(self, printThird):\n \"\"\"\n :type printThird: method\n :rtype: void\n \"\"\"\n with self.__cv:\n while not self.__has_second:\n self.__cv.wait()\n # printThird() outputs \"third\". Do not change or remove this line.\n printThird()\n self.__cv.notifyAll()\n \n"}} diff --git a/cp/cp-10574.jsonl b/cp/cp-10574.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..035192510c0f4dbad09591c244c39d9619c57a82 --- /dev/null +++ b/cp/cp-10574.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10574", "name": "LeetCode 1115: Print Foobar Alternately"} +{"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 FooBar Alternately (Difficulty: Medium)\nTags: Concurrency\n\nSuppose you are given the following code:\nThe same instance of FooBar will be passed to two different threads:\nModify the given program to output \"foobar\" n times.\n\nExample 1:\nclass FooBar {\n public void foo() {\n for (int i = 0; i < n; i++) {\n print(\"foo\");\n }\n }\n\n public void bar() {\n for (int i = 0; i < n; i++) {\n print(\"bar\");\n }\n }\n}\n\nExample 2:\nInput: n = 1\nOutput: \"foobar\"\nExplanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar().\n\"foobar\" is being output 1 time.\n\nExample 3:\nInput: n = 2\nOutput: \"foobarfoobar\"\nExplanation: \"foobar\" is being output 2 times.\n\nConstraints:\n- 1 <= n <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport threading\n\n\nclass FooBar(object):\n def __init__(self, n):\n self.__n = n\n self.__curr = False\n self.__cv = threading.Condition()\n\n def foo(self, printFoo):\n \"\"\"\n :type printFoo: method\n :rtype: void\n \"\"\"\n for i in range(self.__n):\n with self.__cv:\n while self.__curr != False:\n self.__cv.wait()\n self.__curr = not self.__curr\n # printFoo() outputs \"foo\". Do not change or remove this line.\n printFoo()\n self.__cv.notify()\n\n def bar(self, printBar):\n \"\"\"\n :type printBar: method\n :rtype: void\n \"\"\"\n for i in range(self.__n):\n with self.__cv:\n while self.__curr != True:\n self.__cv.wait()\n self.__curr = not self.__curr\n # printBar() outputs \"bar\". Do not change or remove this line.\n printBar()\n self.__cv.notify()\n"}} diff --git a/cp/cp-10575.jsonl b/cp/cp-10575.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ad66f9bd1b5d571ee6e39ecc2de3536cd03a8463 --- /dev/null +++ b/cp/cp-10575.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10575", "name": "LeetCode 1116: Print Zero Even Odd"} +{"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 Zero Even Odd (Difficulty: Medium)\nTags: Concurrency\n\nYou have a function printNumber that can be called with an integer parameter and prints it to the console.\nYou are given an instance of the class ZeroEvenOdd that has three functions: zero, even, and odd. The same instance of ZeroEvenOdd will be passed to three different threads:\nModify the given class to output the series \"010203040506...\" where the length of the series must be 2n.\nImplement the ZeroEvenOdd class:\n\nExample 1:\nInput: n = 2\nOutput: \"0102\"\nExplanation: There are three threads being fired asynchronously.\nOne of them calls zero(), the other calls even(), and the last one calls odd().\n\"0102\" is the correct output.\n\nExample 2:\nInput: n = 5\nOutput: \"0102030405\"\n\nConstraints:\n- 1 <= n <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport threading\n\n\nclass ZeroEvenOdd(object):\n def __init__(self, n):\n self.__n = n\n self.__curr = 0\n self.__cv = threading.Condition()\n \n\t# printNumber(x) outputs \"x\", where x is an integer.\n def zero(self, printNumber):\n \"\"\"\n :type printNumber: method\n :rtype: void\n \"\"\"\n for i in range(self.__n):\n with self.__cv:\n while self.__curr % 2 != 0:\n self.__cv.wait()\n self.__curr += 1\n printNumber(0)\n self.__cv.notifyAll()\n \n def even(self, printNumber):\n \"\"\"\n :type printNumber: method\n :rtype: void\n \"\"\"\n for i in range(2, self.__n+1, 2):\n with self.__cv:\n while self.__curr % 4 != 3:\n self.__cv.wait()\n self.__curr += 1\n printNumber(i)\n self.__cv.notifyAll()\n \n def odd(self, printNumber):\n \"\"\"\n :type printNumber: method\n :rtype: void\n \"\"\"\n for i in range(1, self.__n+1, 2):\n with self.__cv:\n while self.__curr % 4 != 1:\n self.__cv.wait()\n self.__curr += 1\n printNumber(i)\n self.__cv.notifyAll()\n"}} diff --git a/cp/cp-10576.jsonl b/cp/cp-10576.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9e4d1363eaccbdbd6d17c132b1ca3db6ccbc297a --- /dev/null +++ b/cp/cp-10576.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10576", "name": "LeetCode 1117: Building H2O"} +{"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: Building H2O (Difficulty: Medium)\nTags: Concurrency\n\nThere are two kinds of threads: oxygen and hydrogen. Your goal is to group these threads to form water molecules.\nThere is a barrier where each thread has to wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given releaseHydrogen and releaseOxygen methods respectively, which will allow them to pass the barrier. These threads should pass the barrier in groups of three, and they must immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do.\nIn other words:\nWe do not have to worry about matching the threads up explicitly; the threads do not necessarily know which other threads they are paired up with. The key is that threads pass the barriers in complete sets; thus, if we examine the sequence of threads that bind and divide them into groups of three, each group should contain one oxygen and two hydrogen threads.\nWrite synchronization code for oxygen and hydrogen molecules that enforces these constraints.\n\nExample 1:\nInput: water = \"HOH\"\nOutput: \"HHO\"\nExplanation: \"HOH\" and \"OHH\" are also valid answers.\n\nExample 2:\nInput: water = \"OOHHHH\"\nOutput: \"HHOHHO\"\nExplanation: \"HOHHHO\", \"OHHHHO\", \"HHOHOH\", \"HOHHOH\", \"OHHHOH\", \"HHOOHH\", \"HOHOHH\" and \"OHHOHH\" are also valid answers.\n\nConstraints:\n- 3 * n == water.length\n- 1 <= n <= 20\n- water[i] is either 'H' or 'O'.\n- There will be exactly 2 * n 'H' in water.\n- There will be exactly n 'O' in water."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport threading\n\n\nclass H2O(object):\n def __init__(self):\n self.__l = threading.Lock()\n self.__nH = 0\n self.__nO = 0\n self.__releaseHydrogen = None\n self.__releaseOxygen = None\n\n def hydrogen(self, releaseHydrogen):\n with self.__l:\n self.__releaseHydrogen = releaseHydrogen\n self.__nH += 1\n self.__output()\n\n def oxygen(self, releaseOxygen):\n with self.__l:\n self.__releaseOxygen = releaseOxygen\n self.__nO += 1\n self.__output()\n\n def __output(self):\n while self.__nH >= 2 and \\\n self.__nO >= 1:\n self.__nH -= 2\n self.__nO -= 1\n self.__releaseHydrogen()\n self.__releaseHydrogen()\n self.__releaseOxygen()\n\n\n# Time: O(n)\n# Space: O(1)\n# TLE\nclass H2O2(object):\n def __init__(self):\n self.__nH = 0\n self.__nO = 0\n self.__cv = threading.Condition()\n\n def hydrogen(self, releaseHydrogen):\n \"\"\"\n :type releaseHydrogen: method\n :rtype: void\n \"\"\"\n with self.__cv:\n while (self.__nH+1) - 2*self.__nO > 2:\n self.__cv.wait()\n self.__nH += 1\n # releaseHydrogen() outputs \"H\". Do not change or remove this line.\n releaseHydrogen()\n self.__cv.notifyAll()\n\n def oxygen(self, releaseOxygen):\n \"\"\"\n :type releaseOxygen: method\n :rtype: void\n \"\"\"\n with self.__cv:\n while 2*(self.__nO+1) - self.__nH > 2:\n self.__cv.wait()\n self.__nO += 1\n # releaseOxygen() outputs \"O\". Do not change or remove this line.\n releaseOxygen()\n self.__cv.notifyAll()\n"}} diff --git a/cp/cp-10581.jsonl b/cp/cp-10581.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..15e311731996bf47cec4b8a5ade372ea367b1dc0 --- /dev/null +++ b/cp/cp-10581.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10581", "name": "LeetCode 1122: Relative Sort 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: Relative Sort Array (Difficulty: Easy)\nTags: Array, Hash Table, Sorting, Counting Sort\n\nGiven two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.\nSort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.\n\nExample 1:\nInput: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]\nOutput: [2,2,2,1,4,3,3,9,6,7,19]\n\nExample 2:\nInput: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]\nOutput: [22,28,8,6,17,44]\n\nConstraints:\n- 1 <= arr1.length, arr2.length <= 1000\n- 0 <= arr1[i], arr2[i] <= 1000\n- All the elements of arr2 are distinct.\n- Each arr2[i] is in arr1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass Solution(object):\n def relativeSortArray(self, arr1, arr2):\n \"\"\"\n :type arr1: List[int]\n :type arr2: List[int]\n :rtype: List[int]\n \"\"\"\n lookup = {v: i for i, v in enumerate(arr2)}\n return sorted(arr1, key=lambda i: lookup.get(i, len(arr2)+i))\n"}} diff --git a/cp/cp-10582.jsonl b/cp/cp-10582.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..685fcf7f56d8605036b74bd97b17e4c91208d2e4 --- /dev/null +++ b/cp/cp-10582.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10582", "name": "LeetCode 1123: Lowest Common Ancestor Of Deepest Leaves"} +{"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: Lowest Common Ancestor of Deepest Leaves (Difficulty: Medium)\nTags: Hash Table, Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven the root of a binary tree, return the lowest common ancestor of its deepest leaves.\nRecall that:\nNote: This question is the same as 865: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/\n\nExample 1:\nInput: root = [3,5,1,6,2,0,8,null,null,7,4]\nOutput: [2,7,4]\nExplanation: We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest leaf-nodes of the tree.\nNote that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.\n\nExample 2:\nInput: root = [1]\nOutput: [1]\nExplanation: The root is the deepest node in the tree, and it's the lca of itself.\n\nExample 3:\nInput: root = [0,1,3,null,2]\nOutput: [2]\nExplanation: The deepest leaf node in the tree is 2, the lca of one node is itself.\n\nConstraints:\n- The number of nodes in the tree will be in the range [1, 1000].\n- 0 <= Node.val <= 1000\n- The values of the nodes in the tree are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 lcaDeepestLeaves(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n def lcaDeepestLeavesHelper(root):\n if not root:\n return 0, None\n d1, lca1 = lcaDeepestLeavesHelper(root.left)\n d2, lca2 = lcaDeepestLeavesHelper(root.right)\n if d1 > d2:\n return d1+1, lca1\n if d1 < d2:\n return d2+1, lca2\n return d1+1, root\n\n return lcaDeepestLeavesHelper(root)[1]\n"}} diff --git a/cp/cp-10583.jsonl b/cp/cp-10583.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..08566bd4bb0531e15258e60e41f925f0ef8d3265 --- /dev/null +++ b/cp/cp-10583.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10583", "name": "LeetCode 1124: Longest Well Performing Interval"} +{"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 Well-Performing Interval (Difficulty: Medium)\nTags: Array, Hash Table, Stack, Monotonic Stack, Prefix Sum\n\nWe are given hours, a list of the number of hours worked per day for a given employee.\nA day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.\nA well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.\nReturn the length of the longest well-performing interval.\n\nExample 1:\nInput: hours = [9,9,6,0,6,6,9]\nOutput: 3\nExplanation: The longest well-performing interval is [9,9,6].\n\nExample 2:\nInput: hours = [6,6,6]\nOutput: 0\n\nConstraints:\n- 1 <= hours.length <= 10^4\n- 0 <= hours[i] <= 16"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def longestWPI(self, hours):\n \"\"\"\n :type hours: List[int]\n :rtype: int\n \"\"\"\n result, accu = 0, 0\n lookup = {}\n for i, h in enumerate(hours):\n accu = accu+1 if h > 8 else accu-1\n if accu > 0:\n result = i+1\n elif accu-1 in lookup:\n # lookup[accu-1] is the leftmost idx with smaller accu,\n # because for i from 1 to some positive k,\n # lookup[accu-i] is a strickly increasing sequence\n result = max(result, i-lookup[accu-1])\n lookup.setdefault(accu, i)\n return result\n"}} diff --git a/cp/cp-10584.jsonl b/cp/cp-10584.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..60ddbeb4bf6ae47e9cf301ec28b1cf7bf814b066 --- /dev/null +++ b/cp/cp-10584.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10584", "name": "LeetCode 1125: Smallest Sufficient Team"} +{"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: Smallest Sufficient Team (Difficulty: Hard)\nTags: Array, Dynamic Programming, Bit Manipulation, Bitmask\n\nIn a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has.\nConsider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.\nReturn any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.\nIt is guaranteed an answer exists.\n\nExample 1:\nInput: req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]\nOutput: [0,2]\n\nExample 2:\nInput: req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]\nOutput: [1,2]\n\nConstraints:\n- 1 <= req_skills.length <= 16\n- 1 <= req_skills[i].length <= 16\n- req_skills[i] consists of lowercase English letters.\n- All the strings of req_skills are unique.\n- 1 <= people.length <= 60\n- 0 <= people[i].length <= 16\n- 1 <= people[i][j].length <= 16\n- people[i][j] consists of lowercase English letters.\n- All the strings of people[i] are unique.\n- Every skill in people[i] is a skill in req_skills.\n- It is guaranteed a sufficient team exists."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * 2^n), n is the number of skills\n# m is the number of people\n# Space: O(2^n)\n\nclass Solution(object):\n def smallestSufficientTeam(self, req_skills, people):\n \"\"\"\n :type req_skills: List[str]\n :type people: List[List[str]]\n :rtype: List[int]\n \"\"\"\n lookup = {v: i for i, v in enumerate(req_skills)}\n dp = {0: []}\n for i, p in enumerate(people):\n his_skill_set = 0\n for skill in p:\n if skill in lookup:\n his_skill_set |= 1 << lookup[skill]\n for skill_set, people in dp.items():\n with_him = skill_set | his_skill_set\n if with_him == skill_set: continue\n if with_him not in dp or \\\n len(dp[with_him]) > len(people)+1:\n dp[with_him] = people + [i]\n return dp[(1< 2:\n result += stk.pop() * stk[-1]\n return result\n"}} diff --git a/cp/cp-10588.jsonl b/cp/cp-10588.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1f883f277cd7559c340652fd0a6c4746a8585e67 --- /dev/null +++ b/cp/cp-10588.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10588", "name": "LeetCode 1131: Maximum Of Absolute Value Expression"} +{"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 of Absolute Value Expression (Difficulty: Medium)\nTags: Array, Math\n\nGiven two arrays of integers with equal lengths, return the maximum value of:\n|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|\nwhere the maximum is taken over all 0 <= i, j < arr1.length.\n\nExample 1:\nInput: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]\nOutput: 13\n\nExample 2:\nInput: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]\nOutput: 20\n\nConstraints:\n- 2 <= arr1.length == arr2.length <= 40000\n- -10^6 <= arr1[i], arr2[i] <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxAbsValExpr(self, arr1, arr2):\n \"\"\"\n :type arr1: List[int]\n :type arr2: List[int]\n :rtype: int\n \"\"\"\n # 1. max(|arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j| for i > j)\n # = max(|arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j| for j > i)\n # 2. for i > j:\n # (|arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j|)\n # >= c1*(arr1[i]-arr1[j]) + c2*(arr2[i]-arr2[j]) + i-j for c1 in (1, -1), c2 in (1, -1)\n # = (c1*arr1[i]+c2*arr2[i]+i) - (c1*arr1[j]+c2*arr2[j]+j) for c1 in (1, -1), c2 in (1, -1)\n # 1 + 2 => max(|arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j| for i != j)\n # = max((c1*arr1[i]+c2*arr2[i]+i) - (c1*arr1[j]+c2*arr2[j]+j)\n # for c1 in (1, -1), c2 in (1, -1) for i > j)\n result = 0\n for c1 in [1, -1]:\n for c2 in [1, -1]:\n min_prev = float(\"inf\")\n for i in range(len(arr1)):\n curr = c1*arr1[i] + c2*arr2[i] + i\n result = max(result, curr-min_prev)\n min_prev = min(min_prev, curr)\n return result\n\n \n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def maxAbsValExpr(self, arr1, arr2):\n \"\"\"\n :type arr1: List[int]\n :type arr2: List[int]\n :rtype: int\n \"\"\"\n return max(max(c1*arr1[i] + c2*arr2[i] + i for i in range(len(arr1))) -\n min(c1*arr1[i] + c2*arr2[i] + i for i in range(len(arr1)))\n for c1 in [1, -1] for c2 in [1, -1])\n"}} diff --git a/cp/cp-10593.jsonl b/cp/cp-10593.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1959c8d3a844a49e7c06a836412919ee6b52deb0 --- /dev/null +++ b/cp/cp-10593.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10593", "name": "LeetCode 1137: N Th Tribonacci 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: N-th Tribonacci Number (Difficulty: Easy)\nTags: Math, Dynamic Programming, Memoization\n\nThe Tribonacci sequence Tn is defined as follows:\nT0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.\nGiven n, return the value of Tn.\n\nExample 1:\nInput: n = 4\nOutput: 4\nExplanation:\nT_3 = 0 + 1 + 1 = 2\nT_4 = 1 + 1 + 2 = 4\n\nExample 2:\nInput: n = 25\nOutput: 1389537\n\nConstraints:\n- 0 <= n <= 37\n- The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def tribonacci(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n def matrix_expo(A, K):\n result = [[int(i==j) for j in range(len(A))] \\\n for i in range(len(A))]\n while K:\n if K % 2:\n result = matrix_mult(result, A)\n A = matrix_mult(A, A)\n K /= 2\n return result\n\n def matrix_mult(A, B):\n ZB = zip(*B)\n return [[sum(a*b for a, b in itertools.izip(row, col)) \\\n for col in ZB] for row in A]\n\n T = [[1, 1, 0],\n [1, 0, 1],\n [1, 0, 0]]\n return matrix_mult([[1, 0, 0]], matrix_expo(T, n))[0][1] # [a1, a0, a(-1)] * T^n\n \n \n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def tribonacci(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n a, b, c = 0, 1, 1\n for _ in range(n):\n a, b, c = b, c, a+b+c\n return a\n"}} diff --git a/cp/cp-10594.jsonl b/cp/cp-10594.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5d5b264b661dd09fc7da82d6a9ddc954862e8870 --- /dev/null +++ b/cp/cp-10594.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10594", "name": "LeetCode 1138: Alphabet Board Path"} +{"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: Alphabet Board Path (Difficulty: Medium)\nTags: Hash Table, String\n\nOn an alphabet board, we start at position (0, 0), corresponding to character board[0][0].\nHere, board = [\"abcde\", \"fghij\", \"klmno\", \"pqrst\", \"uvwxy\", \"z\"], as shown in the diagram below.\nWe may make the following moves:\n(Here, the only positions that exist on the board are positions with letters on them.)\nReturn a sequence of moves that makes our answer equal to target in the minimum number of moves.  You may return any path that does so.\n\nExample 1:\nInput: target = \"leet\"\r\nOutput: \"DDR!UURRR!!DDD!\"\n\nExample 2:\nInput: target = \"code\"\r\nOutput: \"RR!DDRR!UUL!R!\"\n\nConstraints:\n- 1 <= target.length <= 100\n- target consists only of English lowercase letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def alphabetBoardPath(self, target):\n \"\"\"\n :type target: str\n :rtype: str\n \"\"\"\n x, y = 0, 0\n result = []\n for c in target:\n y1, x1 = divmod(ord(c)-ord('a'), 5)\n result.append('U' * max(y-y1, 0))\n result.append('L' * max(x-x1, 0))\n result.append('R' * max(x1-x, 0))\n result.append('D' * max(y1-y, 0))\n result.append('!')\n x, y = x1, y1\n return \"\".join(result)\n"}} diff --git a/cp/cp-10595.jsonl b/cp/cp-10595.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..54ed5cae68f8213eae63e64097c1e508ec1de8ff --- /dev/null +++ b/cp/cp-10595.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10595", "name": "LeetCode 1139: Largest 1 Bordered Square"} +{"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: Largest 1-Bordered Square (Difficulty: Medium)\nTags: Array, Dynamic Programming, Matrix\n\nGiven a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid.\n\nExample 1:\nInput: grid = [[1,1,1],[1,0,1],[1,1,1]]\r\nOutput: 9\n\nExample 2:\nInput: grid = [[1,1,0,0]]\r\nOutput: 1\n\nConstraints:\n- 1 <= grid.length <= 100\n- 1 <= grid[0].length <= 100\n- grid[i][j] is 0 or 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(n^2)\n\nclass Solution(object):\n def largest1BorderedSquare(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n top, left = [a[:] for a in grid], [a[:] for a in grid]\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if not grid[i][j]:\n continue\n if i:\n top[i][j] = top[i-1][j] + 1\n if j:\n left[i][j] = left[i][j-1] + 1\n for l in reversed(range(1, min(len(grid), len(grid[0]))+1)):\n for i in range(len(grid)-l+1):\n for j in range(len(grid[0])-l+1):\n if min(top[i+l-1][j],\n top[i+l-1][j+l-1],\n left[i][j+l-1],\n left[i+l-1][j+l-1]) >= l:\n return l*l\n return 0\n"}} diff --git a/cp/cp-10596.jsonl b/cp/cp-10596.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..59469ea9c348187bdda1d645b0d4b82b21ecf30b --- /dev/null +++ b/cp/cp-10596.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10596", "name": "LeetCode 1140: Stone Game 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: Stone Game II (Difficulty: Medium)\nTags: Array, Math, Dynamic Programming, Prefix Sum, Game Theory\n\nAlice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones.\nAlice and Bob take turns, with Alice starting first.\nOn each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X). Initially, M = 1.\nThe game continues until all the stones have been taken.\nAssuming Alice and Bob play optimally, return the maximum number of stones Alice can get.\n\nExample 1:\nInput: piles = [2,7,9,4,4]\nOutput: 10\nExplanation:\nSo we return 10 since it's larger.\n\nExample 2:\nInput: piles = [1,2,3,4,5,100]\nOutput: 104\n\nConstraints:\n- 1 <= piles.length <= 100\n- 1 <= piles[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n*(logn)^2)\n# Space: O(nlogn)\n\nclass Solution(object):\n def stoneGameII(self, piles):\n \"\"\"\n :type piles: List[int]\n :rtype: int\n \"\"\"\n def dp(piles, lookup, i, m):\n if i+2*m >= len(piles):\n return piles[i]\n if (i, m) not in lookup:\n lookup[i, m] = piles[i] - \\\n min(dp(piles, lookup, i+x, max(m, x))\n for x in range(1, 2*m+1))\n return lookup[i, m]\n\n for i in reversed(range(len(piles)-1)):\n piles[i] += piles[i+1]\n return dp(piles, {}, 0, 1)\n"}} diff --git a/cp/cp-10597.jsonl b/cp/cp-10597.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6e7c6462a1d81043722d6790d9580b4a4180351c --- /dev/null +++ b/cp/cp-10597.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10597", "name": "LeetCode 1143: Longest Common 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 Common Subsequence (Difficulty: Medium)\nTags: String, Dynamic Programming\n\nGiven two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.\nA subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.\nA common subsequence of two strings is a subsequence that is common to both strings.\n\nExample 1:\nInput: text1 = \"abcde\", text2 = \"ace\" \nOutput: 3 \nExplanation: The longest common subsequence is \"ace\" and its length is 3.\n\nExample 2:\nInput: text1 = \"abc\", text2 = \"abc\"\nOutput: 3\nExplanation: The longest common subsequence is \"abc\" and its length is 3.\n\nExample 3:\nInput: text1 = \"abc\", text2 = \"def\"\nOutput: 0\nExplanation: There is no such common subsequence, so the result is 0.\n\nConstraints:\n- 1 <= text1.length, text2.length <= 1000\n- text1 and text2 consist of only lowercase English characters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(min(m, n))\n\nclass Solution(object):\n def longestCommonSubsequence(self, text1, text2):\n \"\"\"\n :type text1: str\n :type text2: str\n :rtype: int\n \"\"\"\n if len(text1) < len(text2):\n return self.longestCommonSubsequence(text2, text1)\n\n dp = [[0 for _ in range(len(text2)+1)] for _ in range(2)]\n for i in range(1, len(text1)+1):\n for j in range(1, len(text2)+1):\n dp[i%2][j] = dp[(i-1)%2][j-1]+1 if text1[i-1] == text2[j-1] \\\n else max(dp[(i-1)%2][j], dp[i%2][j-1])\n return dp[len(text1)%2][len(text2)]\n"}} diff --git a/cp/cp-10598.jsonl b/cp/cp-10598.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8839b22bcfe11480a722a17fc6cce9375c0a62dd --- /dev/null +++ b/cp/cp-10598.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10598", "name": "LeetCode 1144: Decrease Elements To Make Array Zigzag"} +{"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: Decrease Elements To Make Array Zigzag (Difficulty: Medium)\nTags: Array, Greedy\n\nGiven an array nums of integers, a move consists of choosing any element and decreasing it by 1.\nAn array A is a zigzag array if either:\nReturn the minimum number of moves to transform the given array nums into a zigzag array.\n\nExample 1:\nInput: nums = [1,2,3]\nOutput: 2\nExplanation: We can decrease 2 to 0 or 3 to 1.\n\nExample 2:\nInput: nums = [9,6,1,6,2]\nOutput: 4\n\nConstraints:\n- 1 <= nums.length <= 1000\n- 1 <= nums[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def movesToMakeZigzag(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result = [0, 0]\n for i in range(len(nums)):\n left = nums[i-1] if i-1 >= 0 else float(\"inf\")\n right = nums[i+1] if i+1 < len(nums) else float(\"inf\")\n result[i%2] += max(nums[i] - min(left, right) + 1, 0)\n return min(result)\n"}} diff --git a/cp/cp-10599.jsonl b/cp/cp-10599.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a815bcd151b3ae14e8dfa055a752053b3c88a655 --- /dev/null +++ b/cp/cp-10599.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10599", "name": "LeetCode 1145: Binary Tree Coloring Game"} +{"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: Binary Tree Coloring Game (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Tree\n\nTwo players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n.\nInitially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y != x. The first player colors the node with value x red, and the second player colors the node with value y blue.\nThen, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.)\nIf (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes.\nYou are the second player. If it is possible to choose such a y to ensure you win the game, return true. If it is not possible, return false.\n\nExample 1:\nInput: root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3\nOutput: true\nExplanation: The second player can choose the node with value 2.\n\nExample 2:\nInput: root = [1,2,3], n = 3, x = 1\nOutput: false\n\nConstraints:\n- The number of nodes in the tree is n.\n- 1 <= x <= n <= 100\n- n is odd.\n- 1 <= Node.val <= n\n- All the values of the tree are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 btreeGameWinningMove(self, root, n, x):\n \"\"\"\n :type root: TreeNode\n :type n: int\n :type x: int\n :rtype: bool\n \"\"\"\n def count(node, x, left_right):\n if not node:\n return 0\n left, right = count(node.left, x, left_right), count(node.right, x, left_right)\n if node.val == x:\n left_right[0], left_right[1] = left, right\n return left + right + 1\n\n left_right = [0, 0]\n count(root, x, left_right)\n blue = max(max(left_right), n-(sum(left_right)+1))\n return blue > n-blue\n"}} diff --git a/cp/cp-10600.jsonl b/cp/cp-10600.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b9dec9049b40b1941e867d7dfc2e84278e40637f --- /dev/null +++ b/cp/cp-10600.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10600", "name": "LeetCode 1146: Snapshot 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: Snapshot Array (Difficulty: Medium)\nTags: Array, Hash Table, Binary Search, Design\n\nImplement a SnapshotArray that supports the following interface:\n\nExample 1:\nInput: [\"SnapshotArray\",\"set\",\"snap\",\"set\",\"get\"]\n[[3],[0,5],[],[0,6],[0,0]]\nOutput: [null,null,0,null,5]\nExplanation: \nSnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3\nsnapshotArr.set(0,5); // Set array[0] = 5\nsnapshotArr.snap(); // Take a snapshot, return snap_id = 0\nsnapshotArr.set(0,6);\nsnapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5\n\nConstraints:\n- 1 <= length <= 5 * 10^4\n- 0 <= index < length\n- 0 <= val <= 10^9\n- 0 <= snap_id < (the total number of times we call snap())\n- At most 5 * 10^4 calls will be made to set, snap, and get."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: set: O(1)\n# get: O(logn), n is the total number of set\n# Space: O(n)\n\nimport collections\nimport bisect\n\n\nclass SnapshotArray(object):\n\n def __init__(self, length):\n \"\"\"\n :type length: int\n \"\"\"\n self.__A = collections.defaultdict(lambda: [[0, 0]])\n self.__snap_id = 0\n\n\n def set(self, index, val):\n \"\"\"\n :type index: int\n :type val: int\n :rtype: None\n \"\"\"\n if self.__A[index][-1][0] == self.__snap_id:\n self.__A[index][-1][1] = val\n else:\n self.__A[index].append([self.__snap_id, val])\n\n\n def snap(self):\n \"\"\"\n :rtype: int\n \"\"\"\n self.__snap_id += 1\n return self.__snap_id - 1\n\n\n def get(self, index, snap_id):\n \"\"\"\n :type index: int\n :type snap_id: int\n :rtype: int\n \"\"\"\n i = bisect.bisect_left(self.__A[index], [snap_id+1, float(\"-inf\")]) - 1\n return self.__A[index][i][1] \n"}} diff --git a/cp/cp-10601.jsonl b/cp/cp-10601.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0106df82501d7f305a8bb50564319f4fe6d37cb6 --- /dev/null +++ b/cp/cp-10601.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10601", "name": "LeetCode 1147: Longest Chunked Palindrome Decomposition"} +{"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 Chunked Palindrome Decomposition (Difficulty: Hard)\nTags: Two Pointers, String, Dynamic Programming, Greedy, Rolling Hash, Hash Function\n\nYou are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that:\nReturn the largest possible value of k.\n\nExample 1:\nInput: text = \"ghiabcdefhelloadamhelloabcdefghi\"\nOutput: 7\nExplanation: We can split the string on \"(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)\".\n\nExample 2:\nInput: text = \"merchant\"\nOutput: 1\nExplanation: We can split the string on \"(merchant)\".\n\nExample 3:\nInput: text = \"antaprezatepzapreanta\"\nOutput: 11\nExplanation: We can split the string on \"(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)\".\n\nConstraints:\n- 1 <= text.length <= 1000\n- text consists only of lowercase English characters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# Rabin-Karp Algorithm\nclass Solution(object):\n def longestDecomposition(self, text):\n \"\"\"\n :type text: str\n :rtype: int\n \"\"\"\n def compare(text, l, s1, s2):\n for i in range(l):\n if text[s1+i] != text[s2+i]:\n return False\n return True\n\n MOD = 10**9+7\n D = 26\n result = 0\n left, right, l, pow_D = 0, 0, 0, 1\n for i in range(len(text)):\n left = (D*left + (ord(text[i])-ord('a'))) % MOD\n right = (pow_D*(ord(text[-1-i])-ord('a')) + right) % MOD\n l += 1\n pow_D = (pow_D*D) % MOD \n if left == right and compare(text, l, i-l+1, len(text)-1-i):\n result += 1\n left, right, l, pow_D = 0, 0, 0, 1\n return result\n"}} diff --git a/cp/cp-10606.jsonl b/cp/cp-10606.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..34480cc0809c58d48c977b93d45a2e23292e45f4 --- /dev/null +++ b/cp/cp-10606.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10606", "name": "LeetCode 1154: Day Of The Year"} +{"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: Day of the Year (Difficulty: Easy)\nTags: Math, String\n\nGiven a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.\n\nExample 1:\nInput: date = \"2019-01-09\"\nOutput: 9\nExplanation: Given date is the 9th day of the year in 2019.\n\nExample 2:\nInput: date = \"2019-02-10\"\nOutput: 41\n\nConstraints:\n- date.length == 10\n- date[4] == date[7] == '-', and all other date[i]'s are digits\n- date represents a calendar date between Jan 1st, 1900 and Dec 31st, 2019."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def __init__(self):\n def dayOfMonth(M):\n return (28 if (M == 2) else 31-(M-1)%7%2)\n\n self.__lookup = [0]*12\n for M in range(1, len(self.__lookup)):\n self.__lookup[M] += self.__lookup[M-1]+dayOfMonth(M)\n \n def dayOfYear(self, date):\n \"\"\"\n :type date: str\n :rtype: int\n \"\"\"\n Y, M, D = map(int, date.split(\"-\"))\n leap = 1 if M > 2 and (((Y % 4 == 0) and (Y % 100 != 0)) or (Y % 400 == 0)) else 0\n return self.__lookup[M-1]+D+leap\n\n\n# Time: O(1)\n# Space: O(1)\nclass Solution2(object):\n def dayOfYear(self, date):\n \"\"\"\n :type date: str\n :rtype: int\n \"\"\"\n def numberOfDays(Y, M):\n leap = 1 if ((Y % 4 == 0) and (Y % 100 != 0)) or (Y % 400 == 0) else 0\n return (28+leap if (M == 2) else 31-(M-1)%7%2)\n\n Y, M, result = map(int, date.split(\"-\"))\n for i in range(1, M):\n result += numberOfDays(Y, i)\n return result\n"}} diff --git a/cp/cp-10607.jsonl b/cp/cp-10607.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..164506ae1e3173ccb126a900e37ece4c967e8986 --- /dev/null +++ b/cp/cp-10607.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10607", "name": "LeetCode 1155: Number Of Dice Rolls With Target Sum"} +{"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 Dice Rolls With Target Sum (Difficulty: Medium)\nTags: Dynamic Programming\n\nYou have n dice, and each dice has k faces numbered from 1 to k.\nGiven three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice, so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: n = 1, k = 6, target = 3\nOutput: 1\nExplanation: You throw one die with 6 faces.\nThere is only one way to get a sum of 3.\n\nExample 2:\nInput: n = 2, k = 6, target = 7\nOutput: 6\nExplanation: You throw two dice, each with 6 faces.\nThere are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.\n\nExample 3:\nInput: n = 30, k = 30, target = 500\nOutput: 222616187\nExplanation: The answer must be returned modulo 109 + 7.\n\nConstraints:\n- 1 <= n, k <= 30\n- 1 <= target <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(d * f * t)\n# Space: O(t)\n\nclass Solution(object):\n def numRollsToTarget(self, d, f, target):\n \"\"\"\n :type d: int\n :type f: int\n :type target: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n dp = [[0 for _ in range(target+1)] for _ in range(2)]\n dp[0][0] = 1\n for i in range(1, d+1):\n dp[i%2] = [0 for _ in range(target+1)]\n for k in range(1, f+1):\n for j in range(k, target+1):\n dp[i%2][j] = (dp[i%2][j] + dp[(i-1)%2][j-k]) % MOD\n return dp[d%2][target] % MOD\n"}} diff --git a/cp/cp-10608.jsonl b/cp/cp-10608.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9e25c72ade919c390ab02f0a2ae7cc4697f7b2da --- /dev/null +++ b/cp/cp-10608.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10608", "name": "LeetCode 1156: Swap For Longest Repeated Character Substring"} +{"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: Swap For Longest Repeated Character Substring (Difficulty: Medium)\nTags: Hash Table, String, Sliding Window\n\nYou are given a string text. You can swap two of the characters in the text.\nReturn the length of the longest substring with repeated characters.\n\nExample 1:\nInput: text = \"ababa\"\nOutput: 3\nExplanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is \"aaa\" with length 3.\n\nExample 2:\nInput: text = \"aaabaaa\"\nOutput: 6\nExplanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring \"aaaaaa\" with length 6.\n\nExample 3:\nInput: text = \"aaaaa\"\nOutput: 5\nExplanation: No need to swap, longest repeated character substring is \"aaaaa\" with length is 5.\n\nConstraints:\n- 1 <= text.length <= 2 * 10^4\n- text consist of lowercase English characters only."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def maxRepOpt1(self, text):\n \"\"\"\n :type text: str\n :rtype: int\n \"\"\"\n K = 1\n result = 0\n total_count, count = collections.Counter(), collections.Counter()\n left, max_count = 0, 0\n for i in range(len(text)):\n total_count[text[i]] += 1\n count[text[i]] += 1\n max_count = max(max_count, count[text[i]])\n if i-left+1 - max_count > K:\n count[text[left]] -= 1\n left += 1\n result = max(result, min(i-left+1, total_count[text[i]]))\n return result\n\n\n \n# Time: O(n)\n# Space: O(n)\nimport itertools\n\n\nclass Solution2(object):\n def maxRepOpt1(self, text):\n \"\"\"\n :type text: str\n :rtype: int\n \"\"\"\n A = [[c, len(list(group))] for c, group in itertools.groupby(text)]\n total_count = collections.Counter(text)\n result = max(min(l+1, total_count[c]) for c, l in A)\n for i in range(1, len(A)-1):\n if A[i-1][0] == A[i+1][0] and A[i][1] == 1:\n result = max(result, min(A[i-1][1] + 1 + A[i+1][1], total_count[A[i+1][0]]))\n return result\n"}} diff --git a/cp/cp-10609.jsonl b/cp/cp-10609.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..76fa8ea7088795c693c402dee2c42ccd60a8f1f3 --- /dev/null +++ b/cp/cp-10609.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10609", "name": "LeetCode 1157: Online Majority Element In Subarray"} +{"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: Online Majority Element In Subarray (Difficulty: Hard)\nTags: Array, Binary Search, Design, Binary Indexed Tree, Segment Tree\n\nDesign a data structure that efficiently finds the majority element of a given subarray.\nThe majority element of a subarray is an element that occurs threshold times or more in the subarray.\nImplementing the MajorityChecker class:\n\nExample 1:\nInput\n[\"MajorityChecker\", \"query\", \"query\", \"query\"]\n[[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]]\nOutput\n[null, 1, -1, 2]\n\nExplanation\nMajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]);\nmajorityChecker.query(0, 5, 4); // return 1\nmajorityChecker.query(0, 3, 3); // return -1\nmajorityChecker.query(2, 3, 2); // return 2\n\nConstraints:\n- 1 <= arr.length <= 2 * 10^4\n- 1 <= arr[i] <= 2 * 10^4\n- 0 <= left <= right < arr.length\n- threshold <= right - left + 1\n- 2 * threshold > right - left + 1\n- At most 104 calls will be made to query."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(n)\n# query: O(klogn), k = log2(Q/ERROR_RATE)\n# Space: O(n)\n\nimport collections\nimport random\nimport bisect\n\n\nclass MajorityChecker(object):\n\n def __init__(self, arr):\n \"\"\"\n :type arr: List[int]\n \"\"\"\n Q, ERROR_RATE = 10000, 0.001\n self.__K = int(Q/ERROR_RATE).bit_length() # floor(log2(Q/ERROR_RATE))+1 = 24\n self.__arr = arr\n self.__inv_idx = collections.defaultdict(list)\n for i, x in enumerate(self.__arr):\n self.__inv_idx[x].append(i)\n\n def query(self, left, right, threshold):\n \"\"\"\n :type left: int\n :type right: int\n :type threshold: int\n :rtype: int\n \"\"\"\n def count(inv_idx, m, left, right):\n return bisect.bisect_right(inv_idx[m], right) - \\\n bisect.bisect_left(inv_idx[m], left)\n\n for _ in range(self.__K):\n m = self.__arr[random.randint(left, right)]\n if count(self.__inv_idx, m, left, right) >= threshold:\n return m\n return -1\n\n\n# Time: ctor: O(n)\n# query: O(sqrt(n)*logn)\n# Space: O(n)\nimport collections\nimport bisect\n\n\nclass MajorityChecker2(object):\n\n def __init__(self, arr):\n \"\"\"\n :type arr: List[int]\n \"\"\"\n self.__arr = arr\n self.__inv_idx = collections.defaultdict(list)\n for i, x in enumerate(self.__arr):\n self.__inv_idx[x].append(i)\n self.__bound = int(round((len(arr)**0.5)))\n self.__majorities = [i for i, group in self.__inv_idx.iteritems() if len(group) >= self.__bound]\n\n def query(self, left, right, threshold):\n \"\"\"\n :type left: int\n :type right: int\n :type threshold: int\n :rtype: int\n \"\"\"\n def count(inv_idx, m, left, right):\n return bisect.bisect_right(inv_idx[m], right) - \\\n bisect.bisect_left(inv_idx[m], left)\n\n def boyer_moore_majority_vote(nums, left, right):\n m, cnt = nums[left], 1\n for i in range(left+1, right+1):\n if m == nums[i]:\n cnt += 1\n else:\n cnt -= 1\n if cnt == 0:\n m = nums[i]\n cnt = 1\n return m\n\n if right-left+1 < self.__bound:\n m = boyer_moore_majority_vote(self.__arr, left, right)\n if count(self.__inv_idx, m, left, right) >= threshold:\n return m\n else:\n for m in self.__majorities:\n if count(self.__inv_idx, m, left, right) >= threshold:\n return m\n return -1\n\n\n# Time: ctor: O(nlogn)\n# query: O((logn)^2)\n# Space: O(n)\nimport functools\n\n\nclass SegmentTreeRecu(object): # 0-based index\n def __init__(self, nums, count):\n \"\"\"\n initialize your data structure here.\n :type nums: List[int]\n \"\"\"\n N = len(nums)\n self.__original_length = N\n self.__tree_length = 2**(N.bit_length() + (N&(N-1) != 0))-1\n self.__tree = [-1 for _ in range(self.__tree_length)]\n self.__count = count\n self.__constructTree(nums, 0, self.__original_length-1, 0)\n\n def query(self, i, j):\n return self.__queryRange(i, j, 0, self.__original_length-1, 0)\n\n def __constructTree(self, nums, left, right, idx):\n if left > right:\n return\n if left == right:\n self.__tree[idx] = nums[left]\n return \n mid = left + (right-left)//2\n self.__constructTree(nums, left, mid, idx*2 + 1)\n self.__constructTree(nums, mid+1, right, idx*2 + 2)\n if self.__tree[idx*2 + 1] != -1 and \\\n self.__count(self.__tree[idx*2 + 1], left, right)*2 > right-left+1:\n self.__tree[idx] = self.__tree[idx*2 + 1] \n elif self.__tree[idx*2 + 2] != -1 and \\\n self.__count(self.__tree[idx*2 + 2], left, right)*2 > right-left+1:\n self.__tree[idx] = self.__tree[idx*2 + 2] \n\n def __queryRange(self, range_left, range_right, left, right, idx):\n if left > right:\n return (-1, -1)\n if right < range_left or left > range_right:\n return (-1, -1)\n if range_left <= left and right <= range_right:\n if self.__tree[idx] != -1:\n c = self.__count(self.__tree[idx], range_left, range_right)\n if c*2 > range_right-range_left+1:\n return (self.__tree[idx], c)\n else:\n mid = left + (right-left)//2\n result = self.__queryRange(range_left, range_right, left, mid, idx*2 + 1)\n if result[0] != -1:\n return result\n result = self.__queryRange(range_left, range_right, mid + 1, right, idx*2 + 2)\n if result[0] != -1:\n return result\n return (-1, -1)\n\n\nclass MajorityChecker3(object):\n\n def __init__(self, arr):\n \"\"\"\n :type arr: List[int]\n \"\"\"\n def count(inv_idx, m, left, right):\n return bisect.bisect_right(inv_idx[m], right) - \\\n bisect.bisect_left(inv_idx[m], left)\n\n self.__arr = arr\n self.__inv_idx = collections.defaultdict(list)\n for i, x in enumerate(self.__arr):\n self.__inv_idx[x].append(i)\n self.__segment_tree = SegmentTreeRecu(arr, functools.partial(count, self.__inv_idx))\n\n def query(self, left, right, threshold):\n \"\"\"\n :type left: int\n :type right: int\n :type threshold: int\n :rtype: int\n \"\"\"\n result = self.__segment_tree.query(left, right)\n if result[1] >= threshold:\n return result[0]\n return -1\n\n\n# Time: ctor: O(n)\n# query: O(sqrt(n)*logn)\n# Space: O(n)\nimport collections\nimport bisect\n\n\nclass MajorityChecker4(object):\n\n def __init__(self, arr):\n \"\"\"\n :type arr: List[int]\n \"\"\"\n self.__arr = arr\n self.__inv_idx = collections.defaultdict(list)\n for i, x in enumerate(self.__arr):\n self.__inv_idx[x].append(i)\n self.__bucket_size = int(round((len(arr)**0.5)))\n self.__bucket_majorities = []\n for left in range(0, len(self.__arr), self.__bucket_size):\n right = min(left+self.__bucket_size-1, len(self.__arr)-1)\n self.__bucket_majorities.append(self.__boyer_moore_majority_vote(self.__arr, left, right))\n\n def query(self, left, right, threshold):\n \"\"\"\n :type left: int\n :type right: int\n :type threshold: int\n :rtype: int\n \"\"\"\n def count(inv_idx, m, left, right):\n return bisect.bisect_right(inv_idx[m], right) - \\\n bisect.bisect_left(inv_idx[m], left)\n\n l, r = left//self.__bucket_size, right//self.__bucket_size\n if l == r:\n m = self.__boyer_moore_majority_vote(self.__arr, left, right)\n if count(self.__inv_idx, m, left, right) >= threshold:\n return m\n return -1\n else:\n m = self.__boyer_moore_majority_vote(self.__arr, left, (l+1)*self.__bucket_size-1)\n if count(self.__inv_idx, m, left, right) >= threshold:\n return m\n m = self.__boyer_moore_majority_vote(self.__arr, r*self.__bucket_size, right)\n if count(self.__inv_idx, m, left, right) >= threshold:\n return m\n for i in range(l+1, r):\n if count(self.__inv_idx, self.__bucket_majorities[i], left, right) >= threshold:\n return self.__bucket_majorities[i]\n return -1\n \n def __boyer_moore_majority_vote(self, nums, left, right):\n m, cnt = nums[left], 1\n for i in range(left+1, right+1):\n if m == nums[i]:\n cnt += 1\n else:\n cnt -= 1\n if cnt == 0:\n m = nums[i]\n cnt = 1\n return m\n"}} diff --git a/cp/cp-10610.jsonl b/cp/cp-10610.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6570e185f19103411b14058177cc48756b257c2a --- /dev/null +++ b/cp/cp-10610.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10610", "name": "LeetCode 1160: Find Words That Can Be Formed By Characters"} +{"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 Words That Can Be Formed by Characters (Difficulty: Easy)\nTags: Array, Hash Table, String, Counting\n\nYou are given an array of strings words and a string chars.\nA string is good if it can be formed by characters from chars (each character can only be used once for each word in words).\nReturn the sum of lengths of all good strings in words.\n\nExample 1:\nInput: words = [\"cat\",\"bt\",\"hat\",\"tree\"], chars = \"atach\"\nOutput: 6\nExplanation: The strings that can be formed are \"cat\" and \"hat\" so the answer is 3 + 3 = 6.\n\nExample 2:\nInput: words = [\"hello\",\"world\",\"leetcode\"], chars = \"welldonehoneyr\"\nOutput: 10\nExplanation: The strings that can be formed are \"hello\" and \"world\" so the answer is 5 + 5 = 10.\n\nConstraints:\n- 1 <= words.length <= 1000\n- 1 <= words[i].length, chars.length <= 100\n- words[i] and chars consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n), m is the length of chars, n is the number of words\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def countCharacters(self, words, chars):\n \"\"\"\n :type words: List[str]\n :type chars: str\n :rtype: int\n \"\"\"\n def check(word, chars, count):\n if len(word) > len(chars):\n return False\n curr_count = collections.Counter()\n for c in word:\n curr_count[c] += 1\n if c not in count or count[c] < curr_count[c]:\n return False\n return True\n \n count = collections.Counter(chars)\n return sum(len(word) for word in words if check(word, chars, count))\n\n"}} diff --git a/cp/cp-10611.jsonl b/cp/cp-10611.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dcf168c85e1ec26f5411a13bb0ffbe110ffb2a06 --- /dev/null +++ b/cp/cp-10611.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10611", "name": "LeetCode 1161: Maximum Level Sum Of 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: Maximum Level Sum of a Binary Tree (Difficulty: Medium)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.\nReturn the smallest level x such that the sum of all the values of nodes at level x is maximal.\n\nExample 1:\nInput: root = [1,7,0,7,-8,null,null]\nOutput: 2\nExplanation: \nLevel 1 sum = 1.\nLevel 2 sum = 7 + 0 = 7.\nLevel 3 sum = 7 + -8 = -1.\nSo we return the level with the maximum sum which is level 2.\n\nExample 2:\nInput: root = [989,null,10250,98693,-89388,null,null,null,-32127]\nOutput: 2\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 104].\n- -10^5 <= Node.val <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nimport collections\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\n# dfs solution\nclass Solution(object):\n def maxLevelSum(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def dfs(node, i, level_sums):\n if not node:\n return\n if i == len(level_sums):\n level_sums.append(0)\n level_sums[i] += node.val\n dfs(node.left, i+1, level_sums)\n dfs(node.right, i+1, level_sums)\n\n level_sums = []\n dfs(root, 0, level_sums)\n return level_sums.index(max(level_sums))+1\n\n \n# Time: O(n)\n# Space: O(w)\n# bfs solution\nclass Solution2(object):\n def maxLevelSum(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n result, level, max_total = 0, 1, float(\"-inf\")\n q = collections.deque([root])\n while q:\n total = 0\n for _ in range(len(q)):\n node = q.popleft()\n total += node.val\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if total > max_total:\n result, max_total = level, total\n level += 1\n return result\n"}} diff --git a/cp/cp-10612.jsonl b/cp/cp-10612.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1c1c30818d71162b0a0512fecf2336b7b5df019b --- /dev/null +++ b/cp/cp-10612.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10612", "name": "LeetCode 1162: As Far From Land As Possible"} +{"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: As Far from Land as Possible (Difficulty: Medium)\nTags: Array, Dynamic Programming, Breadth-First Search, Matrix\n\nGiven an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.\nThe distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.\n\nExample 1:\nInput: grid = [[1,0,1],[0,0,0],[1,0,1]]\nOutput: 2\nExplanation: The cell (1, 1) is as far as possible from all the land with distance 2.\n\nExample 2:\nInput: grid = [[1,0,0],[0,0,0],[0,0,0]]\nOutput: 4\nExplanation: The cell (2, 2) is as far as possible from all the land with distance 4.\n\nConstraints:\n- n == grid.length\n- n == grid[i].length\n- 1 <= n <= 100\n- grid[i][j] is 0 or 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m * n)\n\nimport collections\n\n\nclass Solution(object):\n def maxDistance(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n q = collections.deque([(i, j) for i in range(len(grid))\n for j in range(len(grid[0])) if grid[i][j] == 1]) \n if len(q) == len(grid)*len(grid[0]):\n return -1\n level = -1\n while q:\n next_q = collections.deque()\n while q:\n x, y = q.popleft()\n for dx, dy in directions:\n nx, ny = x+dx, y+dy\n if not (0 <= nx < len(grid) and \n 0 <= ny < len(grid[0]) and \n grid[nx][ny] == 0):\n continue\n next_q.append((nx, ny))\n grid[nx][ny] = 1\n q = next_q\n level += 1\n return level\n"}} diff --git a/cp/cp-10613.jsonl b/cp/cp-10613.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9ac94df9d21812ebd527c5cb38ca953acb7260d3 --- /dev/null +++ b/cp/cp-10613.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10613", "name": "LeetCode 1163: Last Substring In Lexicographical Order"} +{"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: Last Substring in Lexicographical Order (Difficulty: Hard)\nTags: Two Pointers, String\n\nGiven a string s, return the last substring of s in lexicographical order.\n\nExample 1:\nInput: s = \"abab\"\nOutput: \"bab\"\nExplanation: The substrings are [\"a\", \"ab\", \"aba\", \"abab\", \"b\", \"ba\", \"bab\"]. The lexicographically maximum substring is \"bab\".\n\nExample 2:\nInput: s = \"leetcode\"\nOutput: \"tcode\"\n\nConstraints:\n- 1 <= s.length <= 4 * 10^5\n- s contains only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def lastSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n left, right, l = 0, 1, 0\n while right+l < len(s):\n if s[left+l] == s[right+l]:\n l += 1\n continue\n if s[left+l] > s[right+l]:\n right += l+1\n else:\n left = max(right, left+l+1)\n right = left+1\n l = 0\n return s[left:]\n\n\n# Time: O(n)\n# Space: O(n)\nimport collections\n\n\nclass Solution2(object):\n def lastSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n count = collections.defaultdict(list)\n for i in range(len(s)):\n count[s[i]].append(i)\n\n max_c = max(count.iterkeys())\n starts = {}\n for i in count[max_c]:\n starts[i] = i+1\n while len(starts)-1 > 0:\n lookup = set()\n next_count = collections.defaultdict(list)\n for start, end in starts.iteritems():\n if end == len(s): # finished\n lookup.add(start)\n continue\n next_count[s[end]].append(start)\t\t\t\t\n if end in starts: # overlapped\n lookup.add(end)\t\t\t\n next_starts = {}\n max_c = max(next_count.iterkeys())\n for start in next_count[max_c]:\n if start not in lookup:\n next_starts[start] = starts[start]+1\n starts = next_starts\n return s[next(starts.iterkeys()):]\n"}} diff --git a/cp/cp-10618.jsonl b/cp/cp-10618.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d33268f34c3c94aceda354878588c1b526b2f7e4 --- /dev/null +++ b/cp/cp-10618.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10618", "name": "LeetCode 1169: Invalid Transactions"} +{"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: Invalid Transactions (Difficulty: Medium)\nTags: Array, Hash Table, String, Sorting\n\nA transaction is possibly invalid if:\nYou are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.\nReturn a list of transactions that are possibly invalid. You may return the answer in any order.\n\nExample 1:\nInput: transactions = [\"alice,20,800,mtv\",\"alice,50,100,beijing\"]\nOutput: [\"alice,20,800,mtv\",\"alice,50,100,beijing\"]\nExplanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.\n\nExample 2:\nInput: transactions = [\"alice,20,800,mtv\",\"alice,50,1200,mtv\"]\nOutput: [\"alice,50,1200,mtv\"]\n\nExample 3:\nInput: transactions = [\"alice,20,800,mtv\",\"bob,50,1200,mtv\"]\nOutput: [\"bob,50,1200,mtv\"]\n\nConstraints:\n- transactions.length <= 1000\n- Each transactions[i] takes the form \"{name},{time},{amount},{city}\"\n- Each {name} and {city} consist of lowercase English letters, and have lengths between 1 and 10.\n- Each {time} consist of digits, and represent an integer between 0 and 1000.\n- Each {amount} consist of digits, and represent an integer between 0 and 2000."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\n\nimport collections\n\n\nclass Solution:\n def invalidTransactions(self, transactions):\n AMOUNT, MINUTES = 1000, 60\n trans = map(lambda x: (x[0], int(x[1]), int(x[2]), x[3]),\n (transaction.split(',') for transaction in transactions))\n trans.sort(key=lambda t: t[1])\n trans_indexes = collections.defaultdict(list)\n for i, t in enumerate(trans):\n trans_indexes[t[0]].append(i)\n result = []\n for name, indexes in trans_indexes.iteritems():\n left, right = 0, 0\n for i, t_index in enumerate(indexes):\n t = trans[t_index]\n if (t[2] > AMOUNT):\n result.append(\"{},{},{},{}\".format(*t))\n continue\n while left+1 < len(indexes) and trans[indexes[left]][1] < t[1]-MINUTES:\n left += 1\n while right+1 < len(indexes) and trans[indexes[right+1]][1] <= t[1]+MINUTES:\n right += 1\n for i in range(left, right+1):\n if trans[indexes[i]][3] != t[3]:\n result.append(\"{},{},{},{}\".format(*t))\n break\n return result\n"}} diff --git a/cp/cp-10619.jsonl b/cp/cp-10619.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cb814871e9e02f17aa240629dc6e1e38c262041e --- /dev/null +++ b/cp/cp-10619.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10619", "name": "LeetCode 1170: Compare Strings By Frequency Of The Smallest Character"} +{"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: Compare Strings by Frequency of the Smallest Character (Difficulty: Medium)\nTags: Array, Hash Table, String, Binary Search, Sorting\n\nLet the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = \"dcce\" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2.\nYou are given an array of strings words and another array of query strings queries. For each query queries[i], count the number of words in words such that f(queries[i]) < f(W) for each W in words.\nReturn an integer array answer, where each answer[i] is the answer to the ith query.\n\nExample 1:\nInput: queries = [\"cbd\"], words = [\"zaaaz\"]\nOutput: [1]\nExplanation: On the first query we have f(\"cbd\") = 1, f(\"zaaaz\") = 3 so f(\"cbd\") < f(\"zaaaz\").\n\nExample 2:\nInput: queries = [\"bbb\",\"cc\"], words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\nOutput: [1,2]\nExplanation: On the first query only f(\"bbb\") < f(\"aaaa\"). On the second query both f(\"aaa\") and f(\"aaaa\") are both > f(\"cc\").\n\nConstraints:\n- 1 <= queries.length <= 2000\n- 1 <= words.length <= 2000\n- 1 <= queries[i].length, words[i].length <= 10\n- queries[i][j], words[i][j] consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((m + n)logn), m is the number of queries, n is the number of words\n# Space: O(n)\n\nimport bisect\n\n\nclass Solution(object):\n def numSmallerByFrequency(self, queries, words):\n \"\"\"\n :type queries: List[str]\n :type words: List[str]\n :rtype: List[int]\n \"\"\"\n words_freq = sorted(word.count(min(word)) for word in words)\n return [len(words)-bisect.bisect_right(words_freq, query.count(min(query))) \\\n for query in queries]\n"}} diff --git a/cp/cp-10620.jsonl b/cp/cp-10620.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5c57bf482a51a9ad1d979e7c329c46b9fd7da253 --- /dev/null +++ b/cp/cp-10620.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10620", "name": "LeetCode 1171: Remove Zero Sum Consecutive Nodes From Linked List"} +{"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: Remove Zero Sum Consecutive Nodes from Linked List (Difficulty: Medium)\nTags: Hash Table, Linked List\n\nGiven the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.\nAfter doing so, return the head of the final linked list.  You may return any such answer.\n(Note that in the examples below, all sequences are serializations of ListNode objects.)\n\nExample 1:\nInput: head = [1,2,-3,3,1]\nOutput: [3,1]\nNote: The answer [1,2,1] would also be accepted.\n\nExample 2:\nInput: head = [1,2,3,-3,4]\nOutput: [1,2,4]\n\nExample 3:\nInput: head = [1,2,3,-3,-2]\nOutput: [1]\n\nConstraints:\n- The given linked list will contain between 1 and 1000 nodes.\n- Each node in the linked list has -1000 <= node.val <= 1000."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def removeZeroSumSublists(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n curr = dummy = ListNode(0)\n dummy.next = head\n prefix = 0\n lookup = collections.OrderedDict()\n while curr:\n prefix += curr.val\n node = lookup.get(prefix, curr)\n while prefix in lookup:\n lookup.popitem()\n lookup[prefix] = node\n node.next = curr.next\n curr = curr.next\n return dummy.next\n"}} diff --git a/cp/cp-10621.jsonl b/cp/cp-10621.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..590eefc3e5e844dc8dd3e51a5fec2be4af1ed952 --- /dev/null +++ b/cp/cp-10621.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10621", "name": "LeetCode 1172: Dinner Plate Stacks"} +{"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: Dinner Plate Stacks (Difficulty: Hard)\nTags: Hash Table, Stack, Design, Heap (Priority Queue)\n\nYou have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity.\nImplement the DinnerPlates class:\n\nExample 1:\nInput\n[\"DinnerPlates\", \"push\", \"push\", \"push\", \"push\", \"push\", \"popAtStack\", \"push\", \"push\", \"popAtStack\", \"popAtStack\", \"pop\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []]\nOutput\n[null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1]\n\nExplanation: \nDinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2\nD.push(1);\nD.push(2);\nD.push(3);\nD.push(4);\nD.push(5); // The stacks are now: 2 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(0); // Returns 2. The stacks are now: 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.push(20); // The stacks are now: 20 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.push(21); // The stacks are now: 20 4 21\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(0); // Returns 20. The stacks are now: 4 21\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(2); // Returns 21. The stacks are now: 4\n 1 3 5\n ﹈ ﹈ ﹈ \nD.pop() // Returns 5. The stacks are now: 4\n 1 3 \n ﹈ ﹈ \nD.pop() // Returns 4. The stacks are now: 1 3 \n ﹈ ﹈ \nD.pop() // Returns 3. The stacks are now: 1 \n ﹈ \nD.pop() // Returns 1. There are no stacks.\nD.pop() // Returns -1. There are still no stacks.\n\nConstraints:\n- 1 <= capacity <= 2 * 10^4\n- 1 <= val <= 2 * 10^4\n- 0 <= index <= 10^5\n- At most 2 * 10^5 calls will be made to push, pop, and popAtStack."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: push: O(logn)\n# pop: O(1), amortized\n# popAtStack: O(logn)\n# Space: O(n * c)\n\nimport heapq\n\n\nclass DinnerPlates(object):\n\n def __init__(self, capacity):\n \"\"\"\n :type capacity: int\n \"\"\"\n self.__stks = []\n self.__c = capacity\n self.__min_heap = []\n\n def push(self, val):\n \"\"\"\n :type val: int\n :rtype: None\n \"\"\"\n if self.__min_heap:\n l = heapq.heappop(self.__min_heap)\n if l < len(self.__stks):\n self.__stks[l].append(val)\n return\n self.__min_heap = [] # nothing is valid in min heap\n if not self.__stks or len(self.__stks[-1]) == self.__c:\n self.__stks.append([])\n self.__stks[-1].append(val)\n\n def pop(self):\n \"\"\"\n :rtype: int\n \"\"\"\n while self.__stks and not self.__stks[-1]:\n self.__stks.pop()\n if not self.__stks:\n return -1\n return self.__stks[-1].pop()\n\n def popAtStack(self, index):\n \"\"\"\n :type index: int\n :rtype: int\n \"\"\"\n if index >= len(self.__stks) or not self.__stks[index]:\n return -1\n heapq.heappush(self.__min_heap, index)\n return self.__stks[index].pop()\n"}} diff --git a/cp/cp-10622.jsonl b/cp/cp-10622.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..95a46434df4957643637ce231755aa2b4d5457a9 --- /dev/null +++ b/cp/cp-10622.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10622", "name": "LeetCode 1175: Prime Arrangements"} +{"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: Prime Arrangements (Difficulty: Easy)\nTags: Math\n\nReturn the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.)\n(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)\nSince the answer may be large, return the answer modulo 10^9 + 7.\n\nExample 1:\nInput: n = 5\nOutput: 12\nExplanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.\n\nExample 2:\nInput: n = 100\nOutput: 682289015\n\nConstraints:\n- 1 <= n <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n/2 + n/3 + ... + n/p) = O(nlog(logn)), see https://mathoverflow.net/questions/4596/on-the-series-1-2-1-3-1-5-1-7-1-11\n# Space: O(n)\n\nclass Solution(object):\n def numPrimeArrangements(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n def count_primes(n):\n if n <= 1:\n return 0\n is_prime = [True]*((n+1)//2)\n cnt = len(is_prime)\n for i in range(3, n+1, 2):\n if i*i > n:\n break\n if not is_prime[i//2]:\n continue\n for j in range(i*i, n+1, 2*i):\n if not is_prime[j//2]:\n continue\n cnt -= 1\n is_prime[j//2] = False\n return cnt\n \n def factorial(n):\n result = 1\n for i in range(2, n+1):\n result = (result*i)%MOD\n return result\n\n MOD = 10**9+7\n cnt = count_primes(n)\n return factorial(cnt) * factorial(n-cnt) % MOD\n"}} diff --git a/cp/cp-10624.jsonl b/cp/cp-10624.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..97bd5b701833832b7ee9888a3896ce7c5fedd4b0 --- /dev/null +++ b/cp/cp-10624.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10624", "name": "LeetCode 1177: Can Make Palindrome From Substring"} +{"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 Make Palindrome from Substring (Difficulty: Medium)\nTags: Array, Hash Table, String, Bit Manipulation, Prefix Sum\n\nYou are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may rearrange the substring s[lefti...righti] for each query and then choose up to ki of them to replace with any lowercase English letter.\nIf the substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false.\nReturn a boolean array answer where answer[i] is the result of the ith query queries[i].\nNote that each letter is counted individually for replacement, so if, for example s[lefti...righti] = \"aaa\", and ki = 2, we can only replace two of the letters. Also, note that no query modifies the initial string s.\nExample :\n\nExample 1:\nInput: s = \"abcda\", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]\nOutput: [true,false,false,true,true]\nExplanation:\nqueries[0]: substring = \"d\", is palidrome.\nqueries[1]: substring = \"bc\", is not palidrome.\nqueries[2]: substring = \"abcd\", is not palidrome after replacing only 1 character.\nqueries[3]: substring = \"abcd\", could be changed to \"abba\" which is palidrome. Also this can be changed to \"baab\" first rearrange it \"bacd\" then replace \"cd\" with \"ab\".\nqueries[4]: substring = \"abcda\", could be changed to \"abcba\" which is palidrome.\n\nExample 2:\nInput: s = \"lyb\", queries = [[0,1,0],[2,2,1]]\nOutput: [false,true]\n\nConstraints:\n- 1 <= s.length, queries.length <= 10^5\n- 0 <= lefti <= righti < s.length\n- 0 <= ki <= s.length\n- s consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n), m is the number of queries, n is the length of s\n# Space: O(n)\n\nimport itertools\n\n\nclass Solution(object):\n def canMakePaliQueries(self, s, queries):\n \"\"\"\n :type s: str\n :type queries: List[List[int]]\n :rtype: List[bool]\n \"\"\"\n CHARSET_SIZE = 26\n curr, count = [0]*CHARSET_SIZE, [[0]*CHARSET_SIZE]\n for c in s:\n curr[ord(c)-ord('a')] += 1\n count.append(curr[:])\n return [sum((b-a)%2 for a, b in itertools.izip(count[left], count[right+1]))//2 <= k\n for left, right, k in queries]\n"}} diff --git a/cp/cp-10625.jsonl b/cp/cp-10625.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9b27f27f5ce4b014014c740cb0da4992d944c274 --- /dev/null +++ b/cp/cp-10625.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10625", "name": "LeetCode 1178: Number Of Valid Words For Each Puzzle"} +{"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 Valid Words for Each Puzzle (Difficulty: Hard)\nTags: Array, Hash Table, String, Bit Manipulation, Trie\n\nExample 1:\nInput: words = [\"aaaa\",\"asas\",\"able\",\"ability\",\"actt\",\"actor\",\"access\"], puzzles = [\"aboveyz\",\"abrodyz\",\"abslute\",\"absoryz\",\"actresz\",\"gaswxyz\"]\nOutput: [1,1,3,2,4,0]\nExplanation: \n1 valid word for \"aboveyz\" : \"aaaa\" \n1 valid word for \"abrodyz\" : \"aaaa\"\n3 valid words for \"abslute\" : \"aaaa\", \"asas\", \"able\"\n2 valid words for \"absoryz\" : \"aaaa\", \"asas\"\n4 valid words for \"actresz\" : \"aaaa\", \"asas\", \"actt\", \"access\"\nThere are no valid words for \"gaswxyz\" cause none of the words in the list contains letter 'g'.\n\nExample 2:\nInput: words = [\"apple\",\"pleas\",\"please\"], puzzles = [\"aelwxyz\",\"aelpxyz\",\"aelpsxy\",\"saelpxy\",\"xaelpsy\"]\nOutput: [0,1,3,2,0]\n\nConstraints:\n- 1 <= words.length <= 10^5\n- 4 <= words[i].length <= 50\n- 1 <= puzzles.length <= 10^4\n- puzzles[i].length == 7\n- words[i] and puzzles[i] consist of lowercase English letters.\n- Each puzzles[i] does not contain repeated characters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n*l + m*L), m is the number of puzzles, L is the length of puzzles\n# , n is the number of words, l is the max length of words\n# Space: O(L!)\n\nclass Solution(object):\n def findNumOfValidWords(self, words, puzzles):\n \"\"\"\n :type words: List[str]\n :type puzzles: List[str]\n :rtype: List[int]\n \"\"\"\n L = 7\n def search(node, puzzle, start, first, met_first):\n result = 0\n if \"_end\" in node and met_first:\n result += node[\"_end\"]\n for i in range(start, len(puzzle)):\n if puzzle[i] not in node:\n continue\n result += search(node[puzzle[i]], puzzle, i+1,\n first, met_first or (puzzle[i] == first))\n return result\n\n _trie = lambda: collections.defaultdict(_trie)\n trie = _trie()\n for word in words:\n count = set(word)\n if len(count) > L:\n continue\n word = sorted(count)\n end = reduce(dict.__getitem__, word, trie)\n end[\"_end\"] = end[\"_end\"]+1 if \"_end\" in end else 1\n result = []\n for puzzle in puzzles:\n first = puzzle[0]\n result.append(search(trie, sorted(puzzle), 0, first, False))\n return result\n\n\n# Time: O(m*2^(L-1) + n*(l+m)), m is the number of puzzles, L is the length of puzzles\n# , n is the number of words, l is the max length of words\n# Space: O(m*2^(L-1))\nimport collections\n\n\nclass Solution2(object):\n def findNumOfValidWords(self, words, puzzles):\n \"\"\"\n :type words: List[str]\n :type puzzles: List[str]\n :rtype: List[int]\n \"\"\"\n L = 7\n lookup = collections.defaultdict(list)\n for i in range(len(puzzles)):\n bits = []\n base = 1 << (ord(puzzles[i][0])-ord('a'))\n for j in range(1, L):\n bits.append(ord(puzzles[i][j])-ord('a'))\n for k in range(2**len(bits)):\n bitset = base\n for j in range(len(bits)):\n if k & (1< destination:\n start, destination = destination, start\n s_to_d = sum(itertools.islice(distance, start, destination))\n d_to_s = sum(itertools.islice(distance, 0, start)) + \\\n sum(itertools.islice(distance, destination, len(distance)))\n return min(s_to_d, d_to_s)\n"}} diff --git a/cp/cp-10631.jsonl b/cp/cp-10631.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..851f63128f9a51826348238b03d54a10fd617ea1 --- /dev/null +++ b/cp/cp-10631.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10631", "name": "LeetCode 1185: Day Of The Week"} +{"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: Day of the Week (Difficulty: Easy)\nTags: Math\n\nGiven a date, return the corresponding day of the week for that date.\nThe input is given as three integers representing the day, month and year respectively.\nReturn the answer as one of the following values {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}.\n\nExample 1:\nInput: day = 31, month = 8, year = 2019\nOutput: \"Saturday\"\n\nExample 2:\nInput: day = 18, month = 7, year = 1999\nOutput: \"Sunday\"\n\nExample 3:\nInput: day = 15, month = 8, year = 1993\nOutput: \"Sunday\"\n\nConstraints:\n- The given dates are valid dates between the years 1971 and 2100."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def dayOfTheWeek(self, day, month, year):\n \"\"\"\n :type day: int\n :type month: int\n :type year: int\n :rtype: str\n \"\"\"\n DAYS = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \\\n \"Thursday\", \"Friday\", \"Saturday\"]\n\n # Zeller Formula\n if month < 3:\n month += 12\n year -= 1\n c, y = divmod(year, 100)\n w = (c//4 - 2*c + y + y//4 + 13*(month+1)//5 + day - 1) % 7\n return DAYS[w]\n"}} diff --git a/cp/cp-10632.jsonl b/cp/cp-10632.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4f8f0079fbd6675869704570cd9125e7c2b2f7cd --- /dev/null +++ b/cp/cp-10632.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10632", "name": "LeetCode 1186: Maximum Subarray Sum With One Deletion"} +{"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 Subarray Sum with One Deletion (Difficulty: Medium)\nTags: Array, Dynamic Programming\n\nGiven an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.\nNote that the subarray needs to be non-empty after deleting one element.\n\nExample 1:\nInput: arr = [1,-2,0,3]\nOutput: 4\nExplanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.\n\nExample 2:\nInput: arr = [1,-2,-2,3]\nOutput: 3\nExplanation: We just choose [3] and it's the maximum sum.\n\nExample 3:\nInput: arr = [-1,-1,-1,-1]\nOutput: -1\nExplanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.\n\nConstraints:\n- 1 <= arr.length <= 10^5\n- -10^4 <= arr[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "class Solution(object):\n def maximumSum(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n result, prev, curr = float(\"-inf\"), float(\"-inf\"), float(\"-inf\")\n for x in arr:\n curr = max(prev, curr+x, x)\n result = max(result, curr)\n prev = max(prev+x, x)\n return result\n"}} diff --git a/cp/cp-10633.jsonl b/cp/cp-10633.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2b20e6daa9d3dc10c4100b0b8a17ed1a596acf51 --- /dev/null +++ b/cp/cp-10633.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10633", "name": "LeetCode 1187: Make Array Strictly Increasing"} +{"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: Make Array Strictly Increasing (Difficulty: Hard)\nTags: Array, Binary Search, Dynamic Programming, Sorting\n\nGiven two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing.\nIn one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j].\nIf there is no way to make arr1 strictly increasing, return -1.\n\nExample 1:\nInput: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]\nOutput: 1\nExplanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7].\n\nExample 2:\nInput: arr1 = [1,5,3,6,7], arr2 = [4,3,1]\nOutput: 2\nExplanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7].\n\nExample 3:\nInput: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]\nOutput: -1\nExplanation: You can't make arr1 strictly increasing.\n\nConstraints:\n- 1 <= arr1.length, arr2.length <= 2000\n- 0 <= arr1[i], arr2[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2 * logn)\n# Space: O(n)\n\nimport collections\nimport bisect\n\n\nclass Solution(object):\n def makeArrayIncreasing(self, arr1, arr2):\n \"\"\"\n :type arr1: List[int]\n :type arr2: List[int]\n :rtype: int\n \"\"\"\n arr2 = sorted(set(arr2))\n dp = {0: -1} # dp[min_cost] = end_with_val\n for val1 in arr1:\n next_dp = collections.defaultdict(lambda: float(\"inf\"))\n for cost, val in dp.iteritems():\n if val < val1:\n next_dp[cost] = min(next_dp[cost], val1)\n k = bisect.bisect_right(arr2, val)\n if k == len(arr2):\n continue\n next_dp[cost+1] = min(next_dp[cost+1], arr2[k])\n dp = next_dp\n if not dp:\n return -1\n return min(dp.iterkeys())\n"}} diff --git a/cp/cp-10635.jsonl b/cp/cp-10635.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e5909b60e3f8c90e59706c2a9c55a56f7ea2eb9c --- /dev/null +++ b/cp/cp-10635.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10635", "name": "LeetCode 1189: Maximum Number Of Balloons"} +{"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 Number of Balloons (Difficulty: Easy)\nTags: Hash Table, String, Counting\n\nGiven a string text, you want to use the characters of text to form as many instances of the word \"balloon\" as possible.\nYou can use each character in text at most once. Return the maximum number of instances that can be formed.\nNote: This question is the same as 2287: Rearrange Characters to Make Target String.\n\nExample 1:\nInput: text = \"nlaebolko\"\nOutput: 1\n\nExample 2:\nInput: text = \"loonbalxballpoon\"\nOutput: 2\n\nExample 3:\nInput: text = \"leetcode\"\nOutput: 0\n\nConstraints:\n- 1 <= text.length <= 10^4\n- text consists of lower case English letters only."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def maxNumberOfBalloons(self, text):\n \"\"\"\n :type text: str\n :rtype: int\n \"\"\"\n TARGET = \"balloon\"\n source_count = collections.Counter(text)\n target_count = collections.Counter(TARGET)\n return min(source_count[c]//target_count[c] for c in target_count.iterkeys())\n"}} diff --git a/cp/cp-10636.jsonl b/cp/cp-10636.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6e5605b875105d2d451d9d922796889e249a3fd5 --- /dev/null +++ b/cp/cp-10636.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10636", "name": "LeetCode 1190: Reverse Substrings Between Each Pair Of Parentheses"} +{"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: Reverse Substrings Between Each Pair of Parentheses (Difficulty: Medium)\nTags: String, Stack\n\nYou are given a string s that consists of lower case English letters and brackets.\nReverse the strings in each pair of matching parentheses, starting from the innermost one.\nYour result should not contain any brackets.\n\nExample 1:\nInput: s = \"(abcd)\"\nOutput: \"dcba\"\n\nExample 2:\nInput: s = \"(u(love)i)\"\nOutput: \"iloveu\"\nExplanation: The substring \"love\" is reversed first, then the whole string is reversed.\n\nExample 3:\nInput: s = \"(ed(et(oc))el)\"\nOutput: \"leetcode\"\nExplanation: First, we reverse the substring \"oc\", then \"etco\", and finally, the whole string.\n\nConstraints:\n- 1 <= s.length <= 2000\n- s only contains lower case English characters and parentheses.\n- It is guaranteed that all parentheses are balanced."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def reverseParentheses(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n stk, lookup = [], {}\n for i, c in enumerate(s):\n if c == '(':\n stk.append(i)\n elif c == ')':\n j = stk.pop()\n lookup[i], lookup[j] = j, i\n result = []\n i, d = 0, 1\n while i < len(s):\n if i in lookup:\n i = lookup[i]\n d *= -1\n else:\n result.append(s[i])\n i += d\n return \"\".join(result)\n\n\n# Time: O(n^2)\n# Space: O(n)\nclass Solution2(object):\n def reverseParentheses(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n stk = [[]]\n for c in s:\n if c == '(':\n stk.append([])\n elif c == ')':\n end = stk.pop()\n end.reverse()\n stk[-1].extend(end)\n else:\n stk[-1].append(c)\n return \"\".join(stk.pop())\n"}} diff --git a/cp/cp-10637.jsonl b/cp/cp-10637.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f1c0ed53616c7d05d48ccdf8f4e060f7e9aa5638 --- /dev/null +++ b/cp/cp-10637.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10637", "name": "LeetCode 1191: K Concatenation Maximum Sum"} +{"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-Concatenation Maximum Sum (Difficulty: Medium)\nTags: Array, Dynamic Programming\n\nGiven an integer array arr and an integer k, modify the array by repeating it k times.\nFor example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].\nReturn the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0.\nAs the answer can be very large, return the answer modulo 109 + 7.\n\nExample 1:\nInput: arr = [1,2], k = 3\nOutput: 9\n\nExample 2:\nInput: arr = [1,-2,1], k = 5\nOutput: 2\n\nExample 3:\nInput: arr = [-1,-2], k = 7\nOutput: 0\n\nConstraints:\n- 1 <= arr.length <= 10^5\n- 1 <= k <= 10^5\n- -10^4 <= arr[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def kConcatenationMaxSum(self, arr, k):\n \"\"\"\n :type arr: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n def max_sub_k_array(arr, k):\n result, curr = float(\"-inf\"), float(\"-inf\")\n for _ in range(k):\n for x in arr:\n curr = max(curr+x, x)\n result = max(result, curr)\n return result\n \n MOD = 10**9+7\n if k == 1:\n return max(max_sub_k_array(arr, 1), 0) % MOD\n return (max(max_sub_k_array(arr, 2), 0) + (k-2)*max(sum(arr), 0)) % MOD\n"}} diff --git a/cp/cp-10638.jsonl b/cp/cp-10638.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9044aa7ed878b77eed58d29ba6da5490158eacab --- /dev/null +++ b/cp/cp-10638.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10638", "name": "LeetCode 1192: Critical Connections In A Network"} +{"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: Critical Connections in a Network (Difficulty: Hard)\nTags: Depth-First Search, Graph, Biconnected Component\n\nThere are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network.\nA critical connection is a connection that, if removed, will make some servers unable to reach some other server.\nReturn all critical connections in the network in any order.\n\nExample 1:\nInput: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]\nOutput: [[1,3]]\nExplanation: [[3,1]] is also accepted.\n\nExample 2:\nInput: n = 2, connections = [[0,1]]\nOutput: [[0,1]]\n\nConstraints:\n- 2 <= n <= 10^5\n- n - 1 <= connections.length <= 10^5\n- 0 <= ai, bi <= n - 1\n- ai != bi\n- There are no repeated connections."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(|V| + |E|)\n# Space: O(|V| + |E|)\n\n# variant of Tarjan's algorithm (https://www.geeksforgeeks.org/bridge-in-a-graph/)\nclass Solution(object):\n def criticalConnections(self, n, connections):\n \"\"\"\n :type n: int\n :type connections: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n def dfs(edges, parent, u, idx, lowlinks, lookup, result):\n if lookup[u]:\n return \n lookup[u] = True\n curr_idx = lowlinks[u] = idx[0]\n idx[0] += 1\n for v in edges[u]:\n if v == parent:\n continue\n dfs(edges, u, v, idx, lowlinks, lookup, result)\n lowlinks[u] = min(lowlinks[u], lowlinks[v])\n if lowlinks[v] > curr_idx:\n # if any lowlink of neighbors is larger than curr_idx\n result.append([u, v])\n \n edges = [[] for _ in range(n)]\n idx, lowlinks, lookup = [0], [0]*n, [False]*n\n result = []\n for u, v in connections:\n edges[u].append(v)\n edges[v].append(u)\n dfs(edges, -1, 0, idx, lowlinks, lookup, result)\n return result\n"}} diff --git a/cp/cp-10639.jsonl b/cp/cp-10639.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6d0c7e7d0beddba26cd7cf49516b1432c6467de1 --- /dev/null +++ b/cp/cp-10639.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10639", "name": "LeetCode 1195: Fizz Buzz Multithreaded"} +{"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: Fizz Buzz Multithreaded (Difficulty: Medium)\nTags: Concurrency\n\nYou have the four functions:\nYou are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads:\nModify the given class to output the series [1, 2, \"fizz\", 4, \"buzz\", ...] where the ith token (1-indexed) of the series is:\nImplement the FizzBuzz class:\n\nExample 1:\nInput: n = 15\nOutput: [1,2,\"fizz\",4,\"buzz\",\"fizz\",7,8,\"fizz\",\"buzz\",11,\"fizz\",13,14,\"fizzbuzz\"]\n\nExample 2:\nInput: n = 5\nOutput: [1,2,\"fizz\",4,\"buzz\"]\n\nConstraints:\n- 1 <= n <= 50"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport threading\n\n\nclass FizzBuzz(object):\n def __init__(self, n):\n self.__n = n\n self.__curr = 0\n self.__cv = threading.Condition()\n\n # printFizz() outputs \"fizz\"\n def fizz(self, printFizz):\n \"\"\"\n :type printFizz: method\n :rtype: void\n \"\"\"\n for i in range(1, self.__n+1):\n with self.__cv:\n while self.__curr % 4 != 0:\n self.__cv.wait()\n self.__curr += 1\n if i % 3 == 0 and i % 5 != 0:\n printFizz()\n self.__cv.notify_all()\n\n # printBuzz() outputs \"buzz\"\n def buzz(self, printBuzz):\n \"\"\"\n :type printBuzz: method\n :rtype: void\n \"\"\"\n for i in range(1, self.__n+1):\n with self.__cv:\n while self.__curr % 4 != 1:\n self.__cv.wait()\n self.__curr += 1\n if i % 3 != 0 and i % 5 == 0:\n printBuzz()\n self.__cv.notify_all()\n\n # printFizzBuzz() outputs \"fizzbuzz\"\n def fizzbuzz(self, printFizzBuzz):\n \"\"\"\n :type printFizzBuzz: method\n :rtype: void\n \"\"\"\n for i in range(1, self.__n+1):\n with self.__cv:\n while self.__curr % 4 != 2:\n self.__cv.wait()\n self.__curr += 1\n if i % 3 == 0 and i % 5 == 0:\n printFizzBuzz()\n self.__cv.notify_all()\n\n # printNumber(x) outputs \"x\", where x is an integer.\n def number(self, printNumber):\n \"\"\"\n :type printNumber: method\n :rtype: void\n \"\"\"\n for i in range(1, self.__n+1):\n with self.__cv:\n while self.__curr % 4 != 3:\n self.__cv.wait()\n self.__curr += 1\n if i % 3 != 0 and i % 5 != 0:\n printNumber(i)\n self.__cv.notify_all()\n"}} diff --git a/cp/cp-10644.jsonl b/cp/cp-10644.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..81695eb406bfaf1be2b0f5c1ba419a311e949de8 --- /dev/null +++ b/cp/cp-10644.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10644", "name": "LeetCode 1200: Minimum Absolute Difference"} +{"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: Minimum Absolute Difference (Difficulty: Easy)\nTags: Array, Sorting\n\nGiven an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.\nReturn a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows\n\nExample 1:\nInput: arr = [4,2,1,3]\nOutput: [[1,2],[2,3],[3,4]]\nExplanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.\n\nExample 2:\nInput: arr = [1,3,6,10,15]\nOutput: [[1,3]]\n\nExample 3:\nInput: arr = [3,8,-10,23,19,-4,-14,27]\nOutput: [[-14,-10],[19,23],[23,27]]\n\nConstraints:\n- 2 <= arr.length <= 10^5\n- -10^6 <= arr[i] <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass Solution(object):\n def minimumAbsDifference(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: List[List[int]]\n \"\"\"\n result = []\n min_diff = float(\"inf\")\n arr.sort()\n for i in range(len(arr)-1):\n diff = arr[i+1]-arr[i]\n if diff < min_diff:\n min_diff = diff\n result = [[arr[i], arr[i+1]]]\n elif diff == min_diff:\n result.append([arr[i], arr[i+1]])\n return result\n"}} diff --git a/cp/cp-10645.jsonl b/cp/cp-10645.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a80465947c760c8d8b139705d0e91bbe3377c10f --- /dev/null +++ b/cp/cp-10645.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10645", "name": "LeetCode 1201: Ugly Number 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: Ugly Number III (Difficulty: Medium)\nTags: Math, Binary Search, Combinatorics, Number Theory\n\nAn ugly number is a positive integer that is divisible by a, b, or c.\nGiven four integers n, a, b, and c, return the nth ugly number.\n\nExample 1:\nInput: n = 3, a = 2, b = 3, c = 5\nOutput: 4\nExplanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.\n\nExample 2:\nInput: n = 4, a = 2, b = 3, c = 4\nOutput: 6\nExplanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6.\n\nExample 3:\nInput: n = 5, a = 2, b = 11, c = 13\nOutput: 10\nExplanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10.\n\nConstraints:\n- 1 <= n, a, b, c <= 10^9\n- 1 <= a * b * c <= 10^18\n- It is guaranteed that the result will be in range [1, 2 * 10^9]."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nclass Solution(object):\n def nthUglyNumber(self, n, a, b, c):\n \"\"\"\n :type n: int\n :type a: int\n :type b: int\n :type c: int\n :rtype: int\n \"\"\"\n def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\n def lcm(x, y):\n return x//gcd(x, y)*y\n\n def count(x, a, b, c, lcm_a_b, lcm_b_c, lcm_c_a, lcm_a_b_c):\n return x//a + x//b + x//c - (x//lcm_a_b + x//lcm_b_c + x//lcm_c_a) + x//lcm_a_b_c\n\n lcm_a_b, lcm_b_c, lcm_c_a = lcm(a, b), lcm(b, c), lcm(c, a)\n lcm_a_b_c = lcm(lcm_a_b, lcm_b_c)\n\n left, right = 1, 2*10**9\n while left <= right:\n mid = left + (right-left)//2\n if count(mid, a, b, c, lcm_a_b, lcm_b_c, lcm_c_a, lcm_a_b_c) >= n:\n right = mid-1\n else:\n left = mid+1\n return left\n"}} diff --git a/cp/cp-10646.jsonl b/cp/cp-10646.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f569a523cb50d12385bacca7fe45ee45b3f53051 --- /dev/null +++ b/cp/cp-10646.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10646", "name": "LeetCode 1202: Smallest String With Swaps"} +{"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: Smallest String With Swaps (Difficulty: Medium)\nTags: Array, Hash Table, String, Depth-First Search, Breadth-First Search, Union Find, Sorting\n\nYou are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.\nYou can swap the characters at any pair of indices in the given pairs any number of times.\nReturn the lexicographically smallest string that s can be changed to after using the swaps.\n\nExample 1:\nInput: s = \"dcab\", pairs = [[0,3],[1,2]]\nOutput: \"bacd\"\nExplaination: \nSwap s[0] and s[3], s = \"bcad\"\nSwap s[1] and s[2], s = \"bacd\"\n\nExample 2:\nInput: s = \"dcab\", pairs = [[0,3],[1,2],[0,2]]\nOutput: \"abcd\"\nExplaination: \nSwap s[0] and s[3], s = \"bcad\"\nSwap s[0] and s[2], s = \"acbd\"\nSwap s[1] and s[2], s = \"abcd\"\n\nExample 3:\nInput: s = \"cba\", pairs = [[0,1],[1,2]]\nOutput: \"abc\"\nExplaination: \nSwap s[0] and s[1], s = \"bca\"\nSwap s[1] and s[2], s = \"bac\"\nSwap s[0] and s[1], s = \"abc\"\n\nConstraints:\n- 1 <= s.length <= 10^5\n- 0 <= pairs.length <= 10^5\n- 0 <= pairs[i][0], pairs[i][1] < s.length\n- s only contains lower case English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport collections\n\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[max(x_root, y_root)] = min(x_root, y_root)\n return True\n\n\nclass Solution(object):\n def smallestStringWithSwaps(self, s, pairs):\n \"\"\"\n :type s: str\n :type pairs: List[List[int]]\n :rtype: str\n \"\"\"\n union_find = UnionFind(len(s))\n for x,y in pairs: \n union_find.union_set(x, y)\n components = collections.defaultdict(list)\n for i in range(len(s)): \n components[union_find.find_set(i)].append(s[i])\n for i in components.iterkeys(): \n components[i].sort(reverse=True)\n result = []\n for i in range(len(s)): \n result.append(components[union_find.find_set(i)].pop())\n return \"\".join(result)\n\n\n# Time: O(nlogn)\n# Space: O(n)\nimport itertools\nclass Solution2(object):\n def smallestStringWithSwaps(self, s, pairs):\n \"\"\"\n :type s: str\n :type pairs: List[List[int]]\n :rtype: str\n \"\"\"\n def dfs(i, adj, lookup, component):\n lookup.add(i)\n component.append(i)\n for j in adj[i]:\n if j in lookup:\n continue\n dfs(j, adj, lookup, component)\n \n adj = collections.defaultdict(list)\n for i, j in pairs:\n adj[i].append(j)\n adj[j].append(i)\n lookup = set()\n result = list(s)\n for i in range(len(s)):\n if i in lookup:\n continue\n component = []\n dfs(i, adj, lookup, component)\n component.sort()\n chars = sorted(result[k] for k in component)\n for comp, char in itertools.izip(component, chars):\n result[comp] = char\n return \"\".join(result)\n"}} diff --git a/cp/cp-10647.jsonl b/cp/cp-10647.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b873a0a975951bfd84a8ec59f8598662706f9b48 --- /dev/null +++ b/cp/cp-10647.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10647", "name": "LeetCode 1203: Sort Items By Groups Respecting Dependencies"} +{"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: Sort Items by Groups Respecting Dependencies (Difficulty: Hard)\nTags: Depth-First Search, Breadth-First Search, Graph, Topological Sort\n\nThere are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to and it's equal to -1 if the i-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.\nReturn a sorted list of the items such that:\nReturn any solution if there is more than one solution and return an empty list if there is no solution.\n\nExample 1:\nInput: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]\nOutput: [6,3,4,1,5,2,0,7]\n\nExample 2:\nInput: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]\nOutput: []\nExplanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.\n\nConstraints:\n- 1 <= m <= n <= 3 * 10^4\n- group.length == beforeItems.length == n\n- -1 <= group[i] <= m - 1\n- 0 <= beforeItems[i].length <= n - 1\n- 0 <= beforeItems[i][j] <= n - 1\n- i != beforeItems[i][j]\n- beforeItems[i] does not contain duplicates elements."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + e)\n# Space: O(n + e)\n\nimport collections\n\n\nclass Topo(object):\n def __init__(self):\n self.__nodes = set()\n self.__in_degree = collections.defaultdict(set)\n self.__out_degree = collections.defaultdict(set)\n \n def add_node(self, node):\n self.__nodes.add(node)\n \n def add_edge(self, src, dst):\n self.add_node(src), self.add_node(dst)\n self.__in_degree[dst].add(src)\n self.__out_degree[src].add(dst)\n \n def sort(self):\n q = collections.deque()\n result = []\n for node in self.__nodes:\n if node not in self.__in_degree:\n q.append(node)\n while q:\n node = q.popleft()\n result.append(node)\n for nei in self.__out_degree[node]:\n self.__in_degree[nei].remove(node)\n if not self.__in_degree[nei]:\n self.__in_degree.pop(nei)\n q.append(nei)\n if len(result) < len(self.__nodes):\n return\n return result\n\n\nclass Solution(object):\n def sortItems(self, n, m, group, beforeItems):\n \"\"\"\n :type n: int\n :type m: int\n :type group: List[int]\n :type beforeItems: List[List[int]]\n :rtype: List[int]\n \"\"\"\n for i in range(n):\n if group[i] == -1:\n group[i] = m\n m += 1 \n global_group = Topo()\n for i in range(m):\n global_group.add_node(i)\n local_groups = collections.defaultdict(Topo)\n for i in range(n):\n local_groups[group[i]].add_node(i)\n for i in range(n):\n for j in beforeItems[i]:\n if group[i] == group[j]:\n local_groups[group[i]].add_edge(j, i)\n else:\n global_group.add_edge(group[j], group[i])\n result = []\n global_order = global_group.sort()\n if global_order is None:\n return []\n for i in global_order:\n local_order = local_groups[i].sort()\n if local_order is None:\n return []\n for x in local_order:\n result.append(x)\n return result\n"}} diff --git a/cp/cp-10648.jsonl b/cp/cp-10648.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..52655d2ab532da7d125217c7aef101cd4dc009a3 --- /dev/null +++ b/cp/cp-10648.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10648", "name": "LeetCode 1206: Design Skiplist"} +{"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 Skiplist (Difficulty: Hard)\nTags: Linked List, Design\n\nDesign a Skiplist without using any built-in libraries.\nA skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists.\nFor example, we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way:\nArtyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons\nYou can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than O(n). It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n).\nSee more about Skiplist: https://en.wikipedia.org/wiki/Skip_list\nImplement the Skiplist class:\nNote that duplicates may exist in the Skiplist, your code needs to handle this situation.\n\nExample 1:\nInput\n[\"Skiplist\", \"add\", \"add\", \"add\", \"search\", \"add\", \"search\", \"erase\", \"erase\", \"search\"]\n[[], [1], [2], [3], [0], [4], [1], [0], [1], [1]]\nOutput\n[null, null, null, null, false, null, true, false, true, false]\n\nExplanation\nSkiplist skiplist = new Skiplist();\nskiplist.add(1);\nskiplist.add(2);\nskiplist.add(3);\nskiplist.search(0); // return False\nskiplist.add(4);\nskiplist.search(1); // return True\nskiplist.erase(0); // return False, 0 is not in skiplist.\nskiplist.erase(1); // return True\nskiplist.search(1); // return False, 1 has already been erased.\n\nConstraints:\n- 0 <= num, target <= 2 * 10^4\n- At most 5 * 10^4 calls will be made to search, add, and erase."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn) on average for each operation\n# Space: O(n)\n\n# see proof in references:\n# 1. https://kunigami.blog/2012/09/25/skip-lists-in-python/\n# 2. https://opendatastructures.org/ods-cpp/4_4_Analysis_Skiplists.html\n# 3. https://brilliant.org/wiki/skip-lists/\nimport random\n\n\nclass SkipNode(object):\n def __init__(self, level=0, num=None):\n self.num = num\n self.nexts = [None]*level\n\n\nclass Skiplist(object):\n P_NUMERATOR, P_DENOMINATOR = 1, 2 # P = 1/4 in redis implementation\n MAX_LEVEL = 32 # enough for 2^32 elements\n\n def __init__(self):\n self.__head = SkipNode()\n self.__len = 0\n\n def search(self, target):\n \"\"\"\n :type target: int\n :rtype: bool\n \"\"\"\n return True if self.__find(target, self.__find_prev_nodes(target)) else False\n \n def add(self, num):\n \"\"\"\n :type num: int\n :rtype: None\n \"\"\"\n node = SkipNode(self.__random_level(), num)\n if len(self.__head.nexts) < len(node.nexts): \n self.__head.nexts.extend([None]*(len(node.nexts)-len(self.__head.nexts)))\n prevs = self.__find_prev_nodes(num)\n for i in range(len(node.nexts)):\n node.nexts[i] = prevs[i].nexts[i]\n prevs[i].nexts[i] = node\n self.__len += 1\n\n def erase(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n prevs = self.__find_prev_nodes(num)\n curr = self.__find(num, prevs)\n if not curr:\n return False\n self.__len -= 1 \n for i in reversed(range(len(curr.nexts))):\n prevs[i].nexts[i] = curr.nexts[i]\n if not self.__head.nexts[i]:\n self.__head.nexts.pop()\n return True\n \n def __find(self, num, prevs):\n if prevs:\n candidate = prevs[0].nexts[0]\n if candidate and candidate.num == num:\n return candidate\n return None\n\n def __find_prev_nodes(self, num):\n prevs = [None]*len(self.__head.nexts)\n curr = self.__head\n for i in reversed(range(len(self.__head.nexts))):\n while curr.nexts[i] and curr.nexts[i].num < num:\n curr = curr.nexts[i]\n prevs[i] = curr\n return prevs\n\n def __random_level(self):\n level = 1\n while random.randint(1, Skiplist.P_DENOMINATOR) <= Skiplist.P_NUMERATOR and \\\n level < Skiplist.MAX_LEVEL:\n level += 1\n return level\n\n def __len__(self):\n return self.__len\n \n def __str__(self):\n result = []\n for i in reversed(range(len(self.__head.nexts))):\n result.append([])\n curr = self.__head.nexts[i]\n while curr:\n result[-1].append(str(curr.num))\n curr = curr.nexts[i]\n return \"\\n\".join(map(lambda x: \"->\".join(x), result))\n"}} diff --git a/cp/cp-10649.jsonl b/cp/cp-10649.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b21c02138952c91f43ac23a37196e798d118e998 --- /dev/null +++ b/cp/cp-10649.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10649", "name": "LeetCode 1207: Unique Number Of Occurrences"} +{"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: Unique Number of Occurrences (Difficulty: Easy)\nTags: Array, Hash Table\n\nGiven an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.\n\nExample 1:\nInput: arr = [1,2,2,1,1,3]\nOutput: true\nExplanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.\n\nExample 2:\nInput: arr = [1,2]\nOutput: false\n\nExample 3:\nInput: arr = [-3,0,1,-3,1,1,1,-3,10,0]\nOutput: true\n\nConstraints:\n- 1 <= arr.length <= 1000\n- -1000 <= arr[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def uniqueOccurrences(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: bool\n \"\"\"\n count = collections.Counter(arr)\n lookup = set()\n for v in count.itervalues():\n if v in lookup:\n return False\n lookup.add(v)\n return True\n\n\n# Time: O(n)\n# Space: O(n)\nclass Solution2(object):\n def uniqueOccurrences(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: bool\n \"\"\"\n count = collections.Counter(arr)\n return len(count) == len(set(count.itervalues()))\n"}} diff --git a/cp/cp-10650.jsonl b/cp/cp-10650.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fcf3bba5049bf8a27a7ff8497a64fa64e9f77de0 --- /dev/null +++ b/cp/cp-10650.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10650", "name": "LeetCode 1208: Get Equal Substrings Within Budget"} +{"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: Get Equal Substrings Within Budget (Difficulty: Medium)\nTags: String, Binary Search, Sliding Window, Prefix Sum\n\nYou are given two strings s and t of the same length and an integer maxCost.\nYou want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters).\nReturn the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0.\n\nExample 1:\nInput: s = \"abcd\", t = \"bcdf\", maxCost = 3\nOutput: 3\nExplanation: \"abc\" of s can change to \"bcd\".\nThat costs 3, so the maximum length is 3.\n\nExample 2:\nInput: s = \"abcd\", t = \"cdef\", maxCost = 3\nOutput: 1\nExplanation: Each character in s costs 2 to change to character in t, so the maximum length is 1.\n\nExample 3:\nInput: s = \"abcd\", t = \"acde\", maxCost = 0\nOutput: 1\nExplanation: You cannot make any change, so the maximum length is 1.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- t.length == s.length\n- 0 <= maxCost <= 10^6\n- s and t consist of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def equalSubstring(self, s, t, maxCost):\n \"\"\"\n :type s: str\n :type t: str\n :type maxCost: int\n :rtype: int\n \"\"\"\n left = 0\n for right in range(len(s)):\n maxCost -= abs(ord(s[right])-ord(t[right]))\n if maxCost < 0:\n maxCost += abs(ord(s[left])-ord(t[left]))\n left += 1\n return (right+1)-left\n"}} diff --git a/cp/cp-10651.jsonl b/cp/cp-10651.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..361afc020ebed7d4498cce495cedae4487e32f40 --- /dev/null +++ b/cp/cp-10651.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10651", "name": "LeetCode 1209: Remove All Adjacent Duplicates In String 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: Remove All Adjacent Duplicates in String II (Difficulty: Medium)\nTags: String, Stack\n\nYou are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.\nWe repeatedly make k duplicate removals on s until we no longer can.\nReturn the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.\n\nExample 1:\nInput: s = \"abcd\", k = 2\nOutput: \"abcd\"\nExplanation: There's nothing to delete.\n\nExample 2:\nInput: s = \"deeedbbcccbdaa\", k = 3\nOutput: \"aa\"\nExplanation: \nFirst delete \"eee\" and \"ccc\", get \"ddbbbdaa\"\nThen delete \"bbb\", get \"dddaa\"\nFinally delete \"ddd\", get \"aa\"\n\nExample 3:\nInput: s = \"pbbcggttciiippooaais\", k = 2\nOutput: \"ps\"\n\nConstraints:\n- 1 <= s.length <= 10^5\n- 2 <= k <= 10^4\n- s only contains lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def removeDuplicates(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n stk = [['^', 0]]\n for c in s:\n if stk[-1][0] == c:\n stk[-1][1] += 1\n if stk[-1][1] == k:\n stk.pop()\n else:\n stk.append([c, 1])\n return \"\".join(c*k for c, k in stk)\n"}} diff --git a/cp/cp-10652.jsonl b/cp/cp-10652.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0fe14dbbd443aee62d9fc32ad98d64d955e4c666 --- /dev/null +++ b/cp/cp-10652.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10652", "name": "LeetCode 1210: Minimum Moves To Reach Target With Rotations"} +{"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: Minimum Moves to Reach Target with Rotations (Difficulty: Hard)\nTags: Array, Breadth-First Search, Matrix\n\nIn an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1).\nIn one move the snake can:\nReturn the minimum number of moves to reach the target.\nIf there is no way to reach the target, return -1.\n\nExample 1:\nInput: grid = [[0,0,0,0,0,1],\n [1,1,0,0,1,0],\n  [0,0,0,0,1,1],\n  [0,0,1,0,1,0],\n  [0,1,1,0,0,0],\n  [0,1,1,0,0,0]]\nOutput: 11\nExplanation:\nOne possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].\n\nExample 2:\nInput: grid = [[0,0,1,1,1,1],\n  [0,0,0,0,1,1],\n  [1,1,0,0,0,1],\n  [1,1,1,0,0,1],\n  [1,1,1,0,0,1],\n  [1,1,1,0,0,0]]\nOutput: 9\n\nConstraints:\n- 2 <= n <= 100\n- 0 <= grid[i][j] <= 1\n- It is guaranteed that the snake starts at empty cells."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def minimumMoves(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n level, q, lookup = 0, [(0, 0, False)], set()\n while q:\n next_q = []\n for r, c, is_vertical in q:\n if (r, c, is_vertical) in lookup:\n continue\n if (r, c, is_vertical) == (len(grid)-1, len(grid)-2, False):\n return level\n lookup.add((r, c, is_vertical))\n if not is_vertical:\n if c+2 != len(grid[0]) and grid[r][c+2] == 0:\n next_q.append((r, c+1, is_vertical))\n if r+1 != len(grid) and grid[r+1][c] == 0 and grid[r+1][c+1] == 0:\n next_q.append((r+1, c, is_vertical))\n next_q.append((r, c, not is_vertical))\n else:\n if r+2 != len(grid) and grid[r+2][c] == 0:\n next_q.append((r+1, c, is_vertical))\n if c+1 != len(grid) and grid[r][c+1] == 0 and grid[r+1][c+1] == 0:\n next_q.append((r, c+1, is_vertical))\n next_q.append((r, c, not is_vertical))\n q = next_q\n level += 1\n return -1\n"}} diff --git a/cp/cp-10658.jsonl b/cp/cp-10658.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f388ce677e0d9bd6a4611aad78cc89c3352b2dfa --- /dev/null +++ b/cp/cp-10658.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10658", "name": "LeetCode 1218: Longest Arithmetic Subsequence Of Given Difference"} +{"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 Arithmetic Subsequence of Given Difference (Difficulty: Medium)\nTags: Array, Hash Table, Dynamic Programming\n\nGiven an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.\nA subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements.\n\nExample 1:\nInput: arr = [1,2,3,4], difference = 1\nOutput: 4\nExplanation: The longest arithmetic subsequence is [1,2,3,4].\n\nExample 2:\nInput: arr = [1,3,5,7], difference = 1\nOutput: 1\nExplanation: The longest arithmetic subsequence is any single element.\n\nExample 3:\nInput: arr = [1,5,7,8,5,3,4,2,1], difference = -2\nOutput: 4\nExplanation: The longest arithmetic subsequence is [7,5,3,1].\n\nConstraints:\n- 1 <= arr.length <= 10^5\n- -10^4 <= arr[i], difference <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def longestSubsequence(self, arr, difference):\n \"\"\"\n :type arr: List[int]\n :type difference: int\n :rtype: int\n \"\"\"\n result = 1\n lookup = collections.defaultdict(int)\n for i in range(len(arr)):\n lookup[arr[i]] = lookup[arr[i]-difference] + 1\n result = max(result, lookup[arr[i]])\n return result\n"}} diff --git a/cp/cp-10659.jsonl b/cp/cp-10659.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..776d9d51720341765be7431f236b7d66edbb4894 --- /dev/null +++ b/cp/cp-10659.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10659", "name": "LeetCode 1219: Path With Maximum Gold"} +{"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: Path with Maximum Gold (Difficulty: Medium)\nTags: Array, Backtracking, Matrix\n\nIn a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.\nReturn the maximum amount of gold you can collect under the conditions:\n\nExample 1:\nInput: grid = [[0,6,0],[5,8,7],[0,9,0]]\nOutput: 24\nExplanation:\n[[0,6,0],\n [5,8,7],\n [0,9,0]]\nPath to get the maximum gold, 9 -> 8 -> 7.\n\nExample 2:\nInput: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]\nOutput: 28\nExplanation:\n[[1,0,7],\n [2,0,6],\n [3,4,5],\n [0,3,0],\n [9,0,20]]\nPath to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 15\n- 0 <= grid[i][j] <= 100\n- There are at most 25 cells containing gold."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m^2 * n^2)\n# Space: O(m * n)\n\nclass Solution(object):\n def getMaximumGold(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n def backtracking(grid, i, j):\n result = 0\n grid[i][j] *= -1\n for dx, dy in directions:\n ni, nj = i+dx, j+dy\n if not (0 <= ni < len(grid) and\n 0 <= nj < len(grid[0]) and\n grid[ni][nj] > 0):\n continue\n result = max(result, backtracking(grid, ni, nj))\n grid[i][j] *= -1\n return grid[i][j] + result\n\n result = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j]:\n result = max(result, backtracking(grid, i, j))\n return result\n"}} diff --git a/cp/cp-10660.jsonl b/cp/cp-10660.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..afbe0ec59ac3a9a7edce8f35867e896ed548be1e --- /dev/null +++ b/cp/cp-10660.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10660", "name": "LeetCode 1220: Count Vowels Permutation"} +{"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: Count Vowels Permutation (Difficulty: Hard)\nTags: Dynamic Programming\n\nGiven an integer n, your task is to count how many strings of length n can be formed under the following rules:\nSince the answer may be too large, return it modulo 10^9 + 7.\n\nExample 1:\nInput: n = 1\nOutput: 5\nExplanation: All possible strings are: \"a\", \"e\", \"i\" , \"o\" and \"u\".\n\nExample 2:\nInput: n = 2\nOutput: 10\nExplanation: All possible strings are: \"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\" and \"ua\".\n\nExample 3:\nInput: n = 5\nOutput: 68\n\nConstraints:\n- 1 <= n <= 2 * 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def countVowelPermutation(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n def matrix_expo(A, K):\n result = [[int(i==j) for j in range(len(A))] \\\n for i in range(len(A))]\n while K:\n if K % 2:\n result = matrix_mult(result, A)\n A = matrix_mult(A, A)\n K /= 2\n return result\n\n def matrix_mult(A, B):\n ZB = zip(*B)\n return [[sum(a*b for a, b in itertools.izip(row, col)) % MOD \\\n for col in ZB] for row in A]\n \n MOD = 10**9 + 7\n T = [[0, 1, 1, 0, 1],\n [1, 0, 1, 0, 0],\n [0, 1, 0, 1, 0],\n [0, 0, 1, 0, 0],\n [0, 0, 1, 1, 0]]\n return sum(map(sum, matrix_expo(T, n-1))) % MOD\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def countVowelPermutation(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n MOD = 10**9 + 7\n a, e, i, o, u = 1, 1, 1, 1, 1\n for _ in range(1, n):\n a, e, i, o, u = (e+i+u) % MOD, (a+i) % MOD, (e+o) % MOD, i, (i+o) % MOD\n return (a+e+i+o+u) % MOD\n"}} diff --git a/cp/cp-10661.jsonl b/cp/cp-10661.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..24e6160735df35a2df81e81ff12332baa089ce75 --- /dev/null +++ b/cp/cp-10661.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10661", "name": "LeetCode 1221: Split A String In Balanced Strings"} +{"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 a String in Balanced Strings (Difficulty: Easy)\nTags: String, Greedy, Counting\n\nBalanced strings are those that have an equal quantity of 'L' and 'R' characters.\nGiven a balanced string s, split it into some number of substrings such that:\nReturn the maximum number of balanced strings you can obtain.\n\nExample 1:\nInput: s = \"RLRRLLRLRL\"\nOutput: 4\nExplanation: s can be split into \"RL\", \"RRLL\", \"RL\", \"RL\", each substring contains same number of 'L' and 'R'.\n\nExample 2:\nInput: s = \"RLRRRLLRLL\"\nOutput: 2\nExplanation: s can be split into \"RL\", \"RRRLLRLL\", each substring contains same number of 'L' and 'R'.\nNote that s cannot be split into \"RL\", \"RR\", \"RL\", \"LR\", \"LL\", because the 2nd and 5th substrings are not balanced.\n\nExample 3:\nInput: s = \"LLLLRRRR\"\nOutput: 1\nExplanation: s can be split into \"LLLLRRRR\".\n\nConstraints:\n- 2 <= s.length <= 1000\n- s[i] is either 'L' or 'R'.\n- s is a balanced string."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def balancedStringSplit(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result, count = 0, 0 \n for c in s:\n count += 1 if c == 'L' else -1 \n if count == 0:\n result += 1\n return result\n"}} diff --git a/cp/cp-10662.jsonl b/cp/cp-10662.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..134257933aeeca47d5a28fd5e5e692f5d8171f58 --- /dev/null +++ b/cp/cp-10662.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10662", "name": "LeetCode 1222: Queens That Can Attack The King"} +{"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: Queens That Can Attack the King (Difficulty: Medium)\nTags: Array, Matrix, Simulation\n\nOn a 0-indexed 8 x 8 chessboard, there can be multiple black queens and one white king.\nYou are given a 2D integer array queens where queens[i] = [xQueeni, yQueeni] represents the position of the ith black queen on the chessboard. You are also given an integer array king of length 2 where king = [xKing, yKing] represents the position of the white king.\nReturn the coordinates of the black queens that can directly attack the king. You may return the answer in any order.\n\nExample 1:\nInput: queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]\nOutput: [[0,1],[1,0],[3,3]]\nExplanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).\n\nExample 2:\nInput: queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]\nOutput: [[2,2],[3,4],[4,4]]\nExplanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).\n\nConstraints:\n- 1 <= queens.length < 64\n- queens[i].length == king.length == 2\n- 0 <= xQueeni, yQueeni, xKing, yKing < 8\n- All the given positions are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def queensAttacktheKing(self, queens, king):\n \"\"\"\n :type queens: List[List[int]]\n :type king: List[int]\n :rtype: List[List[int]]\n \"\"\"\n dirctions = [(-1, 0), (0, 1), (1, 0), (0, -1),\n (-1, 1), (1, 1), (1, -1), (-1, -1)]\n result = []\n lookup = {(i, j) for i, j in queens}\n for dx, dy in dirctions:\n for i in range(1, 8):\n x, y = king[0] + dx*i, king[1] + dy*i\n if (x, y) in lookup:\n result.append([x, y])\n break\n return result\n"}} diff --git a/cp/cp-10663.jsonl b/cp/cp-10663.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..95c3125ebc74486e48e97e5f95c3503c6b4fdf0e --- /dev/null +++ b/cp/cp-10663.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10663", "name": "LeetCode 1223: Dice Roll Simulation"} +{"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: Dice Roll Simulation (Difficulty: Hard)\nTags: Array, Dynamic Programming\n\nA die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.\nGiven an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls. Since the answer may be too large, return it modulo 109 + 7.\nTwo sequences are considered different if at least one element differs from each other.\n\nExample 1:\nInput: n = 2, rollMax = [1,1,2,2,2,3]\nOutput: 34\nExplanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.\n\nExample 2:\nInput: n = 2, rollMax = [1,1,1,1,1,1]\nOutput: 30\n\nExample 3:\nInput: n = 3, rollMax = [1,1,1,2,2,3]\nOutput: 181\n\nConstraints:\n- 1 <= n <= 5000\n- rollMax.length == 6\n- 1 <= rollMax[i] <= 15"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n), m is the max of rollMax\n# Space: O(m)\n\nclass Solution(object):\n def dieSimulator(self, n, rollMax):\n \"\"\"\n :type n: int\n :type rollMax: List[int]\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n def sum_mod(array):\n return reduce(lambda x, y: (x+y)%MOD, array)\n\n dp = [[1] + [0]*(rollMax[i]-1) for i in range(6)] # 0-indexed\n for _ in range(n-1):\n new_dp = [[0]*rollMax[i] for i in range(6)]\n for i in range(6):\n for k in range(rollMax[i]):\n for j in range(6):\n if i == j:\n if k < rollMax[i]-1: # 0-indexed\n new_dp[j][k+1] = (new_dp[j][k+1]+dp[i][k])%MOD\n else:\n new_dp[j][0] = (new_dp[j][0]+dp[i][k])%MOD\n dp = new_dp\n return sum_mod(sum_mod(row) for row in dp)\n"}} diff --git a/cp/cp-10664.jsonl b/cp/cp-10664.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dfbe4e11867c6ce3347c51c65b33f5bd928e63a5 --- /dev/null +++ b/cp/cp-10664.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10664", "name": "LeetCode 1224: Maximum Equal Frequency"} +{"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 Equal Frequency (Difficulty: Hard)\nTags: Array, Hash Table\n\nGiven an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.\nIf after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).\n\nExample 1:\nInput: nums = [2,2,1,1,5,3,3,5]\nOutput: 7\nExplanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.\n\nExample 2:\nInput: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]\nOutput: 13\n\nConstraints:\n- 2 <= nums.length <= 10^5\n- 1 <= nums[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def maxEqualFreq(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result = 0\n count = collections.Counter()\n freq = [0 for _ in range(len(nums)+1)]\n for i, n in enumerate(nums, 1):\n freq[count[n]] -= 1\n freq[count[n]+1] += 1\n count[n] += 1\n c = count[n]\n if freq[c]*c == i and i < len(nums):\n result = i+1\n remain = i-freq[c]*c\n if freq[remain] == 1 and remain in [1, c+1]:\n result = i\n return result\n"}} diff --git a/cp/cp-10665.jsonl b/cp/cp-10665.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9cb52ba79b0b1cb5daa61ad3438c5a82c536a5c3 --- /dev/null +++ b/cp/cp-10665.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10665", "name": "LeetCode 1226: The Dining Philosophers"} +{"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: The Dining Philosophers (Difficulty: Medium)\nTags: Concurrency\n\nFive silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers.\nEach philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when they have both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After an individual philosopher finishes eating, they need to put down both forks so that the forks become available to others. A philosopher can take the fork on their right or the one on their left as they become available, but cannot start eating before getting both forks.\nEating is not limited by the remaining amounts of spaghetti or stomach space; an infinite supply and an infinite demand are assumed.\nDesign a discipline of behaviour (a concurrent algorithm) such that no philosopher will starve; i.e., each can forever continue to alternate between eating and thinking, assuming that no philosopher can know when others may want to eat or think.\nThe problem statement and the image above are taken from wikipedia.org\nThe philosophers' ids are numbered from 0 to 4 in a clockwise order. Implement the function void wantsToEat(philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork) where:\nFive threads, each representing a philosopher, will simultaneously use one object of your class to simulate the process. The function may be called for the same philosopher more than once, even before the last call ends.\n\nExample 1:\nInput: n = 1\nOutput: [[4,2,1],[4,1,1],[0,1,1],[2,2,1],[2,1,1],[2,0,3],[2,1,2],[2,2,2],[4,0,3],[4,1,2],[0,2,1],[4,2,2],[3,2,1],[3,1,1],[0,0,3],[0,1,2],[0,2,2],[1,2,1],[1,1,1],[3,0,3],[3,1,2],[3,2,2],[1,0,3],[1,1,2],[1,2,2]]\nExplanation:\nn is the number of times each philosopher will call the function.\nThe output array describes the calls you made to the functions controlling the forks and the eat function, its format is:\noutput[i] = [a, b, c] (three integers)\n- a is the id of a philosopher.\n- b specifies the fork: {1 : left, 2 : right}.\n- c specifies the operation: {1 : pick, 2 : put, 3 : eat}.\n\nConstraints:\n- 1 <= n <= 60"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport threading\n\n\nclass DiningPhilosophers(object):\n def __init__(self):\n self._l = [threading.Lock() for _ in range(5)]\n\n # call the functions directly to execute, for example, eat()\n def wantsToEat(self, philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork):\n \"\"\"\n :type philosopher: int\n :type pickLeftFork: method\n :type pickRightFork: method\n :type eat: method\n :type putLeftFork: method\n :type putRightFork: method\n :rtype: void\n \"\"\"\n left, right = philosopher, (philosopher+4)%5\n first, second = left, right\n if philosopher%2 == 0:\n first, second = left, right\n else:\n first, second = right, left\n\n with self._l[first]:\n with self._l[second]:\n pickLeftFork()\n pickRightFork()\n eat()\n putLeftFork()\n putRightFork()\n"}} diff --git a/cp/cp-10666.jsonl b/cp/cp-10666.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fec3a67aded688f7c18aed24035c09d0bf621b11 --- /dev/null +++ b/cp/cp-10666.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10666", "name": "LeetCode 1227: Airplane Seat Assignment Probability"} +{"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: Airplane Seat Assignment Probability (Difficulty: Medium)\nTags: Math, Dynamic Programming, Brainteaser, Probability and Statistics\n\nn passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:\nReturn the probability that the nth person gets his own seat.\n\nExample 1:\nInput: n = 1\nOutput: 1.00000\nExplanation: The first person can only get the first seat.\n\nExample 2:\nInput: n = 2\nOutput: 0.50000\nExplanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).\n\nConstraints:\n- 1 <= n <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def nthPersonGetsNthSeat(self, n):\n \"\"\"\n :type n: int\n :rtype: float\n \"\"\"\n # p(k) = 1 * (prob that 1th passenger takes his own seat) +\n # 0 * (prob that 1th passenger takes kth one's seat) +\n # 1 * (prob that 1th passenger takes the others' seat) * \n # (prob that the first k-1 passengers get a seat\n # which is not kth one's seat)\n # = 1/k + p(k-1)*(k-2)/k\n #\n # p(1) = 1\n # p(2) = 1/2 + p(1) * (2-2)/2 = 1/2\n # p(3) = 1/3 + p(2) * (3-2)/3 = 1/3 + 1/2 * (3-2)/3 = 1/2\n # ...\n # p(n) = 1/n + 1/2 * (n-2)/n = (2+n-2)/(2n) = 1/2\n return 0.5 if n != 1 else 1.0\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def nthPersonGetsNthSeat(self, n):\n \"\"\"\n :type n: int\n :rtype: float\n \"\"\"\n dp = [0.0]*2\n dp[0] = 1.0 # zero-indexed\n for i in range(2, n+1):\n dp[(i-1)%2] = 1.0/i+dp[(i-2)%2]*(i-2)/i\n return dp[(n-1)%2]\n"}} diff --git a/cp/cp-10671.jsonl b/cp/cp-10671.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f4e58f6c970e1ce2f065c2c0f0782323267c16ca --- /dev/null +++ b/cp/cp-10671.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10671", "name": "LeetCode 1232: Check If It Is A Straight Line"} +{"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: Check If It Is a Straight Line (Difficulty: Easy)\nTags: Array, Math, Geometry\n\nYou are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.\n\nExample 1:\nInput: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]\nOutput: true\n\nExample 2:\nInput: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]\nOutput: false\n\nConstraints:\n- 2 <= coordinates.length <= 1000\n- coordinates[i].length == 2\n- -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4\n- coordinates contains no duplicate point."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def checkStraightLine(self, coordinates):\n \"\"\"\n :type coordinates: List[List[int]]\n :rtype: bool\n \"\"\"\n i, j = coordinates[:2]\n return all(i[0] * j[1] - j[0] * i[1] +\n j[0] * k[1] - k[0] * j[1] +\n k[0] * i[1] - i[0] * k[1] == 0\n for k in coordinates)\n"}} diff --git a/cp/cp-10672.jsonl b/cp/cp-10672.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4d5a671a1f826d045681e7265d744694ba10c7a5 --- /dev/null +++ b/cp/cp-10672.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10672", "name": "LeetCode 1233: Remove Sub Folders From The Filesystem"} +{"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: Remove Sub-Folders from the Filesystem (Difficulty: Medium)\nTags: Array, String, Depth-First Search, Trie\n\nGiven a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order.\nIf a folder[i] is located within another folder[j], it is called a sub-folder of it. A sub-folder of folder[j] must start with folder[j], followed by a \"/\". For example, \"/a/b\" is a sub-folder of \"/a\", but \"/b\" is not a sub-folder of \"/a/b/c\".\nThe format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters.\n\nExample 1:\nInput: folder = [\"/a\",\"/a/b\",\"/c/d\",\"/c/d/e\",\"/c/f\"]\nOutput: [\"/a\",\"/c/d\",\"/c/f\"]\nExplanation: Folders \"/a/b\" is a subfolder of \"/a\" and \"/c/d/e\" is inside of folder \"/c/d\" in our filesystem.\n\nExample 2:\nInput: folder = [\"/a\",\"/a/b/c\",\"/a/b/d\"]\nOutput: [\"/a\"]\nExplanation: Folders \"/a/b/c\" and \"/a/b/d\" will be removed because they are subfolders of \"/a\".\n\nExample 3:\nInput: folder = [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]\nOutput: [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]\n\nConstraints:\n- 1 <= folder.length <= 4 * 10^4\n- 2 <= folder[i].length <= 100\n- folder[i] contains only lowercase letters and '/'.\n- folder[i] always starts with the character '/'.\n- Each folder name is unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n), n is the total sum of the lengths of folder names\n# Space: O(t), t is the number of nodes in trie\n\nimport collections\nimport itertools\n\n\nclass Solution(object):\n def removeSubfolders(self, folder):\n \"\"\"\n :type folder: List[str]\n :rtype: List[str]\n \"\"\"\n def dfs(curr, path, result):\n if \"_end\" in curr:\n result.append(\"/\" + \"/\".join(path))\n return\n for c in curr:\n if c == \"_end\":\n continue\n path.append(c)\n dfs(curr[c], path, result)\n path.pop()\n\n _trie = lambda: collections.defaultdict(_trie)\n trie = _trie()\n for f in folder:\n f_list = f.split(\"/\")\n reduce(dict.__getitem__,\n itertools.islice(f_list, 1, len(f_list)),\n trie).setdefault(\"_end\")\n result = []\n dfs(trie, [], result)\n return result\n \n"}} diff --git a/cp/cp-10673.jsonl b/cp/cp-10673.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9ef74321823fb4019b0867b27d53003961de3568 --- /dev/null +++ b/cp/cp-10673.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10673", "name": "LeetCode 1234: Replace The Substring For Balanced 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: Replace the Substring for Balanced String (Difficulty: Medium)\nTags: String, Sliding Window\n\nYou are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'.\nA string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string.\nReturn the minimum length of the substring that can be replaced with any other string of the same length to make s balanced. If s is already balanced, return 0.\n\nExample 1:\nInput: s = \"QWER\"\nOutput: 0\nExplanation: s is already balanced.\n\nExample 2:\nInput: s = \"QQWE\"\nOutput: 1\nExplanation: We need to replace a 'Q' to 'R', so that \"RQWE\" (or \"QRWE\") is balanced.\n\nExample 3:\nInput: s = \"QQQW\"\nOutput: 2\nExplanation: We can replace the first \"QQ\" to \"ER\".\n\nConstraints:\n- n == s.length\n- 4 <= n <= 10^5\n- n is a multiple of 4.\n- s contains only 'Q', 'W', 'E', 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 balancedString(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n count = collections.Counter(s)\n result = len(s) \n left = 0\n for right in range(len(s)):\n count[s[right]] -= 1\n while left < len(s) and \\\n all(v <= len(s)//4 for v in count.itervalues()):\n result = min(result, right-left+1)\n count[s[left]] += 1\n left += 1\n return result\n"}} diff --git a/cp/cp-10674.jsonl b/cp/cp-10674.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b09899510dc5eb3366607cf215f0330fe4e3a3e8 --- /dev/null +++ b/cp/cp-10674.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10674", "name": "LeetCode 1235: Maximum Profit In Job Scheduling"} +{"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 Profit in Job Scheduling (Difficulty: Hard)\nTags: Array, Binary Search, Dynamic Programming, Sorting\n\nWe have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].\nYou're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.\nIf you choose a job that ends at time X you will be able to start another job that starts at time X.\n\nExample 1:\nInput: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]\nOutput: 120\nExplanation: The subset chosen is the first and fourth job. \nTime range [1-3]+[3-6] , we get profit of 120 = 50 + 70.\n\nExample 2:\nInput: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]\nOutput: 150\nExplanation: The subset chosen is the first, fourth and fifth job. \nProfit obtained 150 = 20 + 70 + 60.\n\nExample 3:\nInput: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]\nOutput: 6\n\nConstraints:\n- 1 <= startTime.length == endTime.length == profit.length <= 5 * 10^4\n- 1 <= startTime[i] < endTime[i] <= 10^9\n- 1 <= profit[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport itertools\nimport bisect\n\n\nclass Solution(object):\n def jobScheduling(self, startTime, endTime, profit):\n \"\"\"\n :type startTime: List[int]\n :type endTime: List[int]\n :type profit: List[int]\n :rtype: int\n \"\"\"\n jobs = sorted(itertools.izip(endTime, startTime, profit))\n dp = [(0, 0)]\n for e, s, p in jobs:\n i = bisect.bisect_right(dp, (s+1, 0))-1\n if dp[i][1]+p > dp[-1][1]:\n dp.append((e, dp[i][1]+p))\n return dp[-1][1]\n\n\n# Time: O(nlogn)\n# Space: O(n)\nimport heapq\nclass Solution(object):\n def jobScheduling(self, startTime, endTime, profit):\n \"\"\"\n :type startTime: List[int]\n :type endTime: List[int]\n :type profit: List[int]\n :rtype: int\n \"\"\"\n min_heap = zip(startTime, endTime, profit)\n heapq.heapify(min_heap)\n result = 0\n while min_heap:\n s, e, p = heapq.heappop(min_heap)\n if s < e:\n heapq.heappush(min_heap, (e, s, result+p))\n else:\n result = max(result, p)\n return result\n"}} diff --git a/cp/cp-10676.jsonl b/cp/cp-10676.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a01fa9e2111155ff9623a98d68f12690ad578848 --- /dev/null +++ b/cp/cp-10676.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10676", "name": "LeetCode 1237: Find Positive Integer Solution For A Given 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: Find Positive Integer Solution for a Given Equation (Difficulty: Medium)\nTags: Math, Two Pointers, Binary Search, Interactive\n\nGiven a callable function f(x, y) with a hidden formula and a value z, reverse engineer the formula and return all positive integer pairs x and y where f(x,y) == z. You may return the pairs in any order.\nWhile the exact formula is hidden, the function is monotonically increasing, i.e.:\nThe function interface is defined like this:\nWe will judge your solution as follows:\n\nExample 1:\ninterface CustomFunction {\npublic:\n // Returns some positive integer f(x, y) for two positive integers x and y based on a formula.\n int f(int x, int y);\n};\n\nExample 2:\nInput: function_id = 1, z = 5\nOutput: [[1,4],[2,3],[3,2],[4,1]]\nExplanation: The hidden formula for function_id = 1 is f(x, y) = x + y.\nThe following positive integer values of x and y make f(x, y) equal to 5:\nx=1, y=4 -> f(1, 4) = 1 + 4 = 5.\nx=2, y=3 -> f(2, 3) = 2 + 3 = 5.\nx=3, y=2 -> f(3, 2) = 3 + 2 = 5.\nx=4, y=1 -> f(4, 1) = 4 + 1 = 5.\n\nExample 3:\nInput: function_id = 2, z = 5\nOutput: [[1,5],[5,1]]\nExplanation: The hidden formula for function_id = 2 is f(x, y) = x * y.\nThe following positive integer values of x and y make f(x, y) equal to 5:\nx=1, y=5 -> f(1, 5) = 1 * 5 = 5.\nx=5, y=1 -> f(5, 1) = 5 * 1 = 5.\n\nConstraints:\n- 1 <= function_id <= 9\n- 1 <= z <= 100\n- It is guaranteed that the solutions of f(x, y) == z will be in the range 1 <= x, y <= 1000.\n- It is also guaranteed that f(x, y) will fit in 32 bit signed integer if 1 <= x, y <= 1000."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n\"\"\"\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)\n def f(self, x, y):\n \n\"\"\"\nclass Solution(object):\n def findSolution(self, customfunction, z):\n \"\"\"\n :type num: int\n :type z: int\n :rtype: List[List[int]]\n \"\"\"\n result = []\n x, y = 1, 1\n while customfunction.f(x, y) < z:\n y += 1\n while y > 0:\n while y > 0 and customfunction.f(x, y) > z:\n y -= 1\n if y > 0 and customfunction.f(x, y) == z:\n result.append([x, y])\n x += 1\n return result\n"}} diff --git a/cp/cp-10678.jsonl b/cp/cp-10678.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b2c0cfceff030fc8660e6a76a4a4f43accc4454d --- /dev/null +++ b/cp/cp-10678.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10678", "name": "LeetCode 1239: Maximum Length Of A Concatenated String With Unique Characters"} +{"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 a Concatenated String with Unique Characters (Difficulty: Medium)\nTags: Array, String, Backtracking, Bit Manipulation\n\nYou are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.\nReturn the maximum possible length of s.\nA subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.\n\nExample 1:\nInput: arr = [\"un\",\"iq\",\"ue\"]\nOutput: 4\nExplanation: All the valid concatenations are:\n- \"\"\n- \"un\"\n- \"iq\"\n- \"ue\"\n- \"uniq\" (\"un\" + \"iq\")\n- \"ique\" (\"iq\" + \"ue\")\nMaximum length is 4.\n\nExample 2:\nInput: arr = [\"cha\",\"r\",\"act\",\"ers\"]\nOutput: 6\nExplanation: Possible longest valid concatenations are \"chaers\" (\"cha\" + \"ers\") and \"acters\" (\"act\" + \"ers\").\n\nExample 3:\nInput: arr = [\"abcdefghijklmnopqrstuvwxyz\"]\nOutput: 26\nExplanation: The only string in arr has all 26 characters.\n\nConstraints:\n- 1 <= arr.length <= 16\n- 1 <= arr[i].length <= 26\n- arr[i] contains only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n) ~ O(2^n)\n# Space: O(1) ~ O(2^n)\n\npower = [1]\nlog2 = {1:0}\nfor i in range(1, 26):\n power.append(power[-1]<<1)\n log2[power[i]] = i\n\n\nclass Solution(object):\n def maxLength(self, arr):\n \"\"\"\n :type arr: List[str]\n :rtype: int\n \"\"\"\n def bitset(s):\n result = 0\n for c in s:\n if result & power[ord(c)-ord('a')]:\n return 0\n result |= power[ord(c)-ord('a')]\n return result\n \n def number_of_one(n):\n result = 0\n while n:\n n &= n-1\n result += 1\n return result\n\n dp = [0]\n for x in arr:\n x_set = bitset(x)\n if not x_set:\n continue\n curr_len = len(dp)\n for i in range(curr_len):\n if dp[i] & x_set:\n continue\n dp.append(dp[i] | x_set)\n return max(number_of_one(s_set) for s_set in dp)\n\n\n# Time: O(2^n)\n# Space: O(1)\nclass Solution2(object):\n def maxLength(self, arr):\n \"\"\"\n :type arr: List[str]\n :rtype: int\n \"\"\" \n def bitset(s):\n result = 0\n for c in s:\n if result & power[ord(c)-ord('a')]:\n return 0\n result |= power[ord(c)-ord('a')]\n return result\n \n bitsets = [bitset(x) for x in arr]\n result = 0\n for i in range(power[len(arr)]):\n curr_bitset, curr_len = 0, 0\n while i:\n j = i & -i # rightmost bit\n i ^= j\n j = log2[j] # log2(j)\n if not bitsets[j] or (curr_bitset & bitsets[j]):\n break\n curr_bitset |= bitsets[j]\n curr_len += len(arr[j])\n else:\n result = max(result, curr_len)\n return result\n"}} diff --git a/cp/cp-10679.jsonl b/cp/cp-10679.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a635b1229b057e5e3ed98e1bd19d69bab65f83bc --- /dev/null +++ b/cp/cp-10679.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10679", "name": "LeetCode 1240: Tiling A Rectangle With The Fewest Squares"} +{"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: Tiling a Rectangle with the Fewest Squares (Difficulty: Hard)\nTags: Backtracking\n\nGiven a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle.\n\nExample 1:\nInput: n = 2, m = 3\nOutput: 3\nExplanation: 3 squares are necessary to cover the rectangle.\n2 (squares of 1x1)\n1 (square of 2x2)\n\nExample 2:\nInput: n = 5, m = 8\nOutput: 5\n\nExample 3:\nInput: n = 11, m = 13\nOutput: 6\n\nConstraints:\n- 1 <= n, m <= 13"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2 * m^2 * m^(n * m)), given m < n\n# Space: O(n * m)\n\nclass Solution(object):\n def tilingRectangle(self, n, m):\n \"\"\"\n :type n: int\n :type m: int\n :rtype: int\n \"\"\"\n def find_next(board):\n for i in range(len(board)):\n for j in range(len(board[0])):\n if not board[i][j]:\n return i, j\n return -1, -1\n\n def find_max_length(board, i, j):\n max_length = 1\n while i+max_length-1 < len(board) and \\\n j+max_length-1 < len(board[0]):\n for r in range(i, i+max_length-1):\n if board[r][j+max_length-1]:\n return max_length-1\n for c in range(j, j+max_length):\n if board[i+max_length-1][c]:\n return max_length-1\n max_length += 1\n return max_length-1\n\n def fill(board, i, j, length, val):\n for r in range(i, i+length):\n for c in range(j, j+length):\n board[r][c] = val\n\n def backtracking(board, count, result):\n if count >= result[0]: # pruning\n return\n i, j = find_next(board)\n if (i, j) == (-1, -1): # finished\n result[0] = min(result[0], count)\n return\n max_length = find_max_length(board, i, j)\n for k in reversed(range(1, max_length+1)):\n fill(board, i, j, k, 1)\n backtracking(board, count+1, result)\n fill(board, i, j, k, 0)\n\n if m > n:\n return self.tilingRectangle(m, n)\n board = [[0]*m for _ in range(n)]\n result = [float(\"inf\")]\n backtracking(board, 0, result)\n return result[0]\n"}} diff --git a/cp/cp-10685.jsonl b/cp/cp-10685.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ff5da96009357a75966bf442222220644c1423a3 --- /dev/null +++ b/cp/cp-10685.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10685", "name": "LeetCode 1247: Minimum Swaps To Make Strings Equal"} +{"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: Minimum Swaps to Make Strings Equal (Difficulty: Medium)\nTags: Math, String, Greedy\n\nYou are given two strings s1 and s2 of equal length consisting of letters \"x\" and \"y\" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].\nReturn the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.\n\nExample 1:\nInput: s1 = \"xx\", s2 = \"yy\"\nOutput: 1\nExplanation: Swap s1[0] and s2[1], s1 = \"yx\", s2 = \"yx\".\n\nExample 2:\nInput: s1 = \"xy\", s2 = \"yx\"\nOutput: 2\nExplanation: Swap s1[0] and s2[0], s1 = \"yy\", s2 = \"xx\".\nSwap s1[0] and s2[1], s1 = \"xy\", s2 = \"xy\".\nNote that you cannot swap s1[0] and s1[1] to make s1 equal to \"yx\", cause we can only swap chars in different strings.\n\nExample 3:\nInput: s1 = \"xx\", s2 = \"xy\"\nOutput: -1\n\nConstraints:\n- 1 <= s1.length, s2.length <= 1000\n- s1.length == s2.length\n- s1, s2 only contain 'x' or 'y'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minimumSwap(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: int\n \"\"\"\n x1, y1 = 0, 0\n for i in range(len(s1)):\n if s1[i] == s2[i]:\n continue\n x1 += int(s1[i] == 'x')\n y1 += int(s1[i] == 'y')\n if x1%2 != y1%2: # impossible\n return -1\n # case1: per xx or yy needs one swap, (x1//2 + y1//2) \n # case2: per xy or yx needs two swaps, (x1%2 + y1%2)\n return (x1//2 + y1//2) + (x1%2 + y1%2)\n"}} diff --git a/cp/cp-10686.jsonl b/cp/cp-10686.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5645e4b4d7e57d6b3c9dfb6f510ccd2a8ae20f30 --- /dev/null +++ b/cp/cp-10686.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10686", "name": "LeetCode 1248: Count Number Of Nice Subarrays"} +{"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: Count Number of Nice Subarrays (Difficulty: Medium)\nTags: Array, Hash Table, Math, Sliding Window, Prefix Sum\n\nGiven an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.\nReturn the number of nice sub-arrays.\n\nExample 1:\nInput: nums = [1,1,2,1,1], k = 3\nOutput: 2\nExplanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].\n\nExample 2:\nInput: nums = [2,4,6], k = 1\nOutput: 0\nExplanation: There are no odd numbers in the array.\n\nExample 3:\nInput: nums = [2,2,2,1,2,2,1,2,2,2], k = 2\nOutput: 16\n\nConstraints:\n- 1 <= nums.length <= 50000\n- 1 <= nums[i] <= 10^5\n- 1 <= k <= nums.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(k)\n\nclass Solution(object):\n def numberOfSubarrays(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n def atMost(nums, k):\n result, left, count = 0, 0, 0\n for right, x in enumerate(nums):\n count += x%2\n while count > k:\n count -= nums[left]%2\n left += 1\n result += right-left+1\n return result\n\n return atMost(nums, k) - atMost(nums, k-1)\n\n\n# Time: O(n)\n# Space: O(k)\nimport collections\n\n\nclass Solution2(object):\n def numberOfSubarrays(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n result = 0\n dq = collections.deque([-1])\n for i in range(len(nums)):\n if nums[i]%2:\n dq.append(i)\n if len(dq) > k+1:\n dq.popleft()\n if len(dq) == k+1:\n result += dq[1]-dq[0]\n return result\n"}} diff --git a/cp/cp-10687.jsonl b/cp/cp-10687.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4fb1805f9b8894dd537423be797c821d1f9bcc9b --- /dev/null +++ b/cp/cp-10687.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10687", "name": "LeetCode 1249: Minimum Remove To Make Valid Parentheses"} +{"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: Minimum Remove to Make Valid Parentheses (Difficulty: Medium)\nTags: String, Stack\n\nGiven a string s of '(' , ')' and lowercase English characters.\nYour task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.\nFormally, a parentheses string is valid if and only if:\n\nExample 1:\nInput: s = \"lee(t(c)o)de)\"\nOutput: \"lee(t(c)o)de\"\nExplanation: \"lee(t(co)de)\" , \"lee(t(c)ode)\" would also be accepted.\n\nExample 2:\nInput: s = \"a)b(c)d\"\nOutput: \"ab(c)d\"\n\nExample 3:\nInput: s = \"))((\"\nOutput: \"\"\nExplanation: An empty string is also valid.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s[i] is either '(' , ')', or lowercase English letter."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def minRemoveToMakeValid(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n result = list(s)\n count = 0\n for i, v in enumerate(result):\n if v == '(':\n count += 1\n elif v == ')':\n if count:\n count -= 1\n else:\n result[i] = \"\"\n if count:\n for i in reversed(range(len(result))):\n if result[i] == '(':\n result[i] = \"\"\n count -= 1\n if not count:\n break\n return \"\".join(result)\n"}} diff --git a/cp/cp-10688.jsonl b/cp/cp-10688.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c9e02a69e5be4b85fb809cf9a13c802062c3ff8b --- /dev/null +++ b/cp/cp-10688.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10688", "name": "LeetCode 1250: Check If It Is A Good 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: Check If It Is a Good Array (Difficulty: Hard)\nTags: Array, Math, Number Theory\n\nGiven an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand.\nReturn True if the array is good otherwise return False.\n\nExample 1:\nInput: nums = [12,5,7,23]\nOutput: true\nExplanation: Pick numbers 5 and 7.\n5*3 + 7*(-2) = 1\n\nExample 2:\nInput: nums = [29,6,10]\nOutput: true\nExplanation: Pick numbers 29, 6 and 10.\n29*1 + 6*(-3) + 10*(-1) = 1\n\nExample 3:\nInput: nums = [3,6]\nOutput: false\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def isGoodArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n def gcd(a, b):\n while b:\n a, b = b, a%b\n return a\n\n # Bézout's identity\n result = nums[0]\n for num in nums:\n result = gcd(result, num)\n if result == 1:\n break\n return result == 1\n"}} diff --git a/cp/cp-10689.jsonl b/cp/cp-10689.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1198738253ae5fb6ce1f36b90397145783b370a3 --- /dev/null +++ b/cp/cp-10689.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10689", "name": "LeetCode 1252: Cells With Odd Values In A Matrix"} +{"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: Cells with Odd Values in a Matrix (Difficulty: Easy)\nTags: Array, Math, Simulation\n\nThere is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix.\nFor each location indices[i], do both of the following:\nGiven m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices.\nFollow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space?\n\nExample 1:\nInput: m = 2, n = 3, indices = [[0,1],[1,1]]\nOutput: 6\nExplanation: Initial matrix = [[0,0,0],[0,0,0]].\nAfter applying first increment it becomes [[1,2,1],[0,1,0]].\nThe final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.\n\nExample 2:\nInput: m = 2, n = 2, indices = [[1,1],[0,0]]\nOutput: 0\nExplanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.\n\nConstraints:\n- 1 <= m, n <= 50\n- 1 <= indices.length <= 100\n- 0 <= ri < m\n- 0 <= ci < n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + m)\n# Space: O(n + m)\n\nclass Solution(object):\n def oddCells(self, n, m, indices):\n \"\"\"\n :type n: int\n :type m: int\n :type indices: List[List[int]]\n :rtype: int\n \"\"\"\n row, col = [0]*n, [0]*m\n for r, c in indices:\n row[r] ^= 1\n col[c] ^= 1\n row_sum, col_sum = sum(row), sum(col)\n return row_sum*m+col_sum*n-2*row_sum*col_sum\n\n\n# Time: O(n + m)\n# Space: O(n + m)\nimport collections\nimport itertools\n\n\nclass Solution2(object):\n def oddCells(self, n, m, indices):\n \"\"\"\n :type n: int\n :type m: int\n :type indices: List[List[int]]\n :rtype: int\n \"\"\"\n fn = lambda x: sum(count&1 for count in collections.Counter(x).itervalues())\n row_sum, col_sum = map(fn, itertools.izip(*indices))\n return row_sum*m+col_sum*n-2*row_sum*col_sum\n"}} diff --git a/cp/cp-10690.jsonl b/cp/cp-10690.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..39b1c5631289ea124034615fabdc2f97a1722a4f --- /dev/null +++ b/cp/cp-10690.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10690", "name": "LeetCode 1253: Reconstruct A 2 Row Binary Matrix"} +{"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: Reconstruct a 2-Row Binary Matrix (Difficulty: Medium)\nTags: Array, Greedy, Matrix\n\nGiven the following details of a matrix with n columns and 2 rows :\nYour task is to reconstruct the matrix with upper, lower and colsum.\nReturn it as a 2-D integer array.\nIf there are more than one valid solution, any of them will be accepted.\nIf no valid solution exists, return an empty 2-D array.\n\nExample 1:\nInput: upper = 2, lower = 1, colsum = [1,1,1]\nOutput: [[1,1,0],[0,0,1]]\nExplanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.\n\nExample 2:\nInput: upper = 2, lower = 3, colsum = [2,2,1,1]\nOutput: []\n\nExample 3:\nInput: upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]\nOutput: [[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]\n\nConstraints:\n- 1 <= colsum.length <= 10^5\n- 0 <= upper, lower <= colsum.length\n- 0 <= colsum[i] <= 2"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def reconstructMatrix(self, upper, lower, colsum):\n \"\"\"\n :type upper: int\n :type lower: int\n :type colsum: List[int]\n :rtype: List[List[int]]\n \"\"\"\n upper_matrix, lower_matrix = [0]*len(colsum), [0]*len(colsum)\n for i in range(len(colsum)):\n upper_matrix[i] = int(upper > 0 and colsum[i] != 0)\n lower_matrix[i] = colsum[i]-upper_matrix[i]\n upper -= upper_matrix[i]\n lower -= lower_matrix[i]\n return [upper_matrix, lower_matrix] if upper == lower == 0 else []\n"}} diff --git a/cp/cp-10691.jsonl b/cp/cp-10691.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c6501c23d6858b40f2f4c66738722f6d96e3883e --- /dev/null +++ b/cp/cp-10691.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10691", "name": "LeetCode 1254: Number Of Closed Islands"} +{"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 Closed Islands (Difficulty: Medium)\nTags: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix\n\nGiven a 2D grid consists of 0s (land) and 1s (water).  An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.\nReturn the number of closed islands.\n\nExample 1:\nInput: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]\nOutput: 2\nExplanation: \nIslands in gray are closed because they are completely surrounded by water (group of 1s).\n\nExample 2:\nInput: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]\nOutput: 1\n\nExample 3:\nInput: grid = [[1,1,1,1,1,1,1],\n  [1,0,0,0,0,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,1,0,1,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,0,0,0,0,1],\n [1,1,1,1,1,1,1]]\nOutput: 2\n\nConstraints:\n- 1 <= grid.length, grid[0].length <= 100\n- 0 <= grid[i][j] <=1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def closedIsland(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n def fill(grid, i, j):\n if not (0 <= i < len(grid) and \n 0 <= j < len(grid[0]) and \n grid[i][j] == 0):\n return False\n grid[i][j] = 1\n for dx, dy in directions:\n fill(grid, i+dx, j+dy)\n return True\n\n for j in range(len(grid[0])):\n fill(grid, 0, j)\n fill(grid, len(grid)-1, j)\n for i in range(1, len(grid)):\n fill(grid, i, 0)\n fill(grid, i, len(grid[0])-1)\n result = 0\n for i in range(1, len(grid)-1):\n for j in range(1, len(grid[0])-1):\n if fill(grid, i, j):\n result += 1\n return result\n"}} diff --git a/cp/cp-10692.jsonl b/cp/cp-10692.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c430a468ce957fcbbde8e9812d4afe4b6e4a71ec --- /dev/null +++ b/cp/cp-10692.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10692", "name": "LeetCode 1255: Maximum Score Words Formed By Letters"} +{"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 Score Words Formed by Letters (Difficulty: Hard)\nTags: Array, String, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask\n\nGiven a list of words, list of  single letters (might be repeating) and score of every character.\nReturn the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).\nIt is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively.\n\nExample 1:\nInput: words = [\"dog\",\"cat\",\"dad\",\"good\"], letters = [\"a\",\"a\",\"c\",\"d\",\"d\",\"d\",\"g\",\"o\",\"o\"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]\nOutput: 23\nExplanation:\nScore a=1, c=9, d=5, g=3, o=2\nGiven letters, we can form the words \"dad\" (5+1+5) and \"good\" (3+2+2+5) with a score of 23.\nWords \"dad\" and \"dog\" only get a score of 21.\n\nExample 2:\nInput: words = [\"xxxz\",\"ax\",\"bx\",\"cx\"], letters = [\"z\",\"a\",\"b\",\"c\",\"x\",\"x\",\"x\"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]\nOutput: 27\nExplanation:\nScore a=4, b=4, c=4, x=5, z=10\nGiven letters, we can form the words \"ax\" (4+5), \"bx\" (4+5) and \"cx\" (4+5) with a score of 27.\nWord \"xxxz\" only get a score of 25.\n\nExample 3:\nInput: words = [\"leetcode\"], letters = [\"l\",\"e\",\"t\",\"c\",\"o\",\"d\"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]\nOutput: 0\nExplanation:\nLetter \"e\" can only be used once.\n\nConstraints:\n- 1 <= words.length <= 14\n- 1 <= words[i].length <= 15\n- 1 <= letters.length <= 100\n- letters[i].length == 1\n- score.length == 26\n- 0 <= score[i] <= 10\n- words[i], letters[i] contains only lower case English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * 2^n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def maxScoreWords(self, words, letters, score):\n \"\"\"\n :type words: List[str]\n :type letters: List[str]\n :type score: List[int]\n :rtype: int\n \"\"\"\n def backtracking(words, word_scores, word_counts, curr, curr_score, letter_count, result):\n result[0] = max(result[0], curr_score) \n for i in range(curr, len(words)):\n if any(letter_count[c] < word_counts[i][c] for c in word_counts[i]):\n continue\n backtracking(words, word_scores, word_counts, i+1,\n curr_score+word_scores[i], letter_count-word_counts[i],\n result)\n\n letter_count = collections.Counter(letters) \n word_counts = map(collections.Counter, words)\n word_scores = [sum(score[ord(c)-ord('a')] for c in words[i])\n for i in range(len(words))]\n result = [0]\n backtracking(words, word_scores, word_counts, 0, 0, letter_count, result)\n return result[0]\n"}} diff --git a/cp/cp-10697.jsonl b/cp/cp-10697.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0147cb3d29b2af7a84f52b52cdd8c23d32ba8747 --- /dev/null +++ b/cp/cp-10697.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10697", "name": "LeetCode 1260: Shift 2D Grid"} +{"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: Shift 2D Grid (Difficulty: Easy)\nTags: Array, Matrix, Simulation\n\nGiven a 2D grid of size m x n and an integer k. You need to shift the grid k times.\nIn one shift operation:\nReturn the 2D grid after applying shift operation k times.\n\nExample 1:\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1\nOutput: [[9,1,2],[3,4,5],[6,7,8]]\n\nExample 2:\nInput: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4\nOutput: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]\n\nExample 3:\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9\nOutput: [[1,2,3],[4,5,6],[7,8,9]]\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m <= 50\n- 1 <= n <= 50\n- -1000 <= grid[i][j] <= 1000\n- 0 <= k <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def shiftGrid(self, grid, k):\n \"\"\"\n :type grid: List[List[int]]\n :type k: int\n :rtype: List[List[int]]\n \"\"\"\n def rotate(grids, k):\n def reverse(grid, start, end):\n while start < end:\n start_r, start_c = divmod(start, len(grid[0]))\n end_r, end_c = divmod(end-1, len(grid[0]))\n grid[start_r][start_c], grid[end_r][end_c] = grid[end_r][end_c], grid[start_r][start_c]\n start += 1\n end -= 1\n\n k %= len(grid)*len(grid[0])\n reverse(grid, 0, len(grid)*len(grid[0]))\n reverse(grid, 0, k)\n reverse(grid, k, len(grid)*len(grid[0]))\n\n rotate(grid, k)\n return grid\n"}} diff --git a/cp/cp-10698.jsonl b/cp/cp-10698.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6abee5f5797a56daa9350aa885486cd3f81394ac --- /dev/null +++ b/cp/cp-10698.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10698", "name": "LeetCode 1261: Find Elements In A Contaminated 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: Find Elements in a Contaminated Binary Tree (Difficulty: Medium)\nTags: Hash Table, Tree, Depth-First Search, Breadth-First Search, Design, Binary Tree\n\nGiven a binary tree with the following rules:\nNow the binary tree is contaminated, which means all treeNode.val have been changed to -1.\nImplement the FindElements class:\n\nExample 1:\nInput\n[\"FindElements\",\"find\",\"find\"]\n[[[-1,null,-1]],[1],[2]]\nOutput\n[null,false,true]\nExplanation\nFindElements findElements = new FindElements([-1,null,-1]); \nfindElements.find(1); // return False \nfindElements.find(2); // return True\n\nExample 2:\nInput\n[\"FindElements\",\"find\",\"find\",\"find\"]\n[[[-1,-1,-1,-1,-1]],[1],[3],[5]]\nOutput\n[null,true,true,false]\nExplanation\nFindElements findElements = new FindElements([-1,-1,-1,-1,-1]);\nfindElements.find(1); // return True\nfindElements.find(3); // return True\nfindElements.find(5); // return False\n\nExample 3:\nInput\n[\"FindElements\",\"find\",\"find\",\"find\",\"find\"]\n[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]\nOutput\n[null,true,false,false,true]\nExplanation\nFindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);\nfindElements.find(2); // return True\nfindElements.find(3); // return False\nfindElements.find(4); // return False\nfindElements.find(5); // return True\n\nConstraints:\n- TreeNode.val == -1\n- The height of the binary tree is less than or equal to 20\n- The total number of nodes is between [1, 104]\n- Total calls of find() is between [1, 104]\n- 0 <= target <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass FindElements(object):\n\n def __init__(self, root):\n \"\"\"\n :type root: TreeNode\n \"\"\"\n def dfs(node, v, lookup):\n if not node:\n return\n node.val = v \n lookup.add(v)\n dfs(node.left, 2*v+1, lookup)\n dfs(node.right, 2*v+2, lookup)\n\n self.__lookup = set()\n dfs(root, 0, self.__lookup)\n\n def find(self, target):\n \"\"\"\n :type target: int\n :rtype: bool\n \"\"\"\n return target in self.__lookup \n"}} diff --git a/cp/cp-10699.jsonl b/cp/cp-10699.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..40f450a5b63999f05a3ff24b2b982df7ee05613f --- /dev/null +++ b/cp/cp-10699.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10699", "name": "LeetCode 1262: Greatest Sum Divisible By Three"} +{"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: Greatest Sum Divisible by Three (Difficulty: Medium)\nTags: Array, Dynamic Programming, Greedy, Sorting\n\nGiven an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.\n\nExample 1:\nInput: nums = [3,6,5,1,8]\nOutput: 18\nExplanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).\n\nExample 2:\nInput: nums = [4]\nOutput: 0\nExplanation: Since 4 is not divisible by 3, do not pick any number.\n\nExample 3:\nInput: nums = [1,2,3,4,4]\nOutput: 12\nExplanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).\n\nConstraints:\n- 1 <= nums.length <= 4 * 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 maxSumDivThree(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n dp = [0, 0, 0]\n for num in nums:\n for i in [num+x for x in dp]:\n dp[i%3] = max(dp[i%3], i)\n return dp[0]\n"}} diff --git a/cp/cp-10700.jsonl b/cp/cp-10700.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e047afaba9141ba42714c9d1e233907ab674d695 --- /dev/null +++ b/cp/cp-10700.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10700", "name": "LeetCode 1263: Minimum Moves To Move A Box To Their Target Location"} +{"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: Minimum Moves to Move a Box to Their Target Location (Difficulty: Hard)\nTags: Array, Breadth-First Search, Heap (Priority Queue), Matrix\n\nA storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.\nThe game is represented by an m x n grid of characters grid where each element is a wall, floor, or box.\nYour task is to move the box 'B' to the target position 'T' under the following rules:\nReturn the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1.\n\nExample 1:\nInput: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput: 3\nExplanation: We return only the number of times the box is pushed.\n\nExample 2:\nInput: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput: -1\n\nExample 3:\nInput: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\".\",\".\",\"#\",\"#\"],\n [\"#\",\".\",\"#\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput: 5\nExplanation: push the box down, left, left, up and up.\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 20\n- grid contains only characters '.', '#', 'S', 'T', or 'B'.\n- There is only one character 'S', 'B', and 'T' in the grid."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m^2 * n^2)\n# Space: O(m^2 * n^2)\n\n# A* Search Algorithm without heap\nclass Solution(object):\n def minPushBox(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n def dot(a, b):\n return a[0]*b[0]+a[1]*b[1]\n\n def can_reach(grid, b, p, t):\n closer, detour = [p], []\n lookup = set([b])\n while closer or detour:\n if not closer:\n closer, detour = detour, closer\n p = closer.pop()\n if p == t:\n return True\n if p in lookup:\n continue\n lookup.add(p)\n for dx, dy in directions:\n np = (p[0]+dx, p[1]+dy)\n if not (0 <= np[0] < len(grid) and 0 <= np[1] < len(grid[0]) and\n grid[np[0]][np[1]] != '#' and np not in lookup):\n continue\n (closer if dot((dx, dy), (t[0]-p[0], t[1]-p[1])) > 0 else detour).append(np)\n return False\n\n def g(a, b):\n return abs(a[0]-b[0])+abs(a[1]-b[1])\n \n def a_star(grid, b, p, t):\n f, dh = g(b, t), 2\n closer, detour = [(b, p)], []\n lookup = set()\n while closer or detour:\n if not closer:\n f += dh\n closer, detour = detour, closer\n b, p = closer.pop()\n if b == t:\n return f\n if (b, p) in lookup:\n continue\n lookup.add((b, p))\n for dx, dy in directions:\n nb, np = (b[0]+dx, b[1]+dy), (b[0]-dx, b[1]-dy)\n if not (0 <= nb[0] < len(grid) and 0 <= nb[1] < len(grid[0]) and\n 0 <= np[0] < len(grid) and 0 <= np[1] < len(grid[0]) and\n grid[nb[0]][nb[1]] != '#' and grid[np[0]][np[1]] != '#' and\n (nb, b) not in lookup and can_reach(grid, b, p, np)):\n continue\n (closer if dot((dx, dy), (t[0]-b[0], t[1]-b[1])) > 0 else detour).append((nb, b))\n return -1\n \n b, p, t = None, None, None\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 'B':\n b = (i, j)\n elif grid[i][j] == 'S':\n p = (i, j)\n elif grid[i][j] == 'T':\n t = (i, j)\n return a_star(grid, b, p, t)\n"}} diff --git a/cp/cp-10702.jsonl b/cp/cp-10702.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0d68f9e628e42d2713b759dd4d7dbf7d9f1c5415 --- /dev/null +++ b/cp/cp-10702.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10702", "name": "LeetCode 1266: Minimum Time Visiting All Points"} +{"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: Minimum Time Visiting All Points (Difficulty: Easy)\nTags: Array, Math, Geometry\n\nOn a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.\nYou can move according to these rules:\n\nExample 1:\nInput: points = [[1,1],[3,4],[-1,0]]\nOutput: 7\nExplanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] \nTime from [1,1] to [3,4] = 3 seconds \nTime from [3,4] to [-1,0] = 4 seconds\nTotal time = 7 seconds\n\nExample 2:\nInput: points = [[3,2],[-2,2]]\nOutput: 5\n\nConstraints:\n- points.length == n\n- 1 <= n <= 100\n- points[i].length == 2\n- -1000 <= points[i][0], points[i][1] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minTimeToVisitAllPoints(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n return sum(max(abs(points[i+1][0] - points[i][0]),\n abs(points[i+1][1] - points[i][1]))\n for i in range(len(points)-1))\n"}} diff --git a/cp/cp-10703.jsonl b/cp/cp-10703.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ea875c34d172ceb8ee04a07c02dbc86f50baaa56 --- /dev/null +++ b/cp/cp-10703.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10703", "name": "LeetCode 1267: Count Servers That Communicate"} +{"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: Count Servers that Communicate (Difficulty: Medium)\nTags: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix, Counting\n\nYou are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.\n\nReturn the number of servers that communicate with any other server.\n\nExample 1:\nInput: grid = [[1,0],[0,1]]\nOutput: 0\nExplanation: No servers can communicate with others.\n\nExample 2:\nInput: grid = [[1,0],[1,1]]\nOutput: 3\nExplanation: All three servers can communicate with at least one other server.\n\nExample 3:\nInput: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]\nOutput: 4\nExplanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m <= 250\n- 1 <= n <= 250\n- grid[i][j] == 0 or 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m + n)\n\nclass Solution(object):\n def countServers(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n rows, cols = [0]*len(grid), [0]*len(grid[0])\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j]:\n rows[i] += 1\n cols[j] += 1\n result = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] and (rows[i] > 1 or cols[j] > 1):\n result += 1\n return result\n\n"}} diff --git a/cp/cp-10704.jsonl b/cp/cp-10704.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a3b6103e76439e50333da353686d39e114d07337 --- /dev/null +++ b/cp/cp-10704.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10704", "name": "LeetCode 1268: Search Suggestions 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: Search Suggestions System (Difficulty: Medium)\nTags: Array, String, Binary Search, Trie, Sorting, Heap (Priority Queue)\n\nYou are given an array of strings products and a string searchWord.\nDesign a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.\nReturn a list of lists of the suggested products after each character of searchWord is typed.\n\nExample 1:\nInput: products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord = \"mouse\"\nOutput: [[\"mobile\",\"moneypot\",\"monitor\"],[\"mobile\",\"moneypot\",\"monitor\"],[\"mouse\",\"mousepad\"],[\"mouse\",\"mousepad\"],[\"mouse\",\"mousepad\"]]\nExplanation: products sorted lexicographically = [\"mobile\",\"moneypot\",\"monitor\",\"mouse\",\"mousepad\"].\nAfter typing m and mo all products match and we show user [\"mobile\",\"moneypot\",\"monitor\"].\nAfter typing mou, mous and mouse the system suggests [\"mouse\",\"mousepad\"].\n\nExample 2:\nInput: products = [\"havana\"], searchWord = \"havana\"\nOutput: [[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]\nExplanation: The only word \"havana\" will be always suggested while typing the search word.\n\nConstraints:\n- 1 <= products.length <= 1000\n- 1 <= products[i].length <= 3000\n- 1 <= sum(products[i].length) <= 2 * 10^4\n- All the strings of products are unique.\n- products[i] consists of lowercase English letters.\n- 1 <= searchWord.length <= 1000\n- searchWord consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(n * l), n is the number of products\n# , l is the average length of product name\n# suggest: O(l^2)\n# Space: O(t), t is the number of nodes in trie\n\nimport collections\n\n\nclass TrieNode(object):\n\n def __init__(self):\n self.__TOP_COUNT = 3\n self.leaves = collections.defaultdict(TrieNode)\n self.infos = []\n\n def insert(self, words, i):\n curr = self\n for c in words[i]:\n curr = curr.leaves[c]\n curr.add_info(words, i)\n\n def add_info(self, words, i):\n self.infos.append(i)\n self.infos.sort(key=lambda x: words[x])\n if len(self.infos) > self.__TOP_COUNT:\n self.infos.pop()\n\n\nclass Solution(object):\n def suggestedProducts(self, products, searchWord):\n \"\"\"\n :type products: List[str]\n :type searchWord: str\n :rtype: List[List[str]]\n \"\"\"\n trie = TrieNode()\n for i in range(len(products)):\n trie.insert(products, i)\n result = [[] for _ in range(len(searchWord))]\n for i, c in enumerate(searchWord):\n if c not in trie.leaves:\n break\n trie = trie.leaves[c]\n result[i] = map(lambda x: products[x], trie.infos)\n return result\n\n\n# Time: ctor: O(n * l * log(n * l)), n is the number of products\n# , l is the average length of product name\n# suggest: O(l^2)\n# Space: O(t), t is the number of nodes in trie\nclass TrieNode2(object):\n\n def __init__(self):\n self.__TOP_COUNT = 3\n self.leaves = collections.defaultdict(TrieNode2)\n self.infos = []\n\n def insert(self, words, i):\n curr = self\n for c in words[i]:\n curr = curr.leaves[c]\n curr.add_info(i)\n\n def add_info(self, i):\n if len(self.infos) == self.__TOP_COUNT:\n return\n self.infos.append(i)\n\n\nclass Solution2(object):\n def suggestedProducts(self, products, searchWord):\n \"\"\"\n :type products: List[str]\n :type searchWord: str\n :rtype: List[List[str]]\n \"\"\"\n products.sort()\n trie = TrieNode2()\n for i in range(len(products)):\n trie.insert(products, i)\n result = [[] for _ in range(len(searchWord))]\n for i, c in enumerate(searchWord):\n if c not in trie.leaves:\n break\n trie = trie.leaves[c]\n result[i] = map(lambda x: products[x], trie.infos)\n return result\n\n\n# Time: ctor: O(n * l * log(n * l)), n is the number of products\n# , l is the average length of product name\n# suggest: O(l^2 * n)\n# Space: O(n * l)\nimport bisect\n\n\nclass Solution3(object):\n def suggestedProducts(self, products, searchWord):\n \"\"\"\n :type products: List[str]\n :type searchWord: str\n :rtype: List[List[str]]\n \"\"\"\n products.sort() # Time: O(n * l * log(n * l))\n result = []\n prefix = \"\"\n for i, c in enumerate(searchWord): # Time: O(l)\n prefix += c\n start = bisect.bisect_left(products, prefix) # Time: O(log(n * l))\n new_products = []\n for j in range(start, len(products)): # Time: O(n * l)\n if not (i < len(products[j]) and products[j][i] == c):\n break\n new_products.append(products[j])\n products = new_products\n result.append(products[:3])\n return result\n"}} diff --git a/cp/cp-10705.jsonl b/cp/cp-10705.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2908d7548ddd0bff9d01e3b1d392aa249c0c0480 --- /dev/null +++ b/cp/cp-10705.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10705", "name": "LeetCode 1269: Number Of Ways To Stay In The Same Place After Some Steps"} +{"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 Ways to Stay in the Same Place After Some Steps (Difficulty: Hard)\nTags: Dynamic Programming\n\nYou have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).\nGiven two integers steps and arrLen, return the number of ways such that your pointer is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: steps = 3, arrLen = 2\nOutput: 4\nExplanation: There are 4 differents ways to stay at index 0 after 3 steps.\nRight, Left, Stay\nStay, Right, Left\nRight, Stay, Left\nStay, Stay, Stay\n\nExample 2:\nInput: steps = 2, arrLen = 4\nOutput: 2\nExplanation: There are 2 differents ways to stay at index 0 after 2 steps\nRight, Left\nStay, Stay\n\nExample 3:\nInput: steps = 4, arrLen = 2\nOutput: 8\n\nConstraints:\n- 1 <= steps <= 500\n- 1 <= arrLen <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2), n is the number of steps\n# Space: O(n)\n \nclass Solution(object):\n def numWays(self, steps, arrLen):\n \"\"\"\n :type steps: int\n :type arrLen: int\n :rtype: int\n \"\"\"\n MOD = int(1e9+7)\n l = min(1+steps//2, arrLen)\n dp = [0]*(l+2)\n dp[1] = 1\n while steps > 0:\n steps -= 1\n new_dp = [0]*(l+2)\n for i in range(1, l+1):\n new_dp[i] = (dp[i] + dp[i-1] + dp[i+1]) % MOD\n dp = new_dp\n return dp[1]\n"}} diff --git a/cp/cp-10710.jsonl b/cp/cp-10710.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a356846db4aef3ba55b79565ae7d572698532dc1 --- /dev/null +++ b/cp/cp-10710.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10710", "name": "LeetCode 1275: Find Winner On A Tic Tac Toe Game"} +{"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 Winner on a Tic Tac Toe Game (Difficulty: Easy)\nTags: Array, Hash Table, Matrix, Simulation\n\nTic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:\nGiven a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return \"Draw\". If there are still movements to play return \"Pending\".\nYou can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first.\n\nExample 1:\nInput: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]\nOutput: \"A\"\nExplanation: A wins, they always play first.\n\nExample 2:\nInput: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]\nOutput: \"B\"\nExplanation: B wins.\n\nExample 3:\nInput: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]\nOutput: \"Draw\"\nExplanation: The game ends in a draw since there are no moves to make.\n\nConstraints:\n- 1 <= moves.length <= 9\n- moves[i].length == 2\n- 0 <= rowi, coli <= 2\n- There are no repeated elements on moves.\n- moves follow the rules of tic tac toe."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def tictactoe(self, moves):\n \"\"\"\n :type moves: List[List[int]]\n :rtype: str\n \"\"\"\n row, col = [[0]*3 for _ in range(2)], [[0]*3 for _ in range(2)]\n diag, anti_diag = [0]*2, [0]*2\n p = 0\n for r, c in moves:\n row[p][r] += 1\n col[p][c] += 1\n diag[p] += r == c\n anti_diag[p] += r+c == 2\n if 3 in (row[p][r], col[p][c], diag[p], anti_diag[p]):\n return \"AB\"[p]\n p ^= 1\n return \"Draw\" if len(moves) == 9 else \"Pending\"\n"}} diff --git a/cp/cp-10711.jsonl b/cp/cp-10711.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3e8ecae2aeacfb79c31ff391d9d3c0fab914bd41 --- /dev/null +++ b/cp/cp-10711.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10711", "name": "LeetCode 1276: Number Of Burgers With No Waste Of Ingredients"} +{"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 Burgers with No Waste of Ingredients (Difficulty: Medium)\nTags: Math\n\nGiven two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows:\nReturn [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [].\n\nExample 1:\nInput: tomatoSlices = 16, cheeseSlices = 7\nOutput: [1,6]\nExplantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.\nThere will be no remaining ingredients.\n\nExample 2:\nInput: tomatoSlices = 17, cheeseSlices = 4\nOutput: []\nExplantion: There will be no way to use all ingredients to make small and jumbo burgers.\n\nExample 3:\nInput: tomatoSlices = 4, cheeseSlices = 17\nOutput: []\nExplantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.\n\nConstraints:\n- 0 <= tomatoSlices, cheeseSlices <= 10^7"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def numOfBurgers(self, tomatoSlices, cheeseSlices):\n \"\"\"\n :type tomatoSlices: int\n :type cheeseSlices: int\n :rtype: List[int]\n \"\"\"\n # let the number of jumbo burger be x, the number of small burger be y:\n # 4x + 2y = t\n # x + y = c\n # =>\n # x = t/2-c\n # y = 2c-t/2\n # since x, y are natural numbers\n # => t/2 is integer, t/2-c >= 0, 2c-t/2 >= 0\n # => t%2 == 0, 2c <= t <= 4c\n return [tomatoSlices//2-cheeseSlices, 2*cheeseSlices - tomatoSlices//2] \\\n if tomatoSlices%2 == 0 and 2*cheeseSlices <= tomatoSlices <= 4*cheeseSlices \\\n else []\n"}} diff --git a/cp/cp-10712.jsonl b/cp/cp-10712.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..79a047ecb5ef27009e4b74aa36113153669d1fa8 --- /dev/null +++ b/cp/cp-10712.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10712", "name": "LeetCode 1277: Count Square Submatrices With All 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: Count Square Submatrices with All Ones (Difficulty: Medium)\nTags: Array, Dynamic Programming, Matrix\n\nGiven a m * n matrix of ones and zeros, return how many square submatrices have all ones.\n\nExample 1:\nInput: matrix =\n[\n  [0,1,1,1],\n  [1,1,1,1],\n  [0,1,1,1]\n]\nOutput: 15\nExplanation: \nThere are 10 squares of side 1.\nThere are 4 squares of side 2.\nThere is 1 square of side 3.\nTotal number of squares = 10 + 4 + 1 = 15.\n\nExample 2:\nInput: matrix = \n[\n [1,0,1],\n [1,1,0],\n [1,1,0]\n]\nOutput: 7\nExplanation: \nThere are 6 squares of side 1. \nThere is 1 square of side 2. \nTotal number of squares = 6 + 1 = 7.\n\nConstraints:\n- 1 <= arr.length <= 300\n- 1 <= arr[0].length <= 300\n- 0 <= arr[i][j] <= 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def countSquares(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: int\n \"\"\"\n for i in range(1, len(matrix)):\n for j in range(1, len(matrix[0])):\n if not matrix[i][j]:\n continue\n l = min(matrix[i-1][j], matrix[i][j-1])\n matrix[i][j] = l+1 if matrix[i-l][j-l] else l\n return sum(x for row in matrix for x in row)\n"}} diff --git a/cp/cp-10713.jsonl b/cp/cp-10713.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b000d71533b752dec580e7760ba3f08718f4a98f --- /dev/null +++ b/cp/cp-10713.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10713", "name": "LeetCode 1278: Palindrome Partitioning 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: Palindrome Partitioning III (Difficulty: Hard)\nTags: String, Dynamic Programming\n\nYou are given a string s containing lowercase letters and an integer k. You need to :\nReturn the minimal number of characters that you need to change to divide the string.\n\nExample 1:\nInput: s = \"abc\", k = 2\nOutput: 1\nExplanation: You can split the string into \"ab\" and \"c\", and change 1 character in \"ab\" to make it palindrome.\n\nExample 2:\nInput: s = \"aabbc\", k = 3\nOutput: 0\nExplanation: You can split the string into \"aa\", \"bb\" and \"c\", all of them are palindrome.\n\nExample 3:\nInput: s = \"leetcode\", k = 8\nOutput: 0\n\nConstraints:\n- 1 <= k <= s.length <= 100.\n- s only contains lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(k * n^2)\n# Space: O(n^2)\n\nclass Solution(object):\n def palindromePartition(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: int\n \"\"\"\n # dp1[i][j]: minimum number of changes to make s[i, j] palindrome\n dp1 = [[0]*len(s) for _ in range(len(s))]\n for l in range(1, len(s)+1):\n for i in range(len(s)-l+1):\n j = i+l-1\n if i == j-1:\n dp1[i][j] = 0 if s[i] == s[j] else 1\n elif i != j:\n dp1[i][j] = dp1[i+1][j-1] if s[i] == s[j] else dp1[i+1][j-1]+1\n\n # dp2[d][i]: minimum number of changes to divide s[0, i] into d palindromes\n dp2 = [[float(\"inf\")]*len(s) for _ in range(2)]\n dp2[1] = dp1[0][:]\n for d in range(2, k+1):\n dp2[d%2] = [float(\"inf\")]*len(s)\n for i in range(d-1, len(s)): \n for j in range(d-2, i):\n dp2[d%2][i] = min(dp2[d%2][i], dp2[(d-1)%2][j]+dp1[j+1][i])\n return dp2[k%2][len(s)-1]\n"}} diff --git a/cp/cp-10715.jsonl b/cp/cp-10715.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d9179baad1a131960a10b1fd9fe5e41da276e356 --- /dev/null +++ b/cp/cp-10715.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10715", "name": "LeetCode 1281: Subtract The Product And Sum Of Digits Of An Integer"} +{"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: Subtract the Product and Sum of Digits of an Integer (Difficulty: Easy)\nTags: Math\n\nExample 1:\nInput: n = 234\nOutput: 15 \nExplanation: \nProduct of digits = 2 * 3 * 4 = 24 \nSum of digits = 2 + 3 + 4 = 9 \nResult = 24 - 9 = 15\n\nExample 2:\nInput: n = 4421\nOutput: 21\nExplanation: \nProduct of digits = 4 * 4 * 2 * 1 = 32 \nSum of digits = 4 + 4 + 2 + 1 = 11 \nResult = 32 - 11 = 21\n\nConstraints:\n- 1 <= n <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nclass Solution(object):\n def subtractProductAndSum(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n product, total = 1, 0\n while n:\n n, r = divmod(n, 10)\n product *= r\n total += r\n return product-total\n\n\n# Time: O(logn)\n# Space: O(logn)\nimport operator\n\n\nclass Solution2(object):\n def subtractProductAndSum(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n A = map(int, str(n))\n return reduce(operator.mul, A) - sum(A)\n"}} diff --git a/cp/cp-10716.jsonl b/cp/cp-10716.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6873d2ac720ab2fbdcfec09b0f15756945328186 --- /dev/null +++ b/cp/cp-10716.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10716", "name": "LeetCode 1282: Group The People Given The Group Size They Belong To"} +{"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: Group the People Given the Group Size They Belong To (Difficulty: Medium)\nTags: Array, Hash Table, Greedy\n\nThere are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.\nYou are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.\nReturn a list of groups such that each person i is in a group of size groupSizes[i].\nEach person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.\n\nExample 1:\nInput: groupSizes = [3,3,3,3,3,1,3]\nOutput: [[5],[0,1,2],[3,4,6]]\nExplanation: \nThe first group is [5]. The size is 1, and groupSizes[5] = 1.\nThe second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.\nThe third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.\nOther possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].\n\nExample 2:\nInput: groupSizes = [2,1,3,3,3,2]\nOutput: [[1],[0,5],[2,3,4]]\n\nConstraints:\n- groupSizes.length == n\n- 1 <= n <= 500\n- 1 <= groupSizes[i] <= n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def groupThePeople(self, groupSizes):\n \"\"\"\n :type groupSizes: List[int]\n :rtype: List[List[int]]\n \"\"\"\n groups, result = collections.defaultdict(list), []\n for i, size in enumerate(groupSizes):\n groups[size].append(i)\n if len(groups[size]) == size:\n result.append(groups.pop(size))\n return result\n"}} diff --git a/cp/cp-10717.jsonl b/cp/cp-10717.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8940982873cc275c0280d29b4d0524dcd4f0cb01 --- /dev/null +++ b/cp/cp-10717.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10717", "name": "LeetCode 1283: Find The Smallest Divisor Given A Threshold"} +{"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 the Smallest Divisor Given a Threshold (Difficulty: Medium)\nTags: Array, Binary Search\n\nGiven an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.\nEach result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).\nThe test cases are generated so that there will be an answer.\n\nExample 1:\nInput: nums = [1,2,5,9], threshold = 6\nOutput: 5\nExplanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. \nIf the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).\n\nExample 2:\nInput: nums = [44,22,33,11,1], threshold = 5\nOutput: 44\n\nConstraints:\n- 1 <= nums.length <= 5 * 10^4\n- 1 <= nums[i] <= 10^6\n- nums.length <= threshold <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nclass Solution(object):\n def smallestDivisor(self, nums, threshold):\n \"\"\"\n :type nums: List[int]\n :type threshold: int\n :rtype: int\n \"\"\"\n def check(A, d, threshold):\n return sum((i-1)//d+1 for i in nums) <= threshold\n\n left, right = 1, max(nums)\n while left <= right:\n mid = left + (right-left)//2\n if check(nums, mid, threshold):\n right = mid-1\n else:\n left = mid+1\n return left\n"}} diff --git a/cp/cp-10718.jsonl b/cp/cp-10718.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e4d788fb3a3220007dd018062a31af82b03e0269 --- /dev/null +++ b/cp/cp-10718.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10718", "name": "LeetCode 1284: Minimum Number Of Flips To Convert Binary Matrix To Zero Matrix"} +{"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: Minimum Number of Flips to Convert Binary Matrix to Zero Matrix (Difficulty: Hard)\nTags: Array, Hash Table, Bit Manipulation, Breadth-First Search, Matrix\n\nGiven a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge.\nReturn the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.\nA binary matrix is a matrix with all cells equal to 0 or 1 only.\nA zero matrix is a matrix with all cells equal to 0.\n\nExample 1:\nInput: mat = [[0,0],[0,1]]\nOutput: 3\nExplanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.\n\nExample 2:\nInput: mat = [[0]]\nOutput: 0\nExplanation: Given matrix is a zero matrix. We do not need to change it.\n\nExample 3:\nInput: mat = [[1,0,0],[1,0,0]]\nOutput: -1\nExplanation: Given matrix cannot be a zero matrix.\n\nConstraints:\n- m == mat.length\n- n == mat[i].length\n- 1 <= m, n <= 3\n- mat[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((m * n) * 2^(m * n))\n# Space: O((m * n) * 2^(m * n))\n\nimport collections\n\n\nclass Solution(object):\n def minFlips(self, mat):\n \"\"\"\n :type mat: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 0), (0, 1), (1, 0), (0, -1), (-1, 0)]\n start = sum(val << r*len(mat[0])+c for r, row in enumerate(mat) for c, val in enumerate(row))\n q = collections.deque([(start, 0)])\n lookup = {start}\n while q:\n state, step = q.popleft()\n if not state:\n return step\n for r in range(len(mat)):\n for c in range(len(mat[0])):\n new_state = state\n for dr, dc in directions:\n nr, nc = r+dr, c+dc\n if 0 <= nr < len(mat) and 0 <= nc < len(mat[0]):\n new_state ^= 1 << nr*len(mat[0])+nc\n if new_state in lookup:\n continue\n lookup.add(new_state)\n q.append((new_state, step+1))\n return -1\n"}} diff --git a/cp/cp-10719.jsonl b/cp/cp-10719.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6ad0e40958a7f82663b0961497ff09c4f6ac3b30 --- /dev/null +++ b/cp/cp-10719.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10719", "name": "LeetCode 1286: Iterator For Combination"} +{"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: Iterator for Combination (Difficulty: Medium)\nTags: String, Backtracking, Design, Iterator\n\nDesign the CombinationIterator class:\n\nExample 1:\nInput\n[\"CombinationIterator\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[\"abc\", 2], [], [], [], [], [], []]\nOutput\n[null, \"ab\", true, \"ac\", true, \"bc\", false]\n\nExplanation\nCombinationIterator itr = new CombinationIterator(\"abc\", 2);\nitr.next(); // return \"ab\"\nitr.hasNext(); // return True\nitr.next(); // return \"ac\"\nitr.hasNext(); // return True\nitr.next(); // return \"bc\"\nitr.hasNext(); // return False\n\nConstraints:\n- 1 <= combinationLength <= characters.length <= 15\n- All the characters of characters are unique.\n- At most 104 calls will be made to next and hasNext.\n- It is guaranteed that all calls of the function next are valid."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(k), per operation\n# Space: O(k)\n\nimport itertools\n\n\nclass CombinationIterator(object):\n\n def __init__(self, characters, combinationLength):\n \"\"\"\n :type characters: str\n :type combinationLength: int\n \"\"\"\n self.__it = itertools.combinations(characters, combinationLength)\n self.__curr = None\n self.__last = characters[-combinationLength:]\n\n def next(self):\n \"\"\"\n :rtype: str\n \"\"\"\n self.__curr = \"\".join(self.__it.next())\n return self.__curr\n \n def hasNext(self):\n \"\"\"\n :rtype: bool\n \"\"\"\n return self.__curr != self.__last\n\n\n# Time: O(k), per operation\n# Space: O(k)\nimport functools\n\n\nclass CombinationIterator2(object):\n\n def __init__(self, characters, combinationLength):\n \"\"\"\n :type characters: str\n :type combinationLength: int\n \"\"\"\n self.__characters = characters\n self.__combinationLength = combinationLength\n self.__it = self.__iterative_backtracking()\n self.__curr = None\n self.__last = characters[-combinationLength:]\n \n def __iterative_backtracking(self):\n def conquer():\n if len(curr) == self.__combinationLength:\n return curr\n\n def prev_divide(c):\n curr.append(c)\n \n def divide(i):\n if len(curr) != self.__combinationLength:\n for j in reversed(range(i, len(self.__characters)-(self.__combinationLength-len(curr)-1))):\n stk.append(functools.partial(post_divide))\n stk.append(functools.partial(divide, j+1))\n stk.append(functools.partial(prev_divide, self.__characters[j]))\n stk.append(functools.partial(conquer))\n\n def post_divide():\n curr.pop()\n \n curr = []\n stk = [functools.partial(divide, 0)]\n while stk:\n result = stk.pop()()\n if result is not None:\n yield result\n\n def next(self):\n \"\"\"\n :rtype: str\n \"\"\"\n self.__curr = \"\".join(next(self.__it))\n return self.__curr\n \n def hasNext(self):\n \"\"\"\n :rtype: bool\n \"\"\"\n return self.__curr != self.__last\n\n\n# Your CombinationIterator object will be instantiated and called as such:\n# obj = CombinationIterator(characters, combinationLength)\n# param_1 = obj.next()\n# param_2 = obj.hasNext()\n"}} diff --git a/cp/cp-10720.jsonl b/cp/cp-10720.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..18bad147bf61f496a03baf5919c9d02d27dd5d3d --- /dev/null +++ b/cp/cp-10720.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10720", "name": "LeetCode 1287: Element Appearing More Than 25 In Sorted 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: Element Appearing More Than 25% In Sorted Array (Difficulty: Easy)\nTags: Array\n\nGiven an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.\n\nExample 1:\nInput: arr = [1,2,2,6,6,6,6,7,10]\nOutput: 6\n\nExample 2:\nInput: arr = [1,1]\nOutput: 1\n\nConstraints:\n- 1 <= arr.length <= 10^4\n- 0 <= arr[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nimport bisect\n\n\nclass Solution(object):\n def findSpecialInteger(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n for x in [arr[len(arr)//4], arr[len(arr)//2], arr[len(arr)*3//4]]:\n if (bisect.bisect_right(arr, x) - bisect.bisect_left(arr, x)) * 4 > len(arr):\n return x\n return -1\n"}} diff --git a/cp/cp-10721.jsonl b/cp/cp-10721.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dc1253d80fed9d7ecc7f975eb79eea00afbe60fc --- /dev/null +++ b/cp/cp-10721.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10721", "name": "LeetCode 1288: Remove Covered Intervals"} +{"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: Remove Covered Intervals (Difficulty: Medium)\nTags: Array, Sorting\n\nGiven an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.\nThe interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.\nReturn the number of remaining intervals.\n\nExample 1:\nInput: intervals = [[1,4],[3,6],[2,8]]\nOutput: 2\nExplanation: Interval [3,6] is covered by [2,8], therefore it is removed.\n\nExample 2:\nInput: intervals = [[1,4],[2,3]]\nOutput: 1\n\nConstraints:\n- 1 <= intervals.length <= 1000\n- intervals[i].length == 2\n- 0 <= li < ri <= 10^5\n- All the given intervals are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def removeCoveredIntervals(self, intervals):\n \"\"\"\n :type intervals: List[List[int]]\n :rtype: int\n \"\"\"\n intervals.sort(key=lambda x: [x[0], -x[1]])\n result, max_right = 0, 0\n for left, right in intervals:\n result += int(right > max_right)\n max_right = max(max_right, right)\n return result\n"}} diff --git a/cp/cp-10722.jsonl b/cp/cp-10722.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..734bc097bd8517992254f2b79449111099a3c757 --- /dev/null +++ b/cp/cp-10722.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10722", "name": "LeetCode 1289: Minimum Falling Path Sum 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: Minimum Falling Path Sum II (Difficulty: Hard)\nTags: Array, Dynamic Programming, Matrix\n\nGiven an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts.\nA falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.\n\nExample 1:\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: 13\nExplanation: \nThe possible falling paths are:\n[1,5,9], [1,5,7], [1,6,7], [1,6,8],\n[2,4,8], [2,4,9], [2,6,7], [2,6,8],\n[3,4,8], [3,4,9], [3,5,7], [3,5,9]\nThe falling path with the smallest sum is [1,5,7], so the answer is 13.\n\nExample 2:\nInput: grid = [[7]]\nOutput: 7\n\nConstraints:\n- n == grid.length == grid[i].length\n- 1 <= n <= 200\n- -99 <= grid[i][j] <= 99"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nimport heapq\n\n\nclass Solution(object):\n def minFallingPathSum(self, arr):\n \"\"\"\n :type arr: List[List[int]]\n :rtype: int\n \"\"\"\n for i in range(1, len(arr)):\n smallest_two = heapq.nsmallest(2, arr[i-1])\n for j in range(len(arr[0])):\n arr[i][j] += smallest_two[1] if arr[i-1][j] == smallest_two[0] else smallest_two[0]\n return min(arr[-1])\n"}} diff --git a/cp/cp-10723.jsonl b/cp/cp-10723.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b16e69bd128af71b1b8e15ba32b4e6593eaa20dc --- /dev/null +++ b/cp/cp-10723.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10723", "name": "LeetCode 1290: Convert Binary Number In A Linked List To Integer"} +{"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: Convert Binary Number in a Linked List to Integer (Difficulty: Easy)\nTags: Linked List, Math\n\nGiven head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.\nReturn the decimal value of the number in the linked list.\nThe most significant bit is at the head of the linked list.\n\nExample 1:\nInput: head = [1,0,1]\nOutput: 5\nExplanation: (101) in base 2 = (5) in base 10\n\nExample 2:\nInput: head = [0]\nOutput: 0\n\nConstraints:\n- The Linked List is not empty.\n- Number of nodes will not exceed 30.\n- Each node's value is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def getDecimalValue(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: int\n \"\"\"\n result = 0\n while head: \n result = result*2 + head.val \n head = head.next \n return result\n"}} diff --git a/cp/cp-10724.jsonl b/cp/cp-10724.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bc26c7ed31dd5ba46ca991ce96ac89f192215e8f --- /dev/null +++ b/cp/cp-10724.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10724", "name": "LeetCode 1291: Sequential Digits"} +{"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: Sequential Digits (Difficulty: Medium)\nTags: Enumeration\n\nAn integer has sequential digits if and only if each digit in the number is one more than the previous digit.\nReturn a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.\n\nExample 1:\nInput: low = 100, high = 300\nOutput: [123,234]\n\nExample 2:\nInput: low = 1000, high = 13000\nOutput: [1234,2345,3456,4567,5678,6789,12345]\n\nConstraints:\n- 10 <= low <= high <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((8 + 1) * 8 / 2) = O(1)\n# Space: O(8) = O(1)\n\nimport collections\n\n\nclass Solution(object):\n def sequentialDigits(self, low, high):\n \"\"\"\n :type low: int\n :type high: int\n :rtype: List[int]\n \"\"\"\n result = []\n q = collections.deque(range(1, 9))\n while q:\n num = q.popleft()\n if num > high:\n continue\n if low <= num:\n result.append(num)\n if num%10+1 < 10:\n q.append(num*10+num%10+1)\n return result\n"}} diff --git a/cp/cp-10725.jsonl b/cp/cp-10725.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6fc317a5d433744aa781dcfe130eec378eb11cff --- /dev/null +++ b/cp/cp-10725.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10725", "name": "LeetCode 1292: Maximum Side Length Of A Square With Sum Less Than Or Equal To Threshold"} +{"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 Side Length of a Square with Sum Less than or Equal to Threshold (Difficulty: Medium)\nTags: Array, Binary Search, Matrix, Prefix Sum\n\nGiven a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.\n\nExample 1:\nInput: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4\nOutput: 2\nExplanation: The maximum side length of square with sum less than 4 is 2 as shown.\n\nExample 2:\nInput: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1\nOutput: 0\n\nConstraints:\n- m == mat.length\n- n == mat[i].length\n- 1 <= m, n <= 300\n- 0 <= mat[i][j] <= 10^4\n- 0 <= threshold <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n * log(min(m, n)))\n# Space: O(m * n)\n\nclass Solution(object):\n def maxSideLength(self, mat, threshold):\n \"\"\"\n :type mat: List[List[int]]\n :type threshold: int\n :rtype: int\n \"\"\"\n def check(dp, mid, threshold):\n for i in range(mid, len(dp)):\n for j in range(mid, len(dp[0])):\n if dp[i][j] - dp[i-mid][j] - dp[i][j-mid] + dp[i-mid][j-mid] <= threshold:\n return True\n return False\n \n dp = [[0 for _ in range(len(mat[0])+1)] for _ in range(len(mat)+1)]\n for i in range(1, len(mat)+1):\n for j in range(1, len(mat[0])+1):\n dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + mat[i-1][j-1]\n\n left, right = 0, min(len(mat), len(mat[0])+1)\n while left <= right:\n mid = left + (right-left)//2\n if not check(dp, mid, threshold):\n right = mid-1\n else:\n left = mid+1\n return right\n"}} diff --git a/cp/cp-10726.jsonl b/cp/cp-10726.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9257fae426273fb672a4201357346684e7ffcd0f --- /dev/null +++ b/cp/cp-10726.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10726", "name": "LeetCode 1293: Shortest Path In A Grid With Obstacles Elimination"} +{"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: Shortest Path in a Grid with Obstacles Elimination (Difficulty: Hard)\nTags: Array, Breadth-First Search, Matrix\n\nYou are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.\nReturn the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.\n\nExample 1:\nInput: grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1\nOutput: 6\nExplanation: \nThe shortest path without eliminating any obstacle is 10.\nThe shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).\n\nExample 2:\nInput: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1\nOutput: -1\nExplanation: We need to eliminate at least two obstacles to find such a walk.\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 40\n- 1 <= k <= m * n\n- grid[i][j] is either 0 or 1.\n- grid[0][0] == grid[m - 1][n - 1] == 0"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n * k)\n# Space: O(m * n)\n\n# A* Search Algorithm without heap\nclass Solution(object):\n def shortestPath(self, grid, k):\n \"\"\"\n :type grid: List[List[int]]\n :type k: int\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n def dot(a, b):\n return a[0]*b[0]+a[1]*b[1]\n\n def g(a, b):\n return abs(a[0]-b[0])+abs(a[1]-b[1])\n \n def a_star(grid, b, t, k):\n f, dh = g(b, t), 2\n closer, detour = [(b, k)], []\n lookup = {}\n while closer or detour:\n if not closer:\n f += dh\n closer, detour = detour, closer\n b, k = closer.pop()\n if b == t:\n return f\n if b in lookup and lookup[b] >= k:\n continue\n lookup[b] = k\n for dx, dy in directions:\n nb = (b[0]+dx, b[1]+dy)\n if not (0 <= nb[0] < len(grid) and 0 <= nb[1] < len(grid[0]) and\n (grid[nb[0]][nb[1]] == 0 or k > 0) and\n (nb not in lookup or lookup[nb] < k)):\n continue\n (closer if dot((dx, dy), (t[0]-b[0], t[1]-b[1])) > 0 else detour).append((nb, k-int(grid[nb[0]][nb[1]] == 1)))\n return -1\n\n return a_star(grid, (0, 0), (len(grid)-1, len(grid[0])-1), k)\n"}} diff --git a/cp/cp-10727.jsonl b/cp/cp-10727.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8371d9e8fa1bb23c5051a70cca59a7d54c0fdf8e --- /dev/null +++ b/cp/cp-10727.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10727", "name": "LeetCode 1295: Find Numbers With Even Number Of Digits"} +{"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 Numbers with Even Number of Digits (Difficulty: Easy)\nTags: Array, Math\n\nGiven an array nums of integers, return how many of them contain an even number of digits.\n\nExample 1:\nInput: nums = [12,345,2,6,7896]\nOutput: 2\nExplanation: \n12 contains 2 digits (even number of digits). \n345 contains 3 digits (odd number of digits). \n2 contains 1 digit (odd number of digits). \n6 contains 1 digit (odd number of digits). \n7896 contains 4 digits (even number of digits). \nTherefore only 12 and 7896 contain an even number of digits.\n\nExample 2:\nInput: nums = [555,901,482,1771]\nOutput: 1 \nExplanation: \nOnly 1771 contains an even number of digits.\n\nConstraints:\n- 1 <= nums.length <= 500\n- 1 <= nums[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlog(logm)), n the length of nums, m is the max value of nums\n# Space: O(logm)\n\nimport bisect\n\n\nclass Solution(object):\n def __init__(self):\n M = 10**5\n self.__lookup = [0]\n i = 10\n while i < M:\n self.__lookup.append(i)\n i *= 10\n self.__lookup.append(i)\n\n def findNumbers(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def digit_count(n):\n return bisect.bisect_right(self.__lookup, n)\n\n return sum(digit_count(n) % 2 == 0 for n in nums)\n \n\n# Time: O(nlogm), n the length of nums, m is the max value of nums\n# Space: O(logm)\nclass Solution2(object):\n def findNumbers(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def digit_count(n):\n result = 0\n while n:\n n //= 10\n result += 1\n return result\n\n return sum(digit_count(n) % 2 == 0 for n in nums)\n\n\n# Time: O(nlogm), n the length of nums, m is the max value of nums\n# Space: O(logm)\nclass Solution3(object):\n def findNumbers(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n return sum(len(str(n)) % 2 == 0 for n in nums)\n"}} diff --git a/cp/cp-10728.jsonl b/cp/cp-10728.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d3ddf1a8bb15b9bb15a3a55f53bd841970e60ab3 --- /dev/null +++ b/cp/cp-10728.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10728", "name": "LeetCode 1296: Divide Array In Sets Of K Consecutive 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: Divide Array in Sets of K Consecutive Numbers (Difficulty: Medium)\nTags: Array, Hash Table, Greedy, Sorting\n\nGiven an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers.\nReturn true if it is possible. Otherwise, return false.\n\nExample 1:\nInput: nums = [1,2,3,3,4,4,5,6], k = 4\nOutput: true\nExplanation: Array can be divided into [1,2,3,4] and [3,4,5,6].\n\nExample 2:\nInput: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3\nOutput: true\nExplanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].\n\nExample 3:\nInput: nums = [1,2,3,4], k = 3\nOutput: false\nExplanation: Each array should be divided in subarrays of size 3.\n\nConstraints:\n- 1 <= k <= nums.length <= 10^5\n- 1 <= nums[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def isPossibleDivide(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n count = collections.Counter(nums)\n for num in sorted(count.keys()):\n c = count[num]\n if not c:\n continue\n for i in range(num, num+k):\n if count[i] < c:\n return False\n count[i] -= c\n return True\n"}} diff --git a/cp/cp-10729.jsonl b/cp/cp-10729.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8ef7c7b019d00e1e0df4e67e8ec0601ee5c2ea24 --- /dev/null +++ b/cp/cp-10729.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10729", "name": "LeetCode 1297: Maximum Number Of Occurrences Of A Substring"} +{"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 Number of Occurrences of a Substring (Difficulty: Medium)\nTags: Hash Table, String, Sliding Window\n\nGiven a string s, return the maximum number of occurrences of any substring under the following rules:\n\nExample 1:\nInput: s = \"aababcaab\", maxLetters = 2, minSize = 3, maxSize = 4\nOutput: 2\nExplanation: Substring \"aab\" has 2 occurrences in the original string.\nIt satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).\n\nExample 2:\nInput: s = \"aaaa\", maxLetters = 1, minSize = 3, maxSize = 3\nOutput: 2\nExplanation: Substring \"aaa\" occur 2 times in the string. It can overlap.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- 1 <= maxLetters <= 26\n- 1 <= minSize <= maxSize <= min(26, s.length)\n- s consists of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\n# rolling hash (Rabin-Karp Algorithm)\nclass Solution(object):\n def maxFreq(self, s, maxLetters, minSize, maxSize):\n \"\"\"\n :type s: str\n :type maxLetters: int\n :type minSize: int\n :type maxSize: int\n :rtype: int\n \"\"\"\n M, p = 10**9+7, 113\n power, rolling_hash = pow(p, minSize-1, M), 0\n\n left = 0\n lookup, count = collections.defaultdict(int), collections.defaultdict(int)\n for right in range(len(s)):\n count[s[right]] += 1\n if right-left+1 > minSize:\n count[s[left]] -= 1\n rolling_hash = (rolling_hash - ord(s[left])*power) % M\n if count[s[left]] == 0:\n count.pop(s[left])\n left += 1\n rolling_hash = (rolling_hash*p + ord(s[right])) % M\n if right-left+1 == minSize and len(count) <= maxLetters:\n lookup[rolling_hash] += 1\n return max(lookup.values() or [0])\n\n\n# Time: O(m * n), m = 26\n# Space: O(m * n)\nclass Solution2(object):\n def maxFreq(self, s, maxLetters, minSize, maxSize):\n \"\"\"\n :type s: str\n :type maxLetters: int\n :type minSize: int\n :type maxSize: int\n :rtype: int\n \"\"\"\n lookup = {}\n for right in range(minSize-1, len(s)):\n word = s[right-minSize+1:right+1]\n if word in lookup:\n lookup[word] += 1\n elif len(collections.Counter(word)) <= maxLetters:\n lookup[word] = 1\n return max(lookup.values() or [0])\n"}} diff --git a/cp/cp-10730.jsonl b/cp/cp-10730.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4f6b7f5c80f51be0c7fd5521992d17fa2e96ff6c --- /dev/null +++ b/cp/cp-10730.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10730", "name": "LeetCode 1298: Maximum Candies You Can Get From Boxes"} +{"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 Candies You Can Get from Boxes (Difficulty: Hard)\nTags: Array, Breadth-First Search, Graph\n\nYou have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and containedBoxes where:\nYou are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.\nReturn the maximum number of candies you can get following the rules above.\n\nExample 1:\nInput: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]\nOutput: 16\nExplanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2.\nBox 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.\nIn box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.\nTotal number of candies collected = 7 + 4 + 5 = 16 candy.\n\nExample 2:\nInput: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]\nOutput: 6\nExplanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys.\nThe total number of candies will be 6.\n\nConstraints:\n- n == status.length == candies.length == keys.length == containedBoxes.length\n- 1 <= n <= 1000\n- status[i] is either 0 or 1.\n- 1 <= candies[i] <= 1000\n- 0 <= keys[i].length <= n\n- 0 <= keys[i][j] < n\n- All values of keys[i] are unique.\n- 0 <= containedBoxes[i].length <= n\n- 0 <= containedBoxes[i][j] < n\n- All values of containedBoxes[i] are unique.\n- Each box is contained in one box at most.\n- 0 <= initialBoxes.length <= n\n- 0 <= initialBoxes[i] < n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def maxCandies(self, status, candies, keys, containedBoxes, initialBoxes):\n \"\"\"\n :type status: List[int]\n :type candies: List[int]\n :type keys: List[List[int]]\n :type containedBoxes: List[List[int]]\n :type initialBoxes: List[int]\n :rtype: int\n \"\"\"\n result = 0\n q = collections.deque(initialBoxes)\n while q:\n changed = False\n for _ in range(len(q)):\n box = q.popleft()\n if not status[box]:\n q.append(box)\n continue\n changed = True\n result += candies[box]\n for contained_key in keys[box]:\n status[contained_key] = 1\n for contained_box in containedBoxes[box]:\n q.append(contained_box)\n if not changed:\n break\n return result\n"}} diff --git a/cp/cp-10731.jsonl b/cp/cp-10731.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3bc4232878f0497969aee935a2a90adf9f5687ae --- /dev/null +++ b/cp/cp-10731.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10731", "name": "LeetCode 1299: Replace Elements With Greatest Element On Right Side"} +{"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 Elements with Greatest Element on Right Side (Difficulty: Easy)\nTags: Array\n\nGiven an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.\nAfter doing so, return the array.\n\nExample 1:\nInput: arr = [17,18,5,4,6,1]\nOutput: [18,6,6,6,1,-1]\nExplanation: \n- index 0 --> the greatest element to the right of index 0 is index 1 (18).\n- index 1 --> the greatest element to the right of index 1 is index 4 (6).\n- index 2 --> the greatest element to the right of index 2 is index 4 (6).\n- index 3 --> the greatest element to the right of index 3 is index 4 (6).\n- index 4 --> the greatest element to the right of index 4 is index 5 (1).\n- index 5 --> there are no elements to the right of index 5, so we put -1.\n\nExample 2:\nInput: arr = [400]\nOutput: [-1]\nExplanation: There are no elements to the right of index 0.\n\nConstraints:\n- 1 <= arr.length <= 10^4\n- 1 <= arr[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def replaceElements(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: List[int]\n \"\"\"\n curr_max = -1\n for i in reversed(range(len(arr))):\n arr[i], curr_max = curr_max, max(curr_max, arr[i])\n return arr\n"}} diff --git a/cp/cp-10732.jsonl b/cp/cp-10732.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3ecbc48cd3bfd42072aa068d27cef8d1d23709a1 --- /dev/null +++ b/cp/cp-10732.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10732", "name": "LeetCode 1300: Sum Of Mutated Array Closest To Target"} +{"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 Mutated Array Closest to Target (Difficulty: Medium)\nTags: Array, Binary Search, Sorting\n\nGiven an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target.\nIn case of a tie, return the minimum such integer.\nNotice that the answer is not neccesarilly a number from arr.\n\nExample 1:\nInput: arr = [4,9,3], target = 10\nOutput: 3\nExplanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.\n\nExample 2:\nInput: arr = [2,3,5], target = 10\nOutput: 5\n\nExample 3:\nInput: arr = [60864,25176,27249,21296,20204], target = 56803\nOutput: 11361\n\nConstraints:\n- 1 <= arr.length <= 10^4\n- 1 <= arr[i], target <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def findBestValue(self, arr, target):\n \"\"\"\n :type arr: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n arr.sort(reverse=True)\n max_arr = arr[0]\n while arr and arr[-1]*len(arr) <= target:\n target -= arr.pop()\n # let x = ceil(t/n)-1\n # (1) (t/n-1/2) <= x:\n # return x, which is equal to ceil(t/n)-1 = ceil(t/n-1/2) = (2t+n-1)//2n\n # (2) (t/n-1/2) > x:\n # return x+1, which is equal to ceil(t/n) = ceil(t/n-1/2) = (2t+n-1)//2n\n # (1) + (2) => both return (2t+n-1)//2n\n return max_arr if not arr else (2*target+len(arr)-1)//(2*len(arr))\n\n\n# Time: O(nlogn)\n# Space: O(1)\nclass Solution2(object):\n def findBestValue(self, arr, target):\n \"\"\"\n :type arr: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n arr.sort(reverse=True)\n max_arr = arr[0]\n while arr and arr[-1]*len(arr) <= target:\n target -= arr.pop()\n if not arr:\n return max_arr\n x = (target-1)//len(arr)\n return x if target-x*len(arr) <= (x+1)*len(arr)-target else x+1\n\n\n# Time: O(nlogm), m is the max of arr, which may be larger than n\n# Space: O(1)\nclass Solution3(object):\n def findBestValue(self, arr, target):\n \"\"\"\n :type arr: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n def total(arr, v):\n result = 0\n for x in arr:\n result += min(v, x)\n return result\n\n def check(arr, v, target):\n return total(arr, v) >= target\n \n left, right = 1, max(arr)\n while left <= right:\n mid = left + (right-left)//2\n if check(arr, mid, target):\n right = mid-1\n else:\n left = mid+1\n return left-1 if target-total(arr, left-1) <= total(arr, left)-target else left\n"}} diff --git a/cp/cp-10733.jsonl b/cp/cp-10733.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..737bcc6751bb352bbc2ece479f274da0044c6617 --- /dev/null +++ b/cp/cp-10733.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10733", "name": "LeetCode 1301: Number Of Paths With Max Score"} +{"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 Paths with Max Score (Difficulty: Hard)\nTags: Array, Dynamic Programming, Matrix\n\nYou are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S'.\nYou need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.\nReturn a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.\nIn case there is no path, return [0, 0].\n\nExample 1:\nInput: board = [\"E23\",\"2X2\",\"12S\"]\r\nOutput: [7,1]\n\nExample 2:\nInput: board = [\"E12\",\"1X1\",\"21S\"]\r\nOutput: [4,2]\n\nExample 3:\nInput: board = [\"E11\",\"XXX\",\"11S\"]\r\nOutput: [0,0]\n\nConstraints:\n- 2 <= board.length == board[i].length <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def pathsWithMaxScore(self, board):\n \"\"\"\n :type board: List[str]\n :rtype: List[int]\n \"\"\"\n MOD = 10**9+7\n directions = [[1, 0], [0, 1], [1, 1]]\n dp = [[[0, 0] for r in range(len(board[0])+1)]\n for r in range(2)]\n dp[(len(board)-1)%2][len(board[0])-1] = [0, 1]\n for r in reversed(range(len(board))):\n for c in reversed(range(len(board[0]))):\n if board[r][c] in \"XS\":\n continue\n dp[r%2][c] = [0, 0]\n for dr, dc in directions:\n if dp[r%2][c][0] < dp[(r+dr)%2][c+dc][0]:\n dp[r%2][c] = dp[(r+dr)%2][c+dc][:]\n elif dp[r%2][c][0] == dp[(r+dr)%2][c+dc][0]:\n dp[r%2][c][1] = (dp[r%2][c][1]+dp[(r+dr)%2][c+dc][1]) % MOD\n if dp[r%2][c][1] and board[r][c] != 'E':\n dp[r%2][c][0] += int(board[r][c])\n return dp[0][0]\n"}} diff --git a/cp/cp-10734.jsonl b/cp/cp-10734.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..41efd0b9b49da6380ddaff8d416d1ab285532025 --- /dev/null +++ b/cp/cp-10734.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10734", "name": "LeetCode 1302: Deepest Leaves Sum"} +{"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: Deepest Leaves Sum (Difficulty: Medium)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nExample 1:\nInput: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]\nOutput: 15\n\nExample 2:\nInput: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput: 19\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 104].\n- 1 <= Node.val <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(w)\n\n# Definition for a binary tree node.\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 deepestLeavesSum(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n curr = [root]\n while curr:\n prev, curr = curr, [child for p in curr for child in [p.left, p.right] if child]\n return sum(node.val for node in prev)\n"}} diff --git a/cp/cp-10736.jsonl b/cp/cp-10736.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d836bfe7379b289ec557fd05dd4f0541c1f3ef0b --- /dev/null +++ b/cp/cp-10736.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10736", "name": "LeetCode 1305: All Elements In Two Binary Search 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: All Elements in Two Binary Search Trees (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Search Tree, Sorting, Binary Tree\n\nGiven two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.\n\nExample 1:\nInput: root1 = [2,1,4], root2 = [1,0,3]\nOutput: [0,1,1,2,3,4]\n\nExample 2:\nInput: root1 = [1,null,8], root2 = [8,1]\nOutput: [1,1,8,8]\n\nConstraints:\n- The number of nodes in each tree is in the range [0, 5000].\n- -10^5 <= Node.val <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 getAllElements(self, root1, root2):\n \"\"\"\n :type root1: TreeNode\n :type root2: TreeNode\n :rtype: List[int]\n \"\"\"\n def inorder_gen(root):\n result, stack = [], [(root, False)]\n while stack:\n root, is_visited = stack.pop()\n if root is None:\n continue\n if is_visited:\n yield root.val\n else:\n stack.append((root.right, False))\n stack.append((root, True))\n stack.append((root.left, False))\n yield None\n \n result = []\n left_gen, right_gen = inorder_gen(root1), inorder_gen(root2)\n left, right = next(left_gen), next(right_gen)\n while left is not None or right is not None:\n if right is None or (left is not None and left < right):\n result.append(left)\n left = next(left_gen)\n else:\n result.append(right)\n right = next(right_gen)\n return result\n \n"}} diff --git a/cp/cp-10737.jsonl b/cp/cp-10737.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5ae53a39230bee2e75353445ef1740fbdc3900dd --- /dev/null +++ b/cp/cp-10737.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10737", "name": "LeetCode 1306: Jump Game 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: Jump Game III (Difficulty: Medium)\nTags: Array, Depth-First Search, Breadth-First Search\n\nGiven an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach any index with value 0.\nNotice that you can not jump outside of the array at any time.\n\nExample 1:\nInput: arr = [4,2,3,0,3,1,2], start = 5\nOutput: true\nExplanation: \nAll possible ways to reach at index 3 with value 0 are: \nindex 5 -> index 4 -> index 1 -> index 3 \nindex 5 -> index 6 -> index 4 -> index 1 -> index 3\n\nExample 2:\nInput: arr = [4,2,3,0,3,1,2], start = 0\nOutput: true \nExplanation: \nOne possible way to reach at index 3 with value 0 is: \nindex 0 -> index 4 -> index 1 -> index 3\n\nExample 3:\nInput: arr = [3,0,2,1,2], start = 2\nOutput: false\nExplanation: There is no way to reach at index 1 with value 0.\n\nConstraints:\n- 1 <= arr.length <= 5 * 10^4\n- 0 <= arr[i] < arr.length\n- 0 <= start < arr.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def canReach(self, arr, start):\n \"\"\"\n :type arr: List[int]\n :type start: int\n :rtype: bool\n \"\"\"\n q, lookup = collections.deque([start]), set([start])\n while q:\n i = q.popleft()\n if not arr[i]:\n return True\n for j in [i-arr[i], i+arr[i]]:\n if 0 <= j < len(arr) and j not in lookup:\n lookup.add(j)\n q.append(j) \n return False\n"}} diff --git a/cp/cp-10738.jsonl b/cp/cp-10738.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ee0aeff85215a06d7402961413ce5a138071ba63 --- /dev/null +++ b/cp/cp-10738.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10738", "name": "LeetCode 1307: Verbal Arithmetic Puzzle"} +{"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: Verbal Arithmetic Puzzle (Difficulty: Hard)\nTags: Array, Math, String, Backtracking\n\nGiven an equation, represented by words on the left side and the result on the right side.\nYou need to check if the equation is solvable under the following rules:\nReturn true if the equation is solvable, otherwise return false.\n\nExample 1:\nInput: words = [\"SEND\",\"MORE\"], result = \"MONEY\"\nOutput: true\nExplanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'\nSuch that: \"SEND\" + \"MORE\" = \"MONEY\" , 9567 + 1085 = 10652\n\nExample 2:\nInput: words = [\"SIX\",\"SEVEN\",\"SEVEN\"], result = \"TWENTY\"\nOutput: true\nExplanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4\nSuch that: \"SIX\" + \"SEVEN\" + \"SEVEN\" = \"TWENTY\" , 650 + 68782 + 68782 = 138214\n\nExample 3:\nInput: words = [\"LEET\",\"CODE\"], result = \"POINT\"\nOutput: false\nExplanation: There is no possible mapping to satisfy the equation, so we return false.\nNote that two different characters cannot map to the same digit.\n\nConstraints:\n- 2 <= words.length <= 5\n- 1 <= words[i].length, result.length <= 7\n- words[i], result contain only uppercase English letters.\n- The number of different characters used in the expression is at most 10."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(10! * n * l)\n# Space: O(n * l)\n\nimport collections\n\n\nclass Solution(object):\n def isSolvable(self, words, result):\n \"\"\"\n :type words: List[str]\n :type result: str\n :rtype: bool\n \"\"\"\n def backtracking(words, result, i, j, carry, lookup, used):\n if j == len(result):\n return carry == 0\n\n if i != len(words):\n if j >= len(words[i]) or words[i][j] in lookup:\n return backtracking(words, result, i+1, j, carry, lookup, used) \n for val in range(10):\n if val in used or (val == 0 and j == len(words[i])-1):\n continue\n lookup[words[i][j]] = val\n used.add(val)\n if backtracking(words, result, i+1, j, carry, lookup, used):\n return True\n used.remove(val)\n del lookup[words[i][j]]\n return False\n\n carry, val = divmod(carry + sum(lookup[w[j]] for w in words if j < len(w)), 10)\n if result[j] in lookup:\n return val == lookup[result[j]] and \\\n backtracking(words, result, 0, j+1, carry, lookup, used)\n if val in used or (val == 0 and j == len(result)-1):\n return False\n lookup[result[j]] = val\n used.add(val)\n if backtracking(words, result, 0, j+1, carry, lookup, used):\n return True\n used.remove(val)\n del lookup[result[j]]\n return False\n \n return backtracking([w[::-1] for w in words], result[::-1], 0, 0, 0, {}, set())\n"}} diff --git a/cp/cp-10739.jsonl b/cp/cp-10739.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..325a7c72a25612159992d371d56318086b26a71e --- /dev/null +++ b/cp/cp-10739.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10739", "name": "LeetCode 1309: Decrypt String From Alphabet To Integer Mapping"} +{"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: Decrypt String from Alphabet to Integer Mapping (Difficulty: Easy)\nTags: String\n\nYou are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows:\nReturn the string formed after mapping.\nThe test cases are generated so that a unique mapping will always exist.\n\nExample 1:\nInput: s = \"10#11#12\"\nOutput: \"jkab\"\nExplanation: \"j\" -> \"10#\" , \"k\" -> \"11#\" , \"a\" -> \"1\" , \"b\" -> \"2\".\n\nExample 2:\nInput: s = \"1326#\"\nOutput: \"acz\"\n\nConstraints:\n- 1 <= s.length <= 1000\n- s consists of digits and the '#' letter.\n- s will be a valid string such that mapping is always possible."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# forward solution\nclass Solution(object):\n def freqAlphabets(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n def alpha(num):\n return chr(ord('a') + int(num)-1)\n\n i = 0\n result = []\n while i < len(s):\n if i+2 < len(s) and s[i+2] == '#':\n result.append(alpha(s[i:i+2]))\n i += 3\n else:\n result.append(alpha(s[i]))\n i += 1\n return \"\".join(result)\n\n\n# Time: O(n)\n# Space: O(1)\n# backward solution\nclass Solution2(object):\n def freqAlphabets(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n def alpha(num):\n return chr(ord('a') + int(num)-1)\n\n i = len(s)-1\n result = []\n while i >= 0:\n if s[i] == '#':\n result.append(alpha(s[i-2:i]))\n i -= 3\n else:\n result.append(alpha(s[i]))\n i -= 1\n return \"\".join(reversed(result))\n\n# Time: O(n)\n# Space: O(1)\nimport re\n\n\n# regex solution\nclass Solution3(object):\n def freqAlphabets(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n def alpha(num):\n return chr(ord('a') + int(num)-1)\n\n return \"\".join(alpha(i[:2]) for i in re.findall(r\"\\d\\d#|\\d\", s))\n"}} diff --git a/cp/cp-10740.jsonl b/cp/cp-10740.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5b84598e46a42d740ee8f4cc5774b007343be2a7 --- /dev/null +++ b/cp/cp-10740.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10740", "name": "LeetCode 1310: Xor Queries Of A Subarray"} +{"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: XOR Queries of a Subarray (Difficulty: Medium)\nTags: Array, Bit Manipulation, Prefix Sum\n\nYou are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti].\nFor each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ).\nReturn an array answer where answer[i] is the answer to the ith query.\n\nExample 1:\nInput: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]\nOutput: [2,7,14,8] \nExplanation: \nThe binary representation of the elements in the array are:\n1 = 0001 \n3 = 0011 \n4 = 0100 \n8 = 1000 \nThe XOR values for queries are:\n[0,1] = 1 xor 3 = 2 \n[1,2] = 3 xor 4 = 7 \n[0,3] = 1 xor 3 xor 4 xor 8 = 14 \n[3,3] = 8\n\nExample 2:\nInput: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]\nOutput: [8,0,4,4]\n\nConstraints:\n- 1 <= arr.length, queries.length <= 3 * 10^4\n- 1 <= arr[i] <= 10^9\n- queries[i].length == 2\n- 0 <= lefti <= righti < arr.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def xorQueries(self, arr, queries):\n \"\"\"\n :type arr: List[int]\n :type queries: List[List[int]]\n :rtype: List[int]\n \"\"\"\n for i in range(1, len(arr)):\n arr[i] ^= arr[i-1]\n return [arr[right] ^ arr[left-1] if left else arr[right] for left, right in queries]\n"}} diff --git a/cp/cp-10741.jsonl b/cp/cp-10741.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d2bb857a83411ee3046345ae15dd703c5e4ea471 --- /dev/null +++ b/cp/cp-10741.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10741", "name": "LeetCode 1311: Get Watched Videos By Your Friends"} +{"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: Get Watched Videos by Your Friends (Difficulty: Medium)\nTags: Array, Hash Table, Breadth-First Search, Graph, Sorting\n\nThere are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i.\nLevel 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.\n\nExample 1:\nInput: watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1\nOutput: [\"B\",\"C\"] \nExplanation: \nYou have id = 0 (green color in the figure) and your friends are (yellow color in the figure):\nPerson with id = 1 -> watchedVideos = [\"C\"] \nPerson with id = 2 -> watchedVideos = [\"B\",\"C\"] \nThe frequencies of watchedVideos by your friends are: \nB -> 1 \nC -> 2\n\nExample 2:\nInput: watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2\nOutput: [\"D\"]\nExplanation: \nYou have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).\n\nConstraints:\n- n == watchedVideos.length == friends.length\n- 2 <= n <= 100\n- 1 <= watchedVideos[i].length <= 100\n- 1 <= watchedVideos[i][j].length <= 8\n- 0 <= friends[i].length < n\n- 0 <= friends[i][j] < n\n- 0 <= id < n\n- 1 <= level < n\n- if friends[i] contains j, then friends[j] contains i"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + vlogv), v is the number of the level videos\n# Space: O(w)\n\nimport collections\n\n\nclass Solution(object):\n def watchedVideosByFriends(self, watchedVideos, friends, id, level):\n \"\"\"\n :type watchedVideos: List[List[str]]\n :type friends: List[List[int]]\n :type id: int\n :type level: int\n :rtype: List[str]\n \"\"\"\n curr_level, lookup = set([id]), set([id])\n for _ in range(level):\n curr_level = set(j for i in curr_level for j in friends[i] if j not in lookup)\n lookup |= curr_level\n count = collections.Counter([v for i in curr_level for v in watchedVideos[i]])\n return sorted(count.keys(), key=lambda x: (count[x], x))\n"}} diff --git a/cp/cp-10742.jsonl b/cp/cp-10742.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..23b4859be0cd613ef366be8c916eb6fb50f9d287 --- /dev/null +++ b/cp/cp-10742.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10742", "name": "LeetCode 1312: Minimum Insertion Steps To Make A String Palindrome"} +{"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: Minimum Insertion Steps to Make a String Palindrome (Difficulty: Hard)\nTags: String, Dynamic Programming\n\nGiven a string s. In one step you can insert any character at any index of the string.\nReturn the minimum number of steps to make s palindrome.\nA Palindrome String is one that reads the same backward as well as forward.\n\nExample 1:\nInput: s = \"zzazz\"\nOutput: 0\nExplanation: The string \"zzazz\" is already palindrome we do not need any insertions.\n\nExample 2:\nInput: s = \"mbadm\"\nOutput: 2\nExplanation: String can be \"mbdadbm\" or \"mdbabdm\".\n\nExample 3:\nInput: s = \"leetcode\"\nOutput: 5\nExplanation: Inserting 5 characters the string becomes \"leetcodocteel\".\n\nConstraints:\n- 1 <= s.length <= 500\n- s consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def minInsertions(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n def longestCommonSubsequence(text1, text2):\n if len(text1) < len(text2):\n return self.longestCommonSubsequence(text2, text1)\n dp = [[0 for _ in range(len(text2)+1)] for _ in range(2)]\n for i in range(1, len(text1)+1):\n for j in range(1, len(text2)+1):\n dp[i%2][j] = dp[(i-1)%2][j-1]+1 if text1[i-1] == text2[j-1] \\\n else max(dp[(i-1)%2][j], dp[i%2][j-1])\n return dp[len(text1)%2][len(text2)]\n\n return len(s)-longestCommonSubsequence(s, s[::-1])\n"}} diff --git a/cp/cp-10744.jsonl b/cp/cp-10744.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0ca86d30c82fe1eb86e0fcff4d29050df582ca63 --- /dev/null +++ b/cp/cp-10744.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10744", "name": "LeetCode 1314: Matrix Block Sum"} +{"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: Matrix Block Sum (Difficulty: Medium)\nTags: Array, Matrix, Prefix Sum\n\nGiven a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:\n\nExample 1:\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1\nOutput: [[12,21,16],[27,45,33],[24,39,28]]\n\nExample 2:\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2\nOutput: [[45,45,45],[45,45,45],[45,45,45]]\n\nConstraints:\n- m == mat.length\n- n == mat[i].length\n- 1 <= m, n, k <= 100\n- 1 <= mat[i][j] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m * n)\n\nclass Solution(object):\n def matrixBlockSum(self, mat, K):\n \"\"\"\n :type mat: List[List[int]]\n :type K: int\n :rtype: List[List[int]]\n \"\"\"\n m, n = len(mat), len(mat[0])\n accu = [[0 for _ in range(n+1)] for _ in range(m+1)]\n for i in range(m):\n for j in range(n):\n accu[i+1][j+1] = accu[i+1][j]+accu[i][j+1]-accu[i][j]+mat[i][j]\n result = [[0 for _ in range(n)] for _ in range(m)] \n for i in range(m):\n for j in range(n):\n r1, c1, r2, c2 = max(i-K, 0), max(j-K, 0), min(i+K+1, m), min(j+K+1, n)\n result[i][j] = accu[r2][c2]-accu[r1][c2]-accu[r2][c1]+accu[r1][c1]\n return result\n"}} diff --git a/cp/cp-10745.jsonl b/cp/cp-10745.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b73458faa9a2d650b50011854702f28b80d21049 --- /dev/null +++ b/cp/cp-10745.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10745", "name": "LeetCode 1315: Sum Of Nodes With Even Valued Grandparent"} +{"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 Nodes with Even-Valued Grandparent (Difficulty: Medium)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0.\nA grandparent of a node is the parent of its parent if it exists.\n\nExample 1:\nInput: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput: 18\nExplanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.\n\nExample 2:\nInput: root = [1]\nOutput: 0\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 104].\n- 1 <= Node.val <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 sumEvenGrandparent(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def sumEvenGrandparentHelper(root, p, gp):\n return sumEvenGrandparentHelper(root.left, root.val, p) + \\\n sumEvenGrandparentHelper(root.right, root.val, p) + \\\n (root.val if gp is not None and gp % 2 == 0 else 0) if root else 0\n\n return sumEvenGrandparentHelper(root, None, None)\n"}} diff --git a/cp/cp-10746.jsonl b/cp/cp-10746.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..79c7dd370dc7c3c35181765fc1d4ed9bcc03b1ee --- /dev/null +++ b/cp/cp-10746.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10746", "name": "LeetCode 1316: Distinct Echo 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: Distinct Echo Substrings (Difficulty: Hard)\nTags: String, Trie, Rolling Hash, Hash Function\n\nReturn the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).\n\nExample 1:\nInput: text = \"abcabcabc\"\nOutput: 3\nExplanation: The 3 substrings are \"abcabc\", \"bcabca\" and \"cabcab\".\n\nExample 2:\nInput: text = \"leetcodeleetcode\"\nOutput: 2\nExplanation: The 2 substrings are \"ee\" and \"leetcodeleetcode\".\n\nConstraints:\n- 1 <= text.length <= 2000\n- text has only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2 + d), d is the duplicated of result substrings size\n# Space: O(r), r is the size of result substrings set\n\nclass Solution(object):\n def distinctEchoSubstrings(self, text):\n \"\"\"\n :type text: str\n :rtype: int\n \"\"\"\n def KMP(text, l, result):\n prefix = [-1]*(len(text)-l)\n j = -1\n for i in range(1, len(prefix)):\n while j > -1 and text[l+j+1] != text[l+i]:\n j = prefix[j]\n if text[l+j+1] == text[l+i]:\n j += 1\n prefix[i] = j\n if (j+1) and (i+1) % ((i+1) - (j+1)) == 0 and \\\n (i+1) // ((i+1) - (j+1)) % 2 == 0:\n result.add(text[l:l+i+1])\n return len(prefix)-(prefix[-1]+1) \\\n if prefix[-1]+1 and len(prefix) % (len(prefix)-(prefix[-1]+1)) == 0 \\\n else float(\"inf\")\n\n result = set()\n i, l = 0, len(text)-1\n while i < l: # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcdefabcdefabcdef\n l = min(l, i + KMP(text, i, result))\n i += 1\n return len(result)\n\n\n# Time: O(n^2 + d), d is the duplicated of result substrings size\n# Space: O(r), r is the size of result substrings set\nclass Solution2(object):\n def distinctEchoSubstrings(self, text):\n \"\"\"\n :type text: str\n :rtype: int\n \"\"\"\n result = set()\n for l in range(1, len(text)//2+1):\n count = sum(text[i] == text[i+l] for i in range(l))\n for i in range(len(text)-2*l):\n if count == l:\n result.add(text[i:i+l])\n count += (text[i+l] == text[i+l+l]) - (text[i] == text[i+l])\n if count == l:\n result.add(text[len(text)-2*l:len(text)-2*l+l])\n return len(result)\n\n\n# Time: O(n^2 + d), d is the duplicated of result substrings size\n# Space: O(r), r is the size of result substrings set\nclass Solution3(object):\n def distinctEchoSubstrings(self, text):\n \"\"\"\n :type text: str\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n D = 27 # a-z and ''\n result = set()\n for i in range(len(text)-1):\n left, right, pow_D = 0, 0, 1\n for l in range(1, min(i+2, len(text)-i)):\n left = (D*left + (ord(text[i-l+1])-ord('a')+1)) % MOD\n right = (pow_D*(ord(text[i+l])-ord('a')+1) + right) % MOD\n if left == right: # assumed no collision\n result.add(left)\n pow_D = (pow_D*D) % MOD \n return len(result)\n\n\n# Time: O(n^3 + d), d is the duplicated of result substrings size\n# Space: O(r), r is the size of result substrings set\nclass Solution_TLE(object):\n def distinctEchoSubstrings(self, text):\n \"\"\"\n :type text: str\n :rtype: int\n \"\"\"\n def compare(text, l, s1, s2):\n for i in range(l):\n if text[s1+i] != text[s2+i]:\n return False\n return True\n\n MOD = 10**9+7\n D = 27 # a-z and ''\n result = set()\n for i in range(len(text)):\n left, right, pow_D = 0, 0, 1\n for l in range(1, min(i+2, len(text)-i)):\n left = (D*left + (ord(text[i-l+1])-ord('a')+1)) % MOD\n right = (pow_D*(ord(text[i+l])-ord('a')+1) + right) % MOD\n if left == right and compare(text, l, i-l+1, i+1):\n result.add(text[i+1:i+1+l])\n pow_D = (pow_D*D) % MOD \n return len(result)\n"}} diff --git a/cp/cp-10747.jsonl b/cp/cp-10747.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..366efea83daff43be7d67fd99a69a36d7e55cdb5 --- /dev/null +++ b/cp/cp-10747.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10747", "name": "LeetCode 1317: Convert Integer To The Sum Of Two No Zero Integers"} +{"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: Convert Integer to the Sum of Two No-Zero Integers (Difficulty: Easy)\nTags: Math\n\nNo-Zero integer is a positive integer that does not contain any 0 in its decimal representation.\nGiven an integer n, return a list of two integers [a, b] where:\nThe test cases are generated so that there is at least one valid solution. If there are many valid solutions, you can return any of them.\n\nExample 1:\nInput: n = 2\nOutput: [1,1]\nExplanation: Let a = 1 and b = 1.\nBoth a and b are no-zero integers, and a + b = 2 = n.\n\nExample 2:\nInput: n = 11\nOutput: [2,9]\nExplanation: Let a = 2 and b = 9.\nBoth a and b are no-zero integers, and a + b = 11 = n.\nNote that there are other valid answers as [8, 3] that can be accepted.\n\nConstraints:\n- 2 <= n <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nclass Solution(object):\n def getNoZeroIntegers(self, n):\n \"\"\"\n :type n: int\n :rtype: List[int]\n \"\"\"\n a, curr, base = 0, n, 1\n while curr: \n if curr % 10 == 0 or (curr % 10 == 1 and curr != 1):\n a += base\n curr -= 10 # carry\n a += base\n base *= 10\n curr //= 10\n return [a, n-a]\n\n\n# Time: O(nlogn)\n# Space: O(logn)\nclass Solution2(object):\n def getNoZeroIntegers(self, n):\n \"\"\"\n :type n: int\n :rtype: List[int]\n \"\"\"\n return next([a, n-a] for a in range(1, n) if '0' not in '{}{}'.format(a, n-a))\n"}} diff --git a/cp/cp-10748.jsonl b/cp/cp-10748.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b31cd4411aec99abf11c9340ddedc8e2904f02ed --- /dev/null +++ b/cp/cp-10748.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10748", "name": "LeetCode 1318: Minimum Flips To Make A Or B Equal To C"} +{"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: Minimum Flips to Make a OR b Equal to c (Difficulty: Medium)\nTags: Bit Manipulation\n\nGiven 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).\r\nFlip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.\n\nExample 1:\nInput: a = 2, b = 6, c = 5\r\nOutput: 3\r\nExplanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)\n\nExample 2:\nInput: a = 4, b = 2, c = 7\r\nOutput: 1\n\nExample 3:\nInput: a = 1, b = 2, c = 3\r\nOutput: 0\n\nConstraints:\n- 1 <= a <= 10^9\n- 1 <= b <= 10^9\n- 1 <= c <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(31)\n# Space: O(1)\n\nclass Solution(object):\n def minFlips(self, a, b, c):\n \"\"\"\n :type a: int\n :type b: int\n :type c: int\n :rtype: int\n \"\"\"\n def number_of_1_bits(n):\n result = 0\n while n:\n n &= n-1\n result += 1\n return result\n\n return number_of_1_bits((a|b)^c) + number_of_1_bits(a&b&~c)\n\n\n# Time: O(31)\n# Space: O(1)\nclass Solution2(object):\n def minFlips(self, a, b, c):\n \"\"\"\n :type a: int\n :type b: int\n :type c: int\n :rtype: int\n \"\"\"\n result = 0\n for i in range(31):\n a_i, b_i, c_i = map(lambda x: x&1, [a, b, c])\n if (a_i | b_i) != c_i:\n result += 2 if a_i == b_i == 1 else 1\n a, b, c = a >> 1, b >> 1, c >> 1\n return result\n"}} diff --git a/cp/cp-10749.jsonl b/cp/cp-10749.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0f16106efc3c709f537ae228f9f25b27215cdc7d --- /dev/null +++ b/cp/cp-10749.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10749", "name": "LeetCode 1319: Number Of Operations To Make Network Connected"} +{"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 Operations to Make Network Connected (Difficulty: Medium)\nTags: Depth-First Search, Breadth-First Search, Union Find, Graph\n\nThere are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.\nYou are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.\nReturn the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.\n\nExample 1:\nInput: n = 4, connections = [[0,1],[0,2],[1,2]]\nOutput: 1\nExplanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.\n\nExample 2:\nInput: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]\nOutput: 2\n\nExample 3:\nInput: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]\nOutput: -1\nExplanation: There are not enough cables.\n\nConstraints:\n- 1 <= n <= 10^5\n- 1 <= connections.length <= min(n * (n - 1) / 2, 105)\n- connections[i].length == 2\n- 0 <= ai, bi < n\n- ai != bi\n- There are no repeated connections.\n- No two computers are connected by more than one cable."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(|E| + |V|)\n# Space: O(|V|)\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n self.count = n\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[max(x_root, y_root)] = min(x_root, y_root)\n self.count -= 1\n return True\n\n\nclass Solution(object):\n def makeConnected(self, n, connections):\n \"\"\"\n :type n: int\n :type connections: List[List[int]]\n :rtype: int\n \"\"\"\n if len(connections) < n-1:\n return -1\n union_find = UnionFind(n)\n for i, j in connections:\n union_find.union_set(i, j)\n return union_find.count - 1\n\n\n# Time: O(|E| + |V|)\n# Space: O(|V|)\nimport collections\n\n\nclass Solution2(object):\n def makeConnected(self, n, connections):\n \"\"\"\n :type n: int\n :type connections: List[List[int]]\n :rtype: int\n \"\"\"\n def dfs(i, lookup):\n if i in lookup:\n return 0\n lookup.add(i)\n if i in G:\n for j in G[i]:\n dfs(j, lookup)\n return 1\n\n if len(connections) < n-1:\n return -1\n G = collections.defaultdict(list)\n for i, j in connections:\n G[i].append(j)\n G[j].append(i)\n lookup = set()\n return sum(dfs(i, lookup) for i in range(n)) - 1\n"}} diff --git a/cp/cp-10750.jsonl b/cp/cp-10750.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..90dce140e3c5e675cbc82e2199618e3ab2ac7042 --- /dev/null +++ b/cp/cp-10750.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10750", "name": "LeetCode 1320: Minimum Distance To Type A Word Using Two Fingers"} +{"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: Minimum Distance to Type a Word Using Two Fingers (Difficulty: Hard)\nTags: String, Dynamic Programming\n\nYou have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate.\nGiven the string word, return the minimum total distance to type such string using only two fingers.\nThe distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|.\nNote that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.\n\nExample 1:\nInput: word = \"CAKE\"\nOutput: 3\nExplanation: Using two fingers, one optimal way to type \"CAKE\" is: \nFinger 1 on letter 'C' -> cost = 0 \nFinger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 \nFinger 2 on letter 'K' -> cost = 0 \nFinger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 \nTotal distance = 3\n\nExample 2:\nInput: word = \"HAPPY\"\nOutput: 6\nExplanation: Using two fingers, one optimal way to type \"HAPPY\" is:\nFinger 1 on letter 'H' -> cost = 0\nFinger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2\nFinger 2 on letter 'P' -> cost = 0\nFinger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0\nFinger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4\nTotal distance = 6\n\nConstraints:\n- 2 <= word.length <= 300\n- word consists of uppercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(26n)\n# Space: O(26)\n\nclass Solution(object):\n def minimumDistance(self, word):\n \"\"\"\n :type word: str\n :rtype: int\n \"\"\"\n def distance(a, b):\n return abs(a//6 - b//6) + abs(a%6 - b%6)\n\n dp = [0]*26\n for i in range(len(word)-1):\n b, c = ord(word[i])-ord('A'), ord(word[i+1])-ord('A')\n dp[b] = max(dp[a] - distance(a, c) + distance(b, c) for a in range(26))\n return sum(distance(ord(word[i])-ord('A'), ord(word[i+1])-ord('A')) for i in range(len(word)-1)) - max(dp)\n\n\n# Time: O(52n)\n# Space: O(52)\nclass Solution2(object):\n def minimumDistance(self, word):\n \"\"\"\n :type word: str\n :rtype: int\n \"\"\"\n def distance(a, b):\n if -1 in [a, b]:\n return 0\n return abs(a//6 - b//6) + abs(a%6 - b%6)\n\n dp = {(-1, -1): 0}\n for c in word:\n c = ord(c)-ord('A')\n new_dp = {}\n for a, b in dp:\n new_dp[c, b] = min(new_dp.get((c, b), float(\"inf\")), dp[a, b] + distance(a, c))\n new_dp[a, c] = min(new_dp.get((a, c), float(\"inf\")), dp[a, b] + distance(b, c))\n dp = new_dp\n return min(dp.itervalues())\n"}} diff --git a/cp/cp-10751.jsonl b/cp/cp-10751.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ff72fe53585460baa4a39608a468d07cdf060e93 --- /dev/null +++ b/cp/cp-10751.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10751", "name": "LeetCode 1323: Maximum 69 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: Maximum 69 Number (Difficulty: Easy)\nTags: Math, Greedy\n\nYou are given a positive integer num consisting only of digits 6 and 9.\nReturn the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).\n\nExample 1:\nInput: num = 9669\nOutput: 9969\nExplanation: \nChanging the first digit results in 6669.\nChanging the second digit results in 9969.\nChanging the third digit results in 9699.\nChanging the fourth digit results in 9666.\nThe maximum number is 9969.\n\nExample 2:\nInput: num = 9996\nOutput: 9999\nExplanation: Changing the last digit 6 to 9 results in the maximum number.\n\nExample 3:\nInput: num = 9999\nOutput: 9999\nExplanation: It is better not to apply any change.\n\nConstraints:\n- 1 <= num <= 10^4\n- num consists of only 6 and 9 digits."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nclass Solution(object):\n def maximum69Number (self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n curr, base, change = num, 3, 0\n while curr:\n if curr%10 == 6:\n change = base\n base *= 10\n curr //= 10\n return num+change\n\n\n# Time: O(logn)\n# Space: O(logn)\nclass Solution2(object):\n def maximum69Number (self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n return int(str(num).replace('6', '9', 1))\n"}} diff --git a/cp/cp-10753.jsonl b/cp/cp-10753.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3ba46a3768adb42b7f3d218e6b08ba11749c7958 --- /dev/null +++ b/cp/cp-10753.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10753", "name": "LeetCode 1325: Delete Leaves With A Given Value"} +{"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: Delete Leaves With a Given Value (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Tree\n\nGiven a binary tree root and an integer target, delete all the leaf nodes with value target.\nNote that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).\n\nExample 1:\nInput: root = [1,2,3,2,null,2,4], target = 2\nOutput: [1,null,3,null,4]\nExplanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). \nAfter removing, new nodes become leaf nodes with value (target = 2) (Picture in center).\n\nExample 2:\nInput: root = [1,3,3,3,2], target = 3\nOutput: [1,3,null,null,2]\n\nExample 3:\nInput: root = [1,2,null,2,null,2], target = 2\nOutput: [1]\nExplanation: Leaf nodes in green with value (target = 2) are removed at each step.\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 3000].\n- 1 <= Node.val, target <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 removeLeafNodes(self, root, target):\n \"\"\"\n :type root: TreeNode\n :type target: int\n :rtype: TreeNode\n \"\"\"\n if not root:\n return None\n root.left = self.removeLeafNodes(root.left, target)\n root.right = self.removeLeafNodes(root.right, target)\n return None if root.left == root.right and root.val == target else root\n"}} diff --git a/cp/cp-10754.jsonl b/cp/cp-10754.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..453fcf93fe585553e7a08ef31568186eaf265c7e --- /dev/null +++ b/cp/cp-10754.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10754", "name": "LeetCode 1326: Minimum Number Of Taps To Open To Water A Garden"} +{"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: Minimum Number of Taps to Open to Water a Garden (Difficulty: Hard)\nTags: Array, Dynamic Programming, Greedy\n\nThere is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e., the length of the garden is n).\nThere are n + 1 taps located at points [0, 1, ..., n] in the garden.\nGiven an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open.\nReturn the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.\n\nExample 1:\nInput: n = 5, ranges = [3,4,1,1,0,0]\nOutput: 1\nExplanation: The tap at point 0 can cover the interval [-3,3]\nThe tap at point 1 can cover the interval [-3,5]\nThe tap at point 2 can cover the interval [1,3]\nThe tap at point 3 can cover the interval [2,4]\nThe tap at point 4 can cover the interval [4,4]\nThe tap at point 5 can cover the interval [5,5]\nOpening Only the second tap will water the whole garden [0,5]\n\nExample 2:\nInput: n = 3, ranges = [0,0,0,0]\nOutput: -1\nExplanation: Even if you activate all the four taps you cannot water the whole garden.\n\nConstraints:\n- 1 <= n <= 10^4\n- ranges.length == n + 1\n- 0 <= ranges[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def minTaps(self, n, ranges):\n \"\"\"\n :type n: int\n :type ranges: List[int]\n :rtype: int\n \"\"\"\n def jump_game(A):\n jump_count, reachable, curr_reachable = 0, 0, 0\n for i, length in enumerate(A):\n if i > reachable:\n return -1\n if i > curr_reachable:\n curr_reachable = reachable\n jump_count += 1\n reachable = max(reachable, i+length)\n return jump_count\n \n max_range = [0]*(n+1)\n for i, r in enumerate(ranges):\n left, right = max(i-r, 0), min(i+r, n)\n max_range[left] = max(max_range[left], right-left)\n return jump_game(max_range)\n"}} diff --git a/cp/cp-10755.jsonl b/cp/cp-10755.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..14251f7eef570ef56692c42a46de8f640fa0b4eb --- /dev/null +++ b/cp/cp-10755.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10755", "name": "LeetCode 1328: Break A Palindrome"} +{"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: Break a Palindrome (Difficulty: Medium)\nTags: String, Greedy\n\nGiven a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.\nReturn the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.\nA string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, \"abcc\" is lexicographically smaller than \"abcd\" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'.\n\nExample 1:\nInput: palindrome = \"abccba\"\nOutput: \"aaccba\"\nExplanation: There are many ways to make \"abccba\" not a palindrome, such as \"zbccba\", \"aaccba\", and \"abacba\".\nOf all the ways, \"aaccba\" is the lexicographically smallest.\n\nExample 2:\nInput: palindrome = \"a\"\nOutput: \"\"\nExplanation: There is no way to replace a single character to make \"a\" not a palindrome, so return an empty string.\n\nConstraints:\n- 1 <= palindrome.length <= 1000\n- palindrome consists of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def breakPalindrome(self, palindrome):\n \"\"\"\n :type palindrome: str\n :rtype: str\n \"\"\"\n for i in range(len(palindrome)//2):\n if palindrome[i] != 'a':\n return palindrome[:i] + 'a' + palindrome[i+1:]\n return palindrome[:-1] + 'b' if len(palindrome) >= 2 else \"\"\n"}} diff --git a/cp/cp-10756.jsonl b/cp/cp-10756.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ce93f9371b6ccf29d48c1859a579f28f54023195 --- /dev/null +++ b/cp/cp-10756.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10756", "name": "LeetCode 1329: Sort The Matrix Diagonally"} +{"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: Sort the Matrix Diagonally (Difficulty: Medium)\nTags: Array, Sorting, Matrix\n\nA matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2].\nGiven an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.\n\nExample 1:\nInput: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]\nOutput: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]\n\nExample 2:\nInput: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]\nOutput: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]\n\nConstraints:\n- m == mat.length\n- n == mat[i].length\n- 1 <= m, n <= 100\n- 1 <= mat[i][j] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n * log(min(m, n))\n# Space: O(m * n)\n\nimport collections\n\n\nclass Solution(object):\n def diagonalSort(self, mat):\n \"\"\"\n :type mat: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n lookup = collections.defaultdict(list)\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n lookup[i-j].append(mat[i][j])\n for v in lookup.itervalues():\n v.sort()\n for i in reversed(range(len(mat))):\n for j in reversed(range(len(mat[0]))):\n mat[i][j] = lookup[i-j].pop()\n return mat\n"}} diff --git a/cp/cp-10757.jsonl b/cp/cp-10757.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d31fcade081d7cdbb7340368357e384c4635fa41 --- /dev/null +++ b/cp/cp-10757.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10757", "name": "LeetCode 1330: Reverse Subarray To Maximize Array Value"} +{"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: Reverse Subarray To Maximize Array Value (Difficulty: Hard)\nTags: Array, Math, Greedy\n\nYou are given an integer array nums. The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1.\nYou are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.\nFind maximum possible value of the final array.\n\nExample 1:\nInput: nums = [2,3,1,5,4]\nOutput: 10\nExplanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.\n\nExample 2:\nInput: nums = [2,4,9,24,2,1,10]\nOutput: 68\n\nConstraints:\n- 2 <= nums.length <= 3 * 10^4\n- -10^5 <= nums[i] <= 10^5\n- The answer is guaranteed to fit in a 32-bit integer."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxValueAfterReverse(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result, add, max_pair, min_pair = 0, 0, float(\"-inf\"), float(\"inf\")\n for i in range(1, len(nums)):\n result += abs(nums[i-1]-nums[i])\n add = max(add,\n abs(nums[0]-nums[i]) - abs(nums[i-1]-nums[i]),\n abs(nums[-1]-nums[i-1]) - abs(nums[i-1]-nums[i]))\n min_pair = min(min_pair, max(nums[i-1], nums[i]))\n max_pair = max(max_pair, min(nums[i-1], nums[i]))\n return result + max(add, (max_pair-min_pair)*2)\n"}} diff --git a/cp/cp-10759.jsonl b/cp/cp-10759.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5affa1aa2a3303df3d2c7c67d0ec78d0c9e62dda --- /dev/null +++ b/cp/cp-10759.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10759", "name": "LeetCode 1332: Remove Palindromic 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: Remove Palindromic Subsequences (Difficulty: Easy)\nTags: Two Pointers, String\n\nYou are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.\nReturn the minimum number of steps to make the given string empty.\nA string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous.\nA string is called palindrome if is one that reads the same backward as well as forward.\n\nExample 1:\nInput: s = \"ababa\"\nOutput: 1\nExplanation: s is already a palindrome, so its entirety can be removed in a single step.\n\nExample 2:\nInput: s = \"abb\"\nOutput: 2\nExplanation: \"abb\" -> \"bb\" -> \"\". \nRemove palindromic subsequence \"a\" then \"bb\".\n\nExample 3:\nInput: s = \"baabb\"\nOutput: 2\nExplanation: \"baabb\" -> \"b\" -> \"\". \nRemove palindromic subsequence \"baab\" then \"b\".\n\nConstraints:\n- 1 <= s.length <= 1000\n- s[i] is either 'a' or 'b'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def removePalindromeSub(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n def is_palindrome(s):\n for i in range(len(s)//2):\n if s[i] != s[-1-i]:\n return False\n return True\n \n return 2 - is_palindrome(s) - (s == \"\")\n"}} diff --git a/cp/cp-10760.jsonl b/cp/cp-10760.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..733ce7cbb7b3ecc0972900a60dcd25bfbc5cbb12 --- /dev/null +++ b/cp/cp-10760.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10760", "name": "LeetCode 1333: Filter Restaurants By Vegan Friendly Price And Distance"} +{"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: Filter Restaurants by Vegan-Friendly, Price and Distance (Difficulty: Medium)\nTags: Array, Sorting\n\nGiven the array restaurants where  restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters.\nThe veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendlyi set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively.\nReturn the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false.\n\nExample 1:\nInput: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10\nOutput: [3,1,5] \nExplanation: \nThe restaurants are:\nRestaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]\nRestaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]\nRestaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]\nRestaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]\nRestaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] \nAfter filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest).\n\nExample 2:\nInput: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10\nOutput: [4,3,2,1,5]\nExplanation: The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.\n\nExample 3:\nInput: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3\nOutput: [4,5]\n\nConstraints:\n- 1 <= restaurants.length <= 10^4\n- restaurants[i].length == 5\n- 1 <= idi, ratingi, pricei, distancei <= 10^5\n- 1 <= maxPrice, maxDistance <= 10^5\n- veganFriendlyi and veganFriendly are 0 or 1.\n- All idi are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(rlogr), r is the number of result\n# Space: O(r)\n\nclass Solution(object):\n def filterRestaurants(self, restaurants, veganFriendly, maxPrice, maxDistance):\n \"\"\"\n :type restaurants: List[List[int]]\n :type veganFriendly: int\n :type maxPrice: int\n :type maxDistance: int\n :rtype: List[int]\n \"\"\"\n result, lookup = [], {}\n for j, (i, _, v, p, d) in enumerate(restaurants):\n if v >= veganFriendly and p <= maxPrice and d <= maxDistance:\n lookup[i] = j\n result.append(i)\n result.sort(key=lambda i: (-restaurants[lookup[i]][1], -restaurants[lookup[i]][0]))\n return result\n"}} diff --git a/cp/cp-10761.jsonl b/cp/cp-10761.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b31e81a2b5a1078edb89b285d73470ba073d25dd --- /dev/null +++ b/cp/cp-10761.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10761", "name": "LeetCode 1334: Find The City With The Smallest Number Of Neighbors At A Threshold Distance"} +{"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 the City With the Smallest Number of Neighbors at a Threshold Distance (Difficulty: Medium)\nTags: Dynamic Programming, Graph, Shortest Path\n\nThere are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.\nReturn the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.\nNotice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.\n\nExample 1:\nInput: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4\nOutput: 3\nExplanation: The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 4 for each city are:\nCity 0 -> [City 1, City 2] \nCity 1 -> [City 0, City 2, City 3] \nCity 2 -> [City 0, City 1, City 3] \nCity 3 -> [City 1, City 2] \nCities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.\n\nExample 2:\nInput: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2\nOutput: 0\nExplanation: The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 2 for each city are:\nCity 0 -> [City 1] \nCity 1 -> [City 0, City 4] \nCity 2 -> [City 3, City 4] \nCity 3 -> [City 2, City 4]\nCity 4 -> [City 1, City 2, City 3] \nThe city 0 has 1 neighboring city at a distanceThreshold = 2.\n\nConstraints:\n- 2 <= n <= 100\n- 1 <= edges.length <= n * (n - 1) / 2\n- edges[i].length == 3\n- 0 <= fromi < toi < n\n- 1 <= weighti, distanceThreshold <= 10^4\n- All pairs (fromi, toi) are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(n^2)\n\nclass Solution(object):\n def findTheCity(self, n, edges, distanceThreshold):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type distanceThreshold: int\n :rtype: int\n \"\"\"\n dist = [[float(\"inf\")]*n for _ in range(n)]\n for i, j, w in edges:\n dist[i][j] = dist[j][i] = w\n for i in range(n):\n dist[i][i] = 0\n for k in range(n): \n for i in range(n): \n for j in range(n): \n dist[i][j] = min(dist[i][j], dist[i][k]+dist[k][j]) \n result = {sum(d <= distanceThreshold for d in dist[i]): i for i in range(n)}\n return result[min(result.iterkeys())]\n"}} diff --git a/cp/cp-10762.jsonl b/cp/cp-10762.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..28536b865a725d3c4ac977b57b74e47ab62b38f6 --- /dev/null +++ b/cp/cp-10762.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10762", "name": "LeetCode 1335: Minimum Difficulty Of A Job Schedule"} +{"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: Minimum Difficulty of a Job Schedule (Difficulty: Hard)\nTags: Array, Dynamic Programming\n\nYou want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i).\nYou have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day.\nYou are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i].\nReturn the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.\n\nExample 1:\nInput: jobDifficulty = [6,5,4,3,2,1], d = 2\nOutput: 7\nExplanation: First day you can finish the first 5 jobs, total difficulty = 6.\nSecond day you can finish the last job, total difficulty = 1.\nThe difficulty of the schedule = 6 + 1 = 7\n\nExample 2:\nInput: jobDifficulty = [9,9,9], d = 4\nOutput: -1\nExplanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.\n\nExample 3:\nInput: jobDifficulty = [1,1,1], d = 3\nOutput: 3\nExplanation: The schedule is one job per day. total difficulty will be 3.\n\nConstraints:\n- 1 <= jobDifficulty.length <= 300\n- 0 <= jobDifficulty[i] <= 1000\n- 1 <= d <= 10"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(d * n^2)\n# Space: O(d * n)\n\nclass Solution(object):\n def minDifficulty(self, jobDifficulty, d):\n \"\"\"\n :type jobDifficulty: List[int]\n :type d: int\n :rtype: int\n \"\"\"\n if len(jobDifficulty) < d:\n return -1\n \n dp = [[float(\"inf\")]*len(jobDifficulty) for _ in range(d)]\n dp[0][0] = jobDifficulty[0]\n for i in range(1, len(jobDifficulty)):\n dp[0][i] = max(dp[0][i-1], jobDifficulty[i])\n for i in range(1, d):\n for j in range(i, len(jobDifficulty)):\n curr_max = jobDifficulty[j]\n for k in reversed(range(i, j+1)):\n curr_max = max(curr_max, jobDifficulty[k])\n dp[i][j] = min(dp[i][j], dp[i-1][k-1] + curr_max)\n return dp[d-1][len(jobDifficulty)-1]\n"}} diff --git a/cp/cp-10763.jsonl b/cp/cp-10763.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0c47135d93d168c9e4cd4545281a517ca361f38e --- /dev/null +++ b/cp/cp-10763.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10763", "name": "LeetCode 1337: The K Weakest Rows In A Matrix"} +{"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: The K Weakest Rows in a Matrix (Difficulty: Easy)\nTags: Array, Binary Search, Sorting, Heap (Priority Queue), Matrix\n\nYou are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.\nA row i is weaker than a row j if one of the following is true:\nReturn the indices of the k weakest rows in the matrix ordered from weakest to strongest.\n\nExample 1:\nInput: mat = \n[[1,1,0,0,0],\n [1,1,1,1,0],\n [1,0,0,0,0],\n [1,1,0,0,0],\n [1,1,1,1,1]], \nk = 3\nOutput: [2,0,3]\nExplanation: \nThe number of soldiers in each row is: \n- Row 0: 2 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 2 \n- Row 4: 5 \nThe rows ordered from weakest to strongest are [2,0,3,1,4].\n\nExample 2:\nInput: mat = \n[[1,0,0,0],\n [1,1,1,1],\n [1,0,0,0],\n [1,0,0,0]], \nk = 2\nOutput: [0,2]\nExplanation: \nThe number of soldiers in each row is: \n- Row 0: 1 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 1 \nThe rows ordered from weakest to strongest are [0,2,3,1].\n\nConstraints:\n- m == mat.length\n- n == mat[i].length\n- 2 <= n, m <= 100\n- 1 <= k <= m\n- matrix[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(k)\n\nclass Solution(object):\n def kWeakestRows(self, mat, k):\n \"\"\"\n :type mat: List[List[int]]\n :type k: int\n :rtype: List[int]\n \"\"\"\n result, lookup = [], set()\n for j in range(len(mat[0])):\n for i in range(len(mat)):\n if mat[i][j] or i in lookup:\n continue\n lookup.add(i)\n result.append(i)\n if len(result) == k:\n return result\n for i in range(len(mat)):\n if i in lookup:\n continue\n lookup.add(i)\n result.append(i)\n if len(result) == k:\n break\n return result\n\n\n# Time: O(m * n)\n# Space: O(k)\nimport collections\n\n\nclass Solution2(object):\n def kWeakestRows(self, mat, k):\n \"\"\"\n :type mat: List[List[int]]\n :type k: int\n :rtype: List[int]\n \"\"\"\n lookup = collections.OrderedDict()\n for j in range(len(mat[0])):\n for i in range(len(mat)):\n if mat[i][j] or i in lookup:\n continue\n lookup[i] = True\n if len(lookup) == k:\n return lookup.keys()\n for i in range(len(mat)):\n if i in lookup:\n continue\n lookup[i] = True\n if len(lookup) == k:\n break\n return lookup.keys()\n\n\n# Time: O(m * n + klogk)\n# Space: O(m)\nimport random\n\n\nclass Solution3(object):\n def kWeakestRows(self, mat, k):\n \"\"\"\n :type mat: List[List[int]]\n :type k: int\n :rtype: List[int]\n \"\"\"\n def nth_element(nums, n, compare=lambda a, b: a < b):\n def partition_around_pivot(left, right, pivot_idx, nums, compare):\n new_pivot_idx = left\n nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]\n for i in range(left, right):\n if compare(nums[i], nums[right]):\n nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]\n new_pivot_idx += 1\n\n nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]\n return new_pivot_idx\n\n left, right = 0, len(nums) - 1\n while left <= right:\n pivot_idx = random.randint(left, right)\n new_pivot_idx = partition_around_pivot(left, right, pivot_idx, nums, compare)\n if new_pivot_idx == n:\n return\n elif new_pivot_idx > n:\n right = new_pivot_idx - 1\n else: # new_pivot_idx < n\n left = new_pivot_idx + 1\n \n nums = [(sum(mat[i]), i) for i in range(len(mat))]\n nth_element(nums, k)\n return map(lambda x: x[1], sorted(nums[:k]))\n"}} diff --git a/cp/cp-10764.jsonl b/cp/cp-10764.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..aa27de203e8e052666356eca05b8d82898c6a15d --- /dev/null +++ b/cp/cp-10764.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10764", "name": "LeetCode 1338: Reduce Array Size To The Half"} +{"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: Reduce Array Size to The Half (Difficulty: Medium)\nTags: Array, Hash Table, Greedy, Sorting, Heap (Priority Queue)\n\nYou are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.\nReturn the minimum size of the set so that at least half of the integers of the array are removed.\n\nExample 1:\nInput: arr = [3,3,3,3,5,5,5,2,2,7]\nOutput: 2\nExplanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).\nPossible sets of size 2 are {3,5},{3,2},{5,2}.\nChoosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.\n\nExample 2:\nInput: arr = [7,7,7,7,7,7]\nOutput: 1\nExplanation: The only possible set you can choose is {7}. This will make the new array empty.\n\nConstraints:\n- 2 <= arr.length <= 10^5\n- arr.length is even.\n- 1 <= arr[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n \nclass Solution(object):\n def minSetSize(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n counting_sort = [0]*len(arr)\n count = collections.Counter(arr)\n for c in count.itervalues():\n counting_sort[c-1] += 1\n result, total = 0, 0\n for c in reversed(range(len(arr))):\n if not counting_sort[c]:\n continue\n count = min(counting_sort[c],\n ((len(arr)+1)//2 - total - 1)//(c+1) + 1)\n result += count\n total += count*(c+1)\n if total >= (len(arr)+1)//2:\n break\n return result\n"}} diff --git a/cp/cp-10765.jsonl b/cp/cp-10765.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..66b0b513b3486836885739c48d2f74159627a4f6 --- /dev/null +++ b/cp/cp-10765.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10765", "name": "LeetCode 1339: Maximum Product Of Splitted 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 Product of Splitted Binary Tree (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Tree\n\nGiven the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.\nReturn the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7.\nNote that you need to maximize the answer before taking the mod and not after taking it.\n\nExample 1:\nInput: root = [1,2,3,4,5,6]\nOutput: 110\nExplanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)\n\nExample 2:\nInput: root = [1,null,2,3,4,null,null,5,6]\nOutput: 90\nExplanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)\n\nConstraints:\n- The number of nodes in the tree is in the range [2, 5 * 10^4].\n- 1 <= Node.val <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 maxProduct(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n MOD = 10**9 + 7\n def dfs(root, total, result):\n if not root:\n return 0\n subtotal = dfs(root.left, total, result)+dfs(root.right, total, result)+root.val\n result[0] = max(result[0], subtotal*(total-subtotal) )\n return subtotal\n\n result = [0]\n dfs(root, dfs(root, 0, result), result)\n return result[0] % MOD\n"}} diff --git a/cp/cp-10766.jsonl b/cp/cp-10766.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d223106280714b11c619709638fb73edb843af65 --- /dev/null +++ b/cp/cp-10766.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10766", "name": "LeetCode 1340: Jump Game V"} +{"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: Jump Game V (Difficulty: Hard)\nTags: Array, Dynamic Programming, Sorting\n\nGiven an array of integers arr and an integer d. In one step you can jump from index i to index:\nIn addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)).\nYou can choose any index of the array and start jumping. Return the maximum number of indices you can visit.\nNotice that you can not jump outside of the array at any time.\n\nExample 1:\nInput: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2\nOutput: 4\nExplanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.\nNote that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.\nSimilarly You cannot jump from index 3 to index 2 or index 1.\n\nExample 2:\nInput: arr = [3,3,3,3,3], d = 3\nOutput: 1\nExplanation: You can start at any index. You always cannot jump to any index.\n\nExample 3:\nInput: arr = [7,6,5,4,3,2,1], d = 1\nOutput: 7\nExplanation: Start at index 0. You can visit all the indicies.\n\nConstraints:\n- 1 <= arr.length <= 1000\n- 1 <= arr[i] <= 10^5\n- 1 <= d <= arr.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\nimport itertools\n\n\n# sliding window + top-down dp\nclass Solution(object):\n def maxJumps(self, arr, d):\n \"\"\"\n :type arr: List[int]\n :type d: int\n :rtype: int\n \"\"\"\n def dp(arr, d, i, left, right, lookup):\n if lookup[i]:\n return lookup[i]\n lookup[i] = 1\n for j in itertools.chain(left[i], right[i]):\n # each dp[j] will be visited at most twice \n lookup[i] = max(lookup[i], dp(arr, d, j, left, right, lookup)+1)\n return lookup[i]\n\n left, decreasing_dq = [[] for _ in range(len(arr))], collections.deque()\n for i in range(len(arr)):\n if decreasing_dq and i - decreasing_dq[0] == d+1:\n decreasing_dq.popleft()\n while decreasing_dq and arr[decreasing_dq[-1]] < arr[i]:\n if left[i] and arr[left[i][-1]] != arr[decreasing_dq[-1]]:\n left[i] = []\n left[i].append(decreasing_dq.pop())\n decreasing_dq.append(i)\n right, decreasing_dq = [[] for _ in range(len(arr))], collections.deque()\n for i in reversed(range(len(arr))):\n if decreasing_dq and decreasing_dq[0] - i == d+1:\n decreasing_dq.popleft()\n while decreasing_dq and arr[decreasing_dq[-1]] < arr[i]:\n if right[i] and arr[right[i][-1]] != arr[decreasing_dq[-1]]:\n right[i] = []\n right[i].append(decreasing_dq.pop())\n decreasing_dq.append(i)\n\n lookup = [0]*len(arr)\n return max(itertools.imap(lambda x: dp(arr, d, x, left, right, lookup), range(len(arr))))\n\n\n# Time: O(nlogn)\n# Space: O(n)\n# mono stack + bottom-up dp\nclass Solution2(object):\n def maxJumps(self, arr, d):\n \"\"\"\n :type arr: List[int]\n :type d: int\n :rtype: int\n \"\"\"\n left, decreasing_stk = [[] for _ in range(len(arr))], []\n for i in range(len(arr)):\n while decreasing_stk and arr[decreasing_stk[-1]] < arr[i]:\n if i - decreasing_stk[-1] <= d:\n if left[i] and arr[left[i][-1]] != arr[decreasing_stk[-1]]:\n left[i] = []\n left[i].append(decreasing_stk[-1])\n decreasing_stk.pop()\n decreasing_stk.append(i)\n right, decreasing_stk = [[] for _ in range(len(arr))], []\n for i in reversed(range(len(arr))):\n while decreasing_stk and arr[decreasing_stk[-1]] < arr[i]:\n if decreasing_stk[-1] - i <= d:\n if right[i] and arr[right[i][-1]] != arr[decreasing_stk[-1]]:\n right[i] = []\n right[i].append(decreasing_stk[-1])\n decreasing_stk.pop()\n decreasing_stk.append(i)\n\n dp = [0]*len(arr)\n for a, i in sorted([a, i] for i, a in enumerate(arr)):\n dp[i] = 1\n for j in itertools.chain(left[i], right[i]):\n # each dp[j] will be visited at most twice \n dp[i] = max(dp[i], dp[j]+1)\n return max(dp)\n\n\n# Template:\n# https://github.com/kamyu104/FacebookHackerCup-2018/blob/master/Final%20Round/the_claw.py\nclass SegmentTree(object):\n def __init__(self, N,\n build_fn=lambda x, y: [y]*(2*x),\n query_fn=max,\n update_fn=lambda x, y: y,\n default_val=0):\n self.N = N\n self.H = (N-1).bit_length()\n self.query_fn = query_fn\n self.update_fn = update_fn\n self.default_val = default_val\n self.tree = build_fn(N, default_val)\n self.lazy = [None]*N\n\n def __apply(self, x, val):\n self.tree[x] = self.update_fn(self.tree[x], val)\n if x < self.N:\n self.lazy[x] = self.update_fn(self.lazy[x], val)\n\n def update(self, L, R, h): # Time: O(logN), Space: O(N)\n def pull(x):\n while x > 1:\n x //= 2\n self.tree[x] = self.query_fn(self.tree[x*2], self.tree[x*2+1])\n if self.lazy[x] is not None:\n self.tree[x] = self.update_fn(self.tree[x], self.lazy[x])\n L += self.N\n R += self.N\n L0, R0 = L, R\n while L <= R:\n if L & 1: # is right child\n self.__apply(L, h)\n L += 1\n if R & 1 == 0: # is left child\n self.__apply(R, h)\n R -= 1\n L //= 2\n R //= 2\n pull(L0)\n pull(R0)\n\n def query(self, L, R): # Time: O(logN), Space: O(N)\n def push(x):\n n = 2**self.H\n while n != 1:\n y = x // n\n if self.lazy[y] is not None:\n self.__apply(y*2, self.lazy[y])\n self.__apply(y*2 + 1, self.lazy[y])\n self.lazy[y] = None\n n //= 2\n\n result = self.default_val\n if L > R:\n return result\n\n L += self.N\n R += self.N\n push(L)\n push(R)\n while L <= R:\n if L & 1: # is right child\n result = self.query_fn(result, self.tree[L])\n L += 1\n if R & 1 == 0: # is left child\n result = self.query_fn(result, self.tree[R])\n R -= 1\n L //= 2\n R //= 2\n return result\n \n def __str__(self):\n showList = []\n for i in range(self.N):\n showList.append(self.query(i, i))\n return \",\".join(map(str, showList))\n\n\n# Time: O(nlogn)\n# Space: O(n)\n# mono stack + bottom-up dp + segment tree\nclass Solution3(object):\n def maxJumps(self, arr, d):\n \"\"\"\n :type arr: List[int]\n :type d: int\n :rtype: int\n \"\"\"\n left, decreasing_stk = range(len(arr)), []\n for i in range(len(arr)):\n while decreasing_stk and arr[decreasing_stk[-1]] < arr[i]:\n if i - decreasing_stk[-1] <= d:\n left[i] = decreasing_stk[-1]\n decreasing_stk.pop()\n decreasing_stk.append(i)\n right, decreasing_stk = range(len(arr)), []\n for i in reversed(range(len(arr))):\n while decreasing_stk and arr[decreasing_stk[-1]] < arr[i]:\n if decreasing_stk[-1] - i <= d:\n right[i] = decreasing_stk[-1]\n decreasing_stk.pop()\n decreasing_stk.append(i)\n\n segment_tree = SegmentTree(len(arr))\n for _, i in sorted([x, i] for i, x in enumerate(arr)):\n segment_tree.update(i, i, segment_tree.query(left[i], right[i]) + 1)\n return segment_tree.query(0, len(arr)-1)\n"}} diff --git a/cp/cp-10768.jsonl b/cp/cp-10768.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9a03cc13cb09ac070b0d22fb46cb2d209eaed667 --- /dev/null +++ b/cp/cp-10768.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10768", "name": "LeetCode 1343: Number Of Sub Arrays Of Size K And Average Greater Than Or Equal To Threshold"} +{"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 Sub-arrays of Size K and Average Greater than or Equal to Threshold (Difficulty: Medium)\nTags: Array, Sliding Window\n\nGiven an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold.\n\nExample 1:\nInput: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4\nOutput: 3\nExplanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).\n\nExample 2:\nInput: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5\nOutput: 6\nExplanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.\n\nConstraints:\n- 1 <= arr.length <= 10^5\n- 1 <= arr[i] <= 10^4\n- 1 <= k <= arr.length\n- 0 <= threshold <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def numOfSubarrays(self, arr, k, threshold):\n \"\"\"\n :type arr: List[int]\n :type k: int\n :type threshold: int\n :rtype: int\n \"\"\"\n result, curr = 0, sum(itertools.islice(arr, 0, k-1))\n for i in range(k-1, len(arr)):\n curr += arr[i]-(arr[i-k] if i-k >= 0 else 0)\n result += int(curr >= threshold*k)\n return result\n \n\n# Time: O(n)\n# Space: O(n)\nclass Solution2(object):\n def numOfSubarrays(self, arr, k, threshold):\n \"\"\"\n :type arr: List[int]\n :type k: int\n :type threshold: int\n :rtype: int\n \"\"\"\n accu = [0]\n for x in arr:\n accu.append(accu[-1]+x)\n result = 0\n for i in range(len(accu)-k):\n if accu[i+k]-accu[i] >= threshold*k:\n result += 1\n return result\n"}} diff --git a/cp/cp-10769.jsonl b/cp/cp-10769.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4e9f1223ea8b7fb65cdaa29648a046d1b63255c4 --- /dev/null +++ b/cp/cp-10769.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10769", "name": "LeetCode 1344: Angle Between Hands Of A Clock"} +{"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: Angle Between Hands of a Clock (Difficulty: Medium)\nTags: Math\n\nGiven two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand.\nAnswers within 10-5 of the actual value will be accepted as correct.\n\nExample 1:\nInput: hour = 12, minutes = 30\nOutput: 165\n\nExample 2:\nInput: hour = 3, minutes = 30\nOutput: 75\n\nExample 3:\nInput: hour = 3, minutes = 15\nOutput: 7.5\n\nConstraints:\n- 1 <= hour <= 12\n- 0 <= minutes <= 59"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def angleClock(self, hour, minutes):\n \"\"\"\n :type hour: int\n :type minutes: int\n :rtype: float\n \"\"\"\n angle1 = (hour % 12 * 60.0 + minutes) / 720.0\n angle2 = minutes / 60.0\n diff = abs(angle1-angle2)\n return min(diff, 1.0-diff) * 360.0\n"}} diff --git a/cp/cp-10770.jsonl b/cp/cp-10770.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..427875e0551b2350ff151e671ed9650665babad5 --- /dev/null +++ b/cp/cp-10770.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10770", "name": "LeetCode 1345: Jump Game Iv"} +{"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: Jump Game IV (Difficulty: Hard)\nTags: Array, Hash Table, Breadth-First Search\n\nGiven an array of integers arr, you are initially positioned at the first index of the array.\nIn one step you can jump from index i to index:\nReturn the minimum number of steps to reach the last index of the array.\nNotice that you can not jump outside of the array at any time.\n\nExample 1:\nInput: arr = [100,-23,-23,404,100,23,23,23,3,404]\nOutput: 3\nExplanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.\n\nExample 2:\nInput: arr = [7]\nOutput: 0\nExplanation: Start index is the last index. You do not need to jump.\n\nExample 3:\nInput: arr = [7,6,9,6,9,6,9,7]\nOutput: 1\nExplanation: You can jump directly from index 0 to index 7 which is last index of the array.\n\nConstraints:\n- 1 <= arr.length <= 5 * 10^4\n- -108 <= arr[i] <= 10^8"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def minJumps(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n groups = collections.defaultdict(list)\n for i, x in enumerate(arr):\n groups[x].append(i)\n q = collections.deque([(0, 0)])\n lookup = set([0])\n while q:\n pos, step = q.popleft()\n if pos == len(arr)-1:\n break\n neighbors = set(groups[arr[pos]] + [pos-1, pos+1])\n groups[arr[pos]] = []\n for p in neighbors:\n if p in lookup or not 0 <= p < len(arr):\n continue\n lookup.add(p)\n q.append((p, step+1)) \n return step\n"}} diff --git a/cp/cp-10771.jsonl b/cp/cp-10771.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..35623a6030d5ee87aa9e2de689ae3632bcfe0f47 --- /dev/null +++ b/cp/cp-10771.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10771", "name": "LeetCode 1346: Check If N And Its Double Exist"} +{"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: Check If N and Its Double Exist (Difficulty: Easy)\nTags: Array, Hash Table, Two Pointers, Binary Search, Sorting\n\nGiven an array arr of integers, check if there exist two indices i and j such that :\n\nExample 1:\nInput: arr = [10,2,5,3]\nOutput: true\nExplanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j]\n\nExample 2:\nInput: arr = [3,1,7,11]\nOutput: false\nExplanation: There is no i and j that satisfy the conditions.\n\nConstraints:\n- 2 <= arr.length <= 500\n- -103 <= arr[i] <= 103"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def checkIfExist(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: bool\n \"\"\"\n lookup = set()\n for x in arr:\n if 2*x in lookup or \\\n (x%2 == 0 and x//2 in lookup):\n return True\n lookup.add(x)\n return False\n"}} diff --git a/cp/cp-10773.jsonl b/cp/cp-10773.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..86279723ff9fe7b13f4206143d4d5010a0717ee0 --- /dev/null +++ b/cp/cp-10773.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10773", "name": "LeetCode 1348: Tweet Counts Per Frequency"} +{"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: Tweet Counts Per Frequency (Difficulty: Medium)\nTags: Hash Table, Binary Search, Design, Sorting, Ordered Set\n\nA social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day).\nFor example, the period [10, 10000] (in seconds) would be partitioned into the following time chunks with these frequencies:\nNotice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example).\nDesign and implement an API to help the company with their analysis.\nImplement the TweetCounts class:\nExample:\n\nExample 1:\nInput\n[\"TweetCounts\",\"recordTweet\",\"recordTweet\",\"recordTweet\",\"getTweetCountsPerFrequency\",\"getTweetCountsPerFrequency\",\"recordTweet\",\"getTweetCountsPerFrequency\"]\n[[],[\"tweet3\",0],[\"tweet3\",60],[\"tweet3\",10],[\"minute\",\"tweet3\",0,59],[\"minute\",\"tweet3\",0,60],[\"tweet3\",120],[\"hour\",\"tweet3\",0,210]]\n\nOutput\n[null,null,null,null,[2],[2,1],null,[4]]\n\nExplanation\nTweetCounts tweetCounts = new TweetCounts();\ntweetCounts.recordTweet(\"tweet3\", 0); // New tweet \"tweet3\" at time 0\ntweetCounts.recordTweet(\"tweet3\", 60); // New tweet \"tweet3\" at time 60\ntweetCounts.recordTweet(\"tweet3\", 10); // New tweet \"tweet3\" at time 10\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 59); // return [2]; chunk [0,59] had 2 tweets\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet\ntweetCounts.recordTweet(\"tweet3\", 120); // New tweet \"tweet3\" at time 120\ntweetCounts.getTweetCountsPerFrequency(\"hour\", \"tweet3\", 0, 210); // return [4]; chunk [0,210] had 4 tweets\n\nConstraints:\n- 0 <= time, startTime, endTime <= 10^9\n- 0 <= endTime - startTime <= 10^4\n- There will be at most 104 calls in total to recordTweet and getTweetCountsPerFrequency."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: add: O(logn),\n# query: O(c), c is the total count of matching records\n# Space: O(n)\n\nimport collections\nimport random\n\n\n# Template:\n# https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/design-skiplist.py\nclass SkipNode(object):\n def __init__(self, level=0, val=None):\n self.val = val\n self.nexts = [None]*level\n self.prevs = [None]*level\n\nclass SkipList(object):\n P_NUMERATOR, P_DENOMINATOR = 1, 2 # P = 1/4 in redis implementation\n MAX_LEVEL = 32 # enough for 2^32 elements\n\n def __init__(self, end=float(\"inf\"), can_duplicated=False):\n random.seed(0)\n self.__head = SkipNode()\n self.__len = 0\n self.__can_duplicated = can_duplicated\n self.add(end)\n \n def lower_bound(self, target):\n return self.__lower_bound(target, self.__find_prev_nodes(target))\n\n def find(self, target):\n return self.__find(target, self.__find_prev_nodes(target))\n \n def add(self, val):\n if not self.__can_duplicated and self.find(val):\n return False\n node = SkipNode(self.__random_level(), val)\n if len(self.__head.nexts) < len(node.nexts): \n self.__head.nexts.extend([None]*(len(node.nexts)-len(self.__head.nexts)))\n prevs = self.__find_prev_nodes(val)\n for i in range(len(node.nexts)):\n node.nexts[i] = prevs[i].nexts[i]\n if prevs[i].nexts[i]:\n prevs[i].nexts[i].prevs[i] = node\n prevs[i].nexts[i] = node\n node.prevs[i] = prevs[i]\n self.__len += 1\n return True\n\n def remove(self, val):\n prevs = self.__find_prev_nodes(val)\n curr = self.__find(val, prevs)\n if not curr:\n return False\n self.__len -= 1 \n for i in reversed(range(len(curr.nexts))):\n prevs[i].nexts[i] = curr.nexts[i]\n if curr.nexts[i]:\n curr.nexts[i].prevs[i] = prevs[i]\n if not self.__head.nexts[i]:\n self.__head.nexts.pop()\n return True\n \n def __lower_bound(self, val, prevs):\n if prevs:\n candidate = prevs[0].nexts[0]\n if candidate:\n return candidate\n return None\n\n def __find(self, val, prevs):\n candidate = self.__lower_bound(val, prevs)\n if candidate and candidate.val == val:\n return candidate\n return None\n\n def __find_prev_nodes(self, val):\n prevs = [None]*len(self.__head.nexts)\n curr = self.__head\n for i in reversed(range(len(self.__head.nexts))):\n while curr.nexts[i] and curr.nexts[i].val < val:\n curr = curr.nexts[i]\n prevs[i] = curr\n return prevs\n\n def __random_level(self):\n level = 1\n while random.randint(1, SkipList.P_DENOMINATOR) <= SkipList.P_NUMERATOR and \\\n level < SkipList.MAX_LEVEL:\n level += 1\n return level\n\n def __len__(self):\n return self.__len-1 # excluding end node\n \n def __str__(self):\n result = []\n for i in reversed(range(len(self.__head.nexts))):\n result.append([])\n curr = self.__head.nexts[i]\n while curr:\n result[-1].append(str(curr.val))\n curr = curr.nexts[i]\n return \"\\n\".join(map(lambda x: \"->\".join(x), result))\n\n \nclass TweetCounts(object):\n\n def __init__(self):\n self.__records = collections.defaultdict(lambda: SkipList(can_duplicated=True))\n self.__lookup = {\"minute\":60, \"hour\":3600, \"day\":86400}\n\n def recordTweet(self, tweetName, time):\n \"\"\"\n :type tweetName: str\n :type time: int\n :rtype: None\n \"\"\"\n self.__records[tweetName].add(time)\n\n def getTweetCountsPerFrequency(self, freq, tweetName, startTime, endTime):\n \"\"\"\n :type freq: str\n :type tweetName: str\n :type startTime: int\n :type endTime: int\n :rtype: List[int]\n \"\"\"\n delta = self.__lookup[freq]\n result = [0]*((endTime-startTime)//delta+1)\n it = self.__records[tweetName].lower_bound(startTime)\n while it is not None and it.val <= endTime:\n result[(it.val-startTime)//delta] += 1\n it = it.nexts[0]\n return result\n\n\n# Time: add: O(n),\n# query: O(rlogn), r is the size of result\n# Space: O(n)\nimport bisect\nclass TweetCounts2(object):\n\n def __init__(self):\n self.__records = collections.defaultdict(list)\n self.__lookup = {\"minute\":60, \"hour\":3600, \"day\":86400}\n\n def recordTweet(self, tweetName, time):\n \"\"\"\n :type tweetName: str\n :type time: int\n :rtype: None\n \"\"\"\n bisect.insort(self.__records[tweetName], time)\n\n def getTweetCountsPerFrequency(self, freq, tweetName, startTime, endTime):\n \"\"\"\n :type freq: str\n :type tweetName: str\n :type startTime: int\n :type endTime: int\n :rtype: List[int]\n \"\"\"\n delta = self.__lookup[freq]\n i = startTime\n result = []\n while i <= endTime:\n j = min(i+delta, endTime+1)\n result.append(bisect.bisect_left(self.__records[tweetName], j) - \\\n bisect.bisect_left(self.__records[tweetName], i))\n i += delta\n return result\n\n \n# Time: add: O(1),\n# query: O(n)\n# Space: O(n)\nclass TweetCounts3(object):\n\n def __init__(self):\n self.__records = collections.defaultdict(list)\n self.__lookup = {\"minute\":60, \"hour\":3600, \"day\":86400}\n\n def recordTweet(self, tweetName, time):\n \"\"\"\n :type tweetName: str\n :type time: int\n :rtype: None\n \"\"\"\n self.__records[tweetName].append(time)\n\n def getTweetCountsPerFrequency(self, freq, tweetName, startTime, endTime):\n \"\"\"\n :type freq: str\n :type tweetName: str\n :type startTime: int\n :type endTime: int\n :rtype: List[int]\n \"\"\"\n delta = self.__lookup[freq]\n result = [0]*((endTime- startTime)//delta+1)\n for t in self.__records[tweetName]:\n if startTime <= t <= endTime:\n result[(t-startTime)//delta] += 1\n return result\n"}} diff --git a/cp/cp-10774.jsonl b/cp/cp-10774.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b3530b3ef569b00ea3fe95e32bfc50f538b762fb --- /dev/null +++ b/cp/cp-10774.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10774", "name": "LeetCode 1349: Maximum Students Taking Exam"} +{"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 Students Taking Exam (Difficulty: Hard)\nTags: Array, Dynamic Programming, Bit Manipulation, Matrix, Bitmask\n\nGiven a m * n matrix seats  that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character.\nStudents can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible.\nStudents must be placed in seats in good condition.\n\nExample 1:\nInput: seats = [[\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n  [\".\",\"#\",\"#\",\"#\",\"#\",\".\"],\n  [\"#\",\".\",\"#\",\"#\",\".\",\"#\"]]\nOutput: 4\nExplanation: Teacher can place 4 students in available seats so they don't cheat on the exam.\n\nExample 2:\nInput: seats = [[\".\",\"#\"],\n  [\"#\",\"#\"],\n  [\"#\",\".\"],\n  [\"#\",\"#\"],\n  [\".\",\"#\"]]\nOutput: 3\nExplanation: Place all students in available seats.\n\nExample 3:\nInput: seats = [[\"#\",\".\",\".\",\".\",\"#\"],\n  [\".\",\"#\",\".\",\"#\",\".\"],\n  [\".\",\".\",\"#\",\".\",\".\"],\n  [\".\",\"#\",\".\",\"#\",\".\"],\n  [\"#\",\".\",\".\",\".\",\"#\"]]\nOutput: 10\nExplanation: Place students in available seats in column 1, 3 and 5.\n\nConstraints:\n- seats contains only characters '.' and'#'.\n- m == seats.length\n- n == seats[i].length\n- 1 <= m <= 8\n- 1 <= n <= 8"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n * sqrt(m * n))\n# Space: O(m * n)\n\n# the problem is the same as google codejam 2008 round 3 problem C\n# https://github.com/kamyu104/GoogleCodeJam-2008/blob/master/Round%203/no_cheating.py\n\nimport collections\n\n\nfrom functools import partial\n\n# Time: O(E * sqrt(V))\n# Space: O(V)\n# Source code from http://code.activestate.com/recipes/123641-hopcroft-karp-bipartite-matching/\n# Hopcroft-Karp bipartite max-cardinality matching and max independent set\n# David Eppstein, UC Irvine, 27 Apr 2002\ndef bipartiteMatch(graph):\n '''Find maximum cardinality matching of a bipartite graph (U,V,E).\n The input format is a dictionary mapping members of U to a list\n of their neighbors in V. The output is a triple (M,A,B) where M is a\n dictionary mapping members of V to their matches in U, A is the part\n of the maximum independent set in U, and B is the part of the MIS in V.\n The same object may occur in both U and V, and is treated as two\n distinct vertices if this happens.'''\n \n # initialize greedy matching (redundant, but faster than full search)\n matching = {}\n for u in graph:\n for v in graph[u]:\n if v not in matching:\n matching[v] = u\n break\n \n while 1:\n # structure residual graph into layers\n # pred[u] gives the neighbor in the previous layer for u in U\n # preds[v] gives a list of neighbors in the previous layer for v in V\n # unmatched gives a list of unmatched vertices in final layer of V,\n # and is also used as a flag value for pred[u] when u is in the first layer\n preds = {}\n unmatched = []\n pred = dict([(u,unmatched) for u in graph])\n for v in matching:\n del pred[matching[v]]\n layer = list(pred)\n \n # repeatedly extend layering structure by another pair of layers\n while layer and not unmatched:\n newLayer = {}\n for u in layer:\n for v in graph[u]:\n if v not in preds:\n newLayer.setdefault(v,[]).append(u)\n layer = []\n for v in newLayer:\n preds[v] = newLayer[v]\n if v in matching:\n layer.append(matching[v])\n pred[matching[v]] = v\n else:\n unmatched.append(v)\n \n # did we finish layering without finding any alternating paths?\n if not unmatched:\n unlayered = {}\n for u in graph:\n for v in graph[u]:\n if v not in preds:\n unlayered[v] = None\n return (matching,list(pred),list(unlayered))\n\n # recursively search backward through layers to find alternating paths\n # recursion returns true if found path, false otherwise\n def recurse(v):\n if v in preds:\n L = preds[v]\n del preds[v]\n for u in L:\n if u in pred:\n pu = pred[u]\n del pred[u]\n if pu is unmatched or recurse(pu):\n matching[v] = u\n return 1\n return 0\n \n def recurse_iter(v):\n def divide(v):\n if v not in preds:\n return\n L = preds[v]\n del preds[v]\n for u in L :\n if u in pred and pred[u] is unmatched: # early return\n del pred[u]\n matching[v] = u\n ret[0] = True\n return\n stk.append(partial(conquer, v, iter(L)))\n\n def conquer(v, it):\n for u in it:\n if u not in pred:\n continue\n pu = pred[u]\n del pred[u]\n stk.append(partial(postprocess, v, u, it))\n stk.append(partial(divide, pu))\n return\n\n def postprocess(v, u, it):\n if not ret[0]:\n stk.append(partial(conquer, v, it))\n return\n matching[v] = u\n\n ret, stk = [False], []\n stk.append(partial(divide, v))\n while stk:\n stk.pop()()\n return ret[0]\n\n for v in unmatched: recurse_iter(v)\n\n\n# Hopcroft-Karp bipartite matching\nclass Solution(object):\n def maxStudents(self, seats):\n \"\"\"\n :type seats: List[List[str]]\n :rtype: int\n \"\"\"\n directions = [(-1, -1), (0, -1), (1, -1), (-1, 1), (0, 1), (1, 1)]\n E, count = collections.defaultdict(list), 0\n for i in range(len(seats)):\n for j in range(len(seats[0])):\n if seats[i][j] != '.':\n continue\n count += 1\n if j%2:\n continue\n for dx, dy in directions:\n ni, nj = i+dx, j+dy\n if 0 <= ni < len(seats) and \\\n 0 <= nj < len(seats[0]) and \\\n seats[ni][nj] == '.':\n E[i*len(seats[0])+j].append(ni*len(seats[0])+nj)\n return count-len(bipartiteMatch(E)[0])\n\n\n# Time: O(|V| * |E|) = O(m^2 * n^2)\n# Space: O(|V| + |E|) = O(m * n)\n# Hungarian bipartite matching\nclass Solution2(object):\n def maxStudents(self, seats):\n \"\"\"\n :type seats: List[List[str]]\n :rtype: int\n \"\"\"\n directions = [(-1, -1), (0, -1), (1, -1), (-1, 1), (0, 1), (1, 1)]\n def dfs(seats, e, lookup, matching):\n i, j = e\n for dx, dy in directions:\n ni, nj = i+dx, j+dy\n if 0 <= ni < len(seats) and 0 <= nj < len(seats[0]) and \\\n seats[ni][nj] == '.' and not lookup[ni][nj]:\n lookup[ni][nj] = True\n if matching[ni][nj] == -1 or dfs(seats, matching[ni][nj], lookup, matching):\n matching[ni][nj] = e\n return True\n return False\n \n def Hungarian(seats):\n result = 0\n matching = [[-1]*len(seats[0]) for _ in range(len(seats))]\n for i in range(len(seats)):\n for j in range(0, len(seats[0]), 2):\n if seats[i][j] != '.':\n continue\n lookup = [[False]*len(seats[0]) for _ in range(len(seats))]\n if dfs(seats, (i, j), lookup, matching):\n result += 1\n return result\n \n count = 0\n for i in range(len(seats)):\n for j in range(len(seats[0])):\n if seats[i][j] == '.':\n count += 1\n return count-Hungarian(seats)\n\n\n# Time: O(m * 2^n * 2^n) = O(m * 4^n)\n# Space: O(2^n)\n# dp solution\nclass Solution3(object):\n def maxStudents(self, seats):\n \"\"\"\n :type seats: List[List[str]]\n :rtype: int\n \"\"\"\n def popcount(n):\n result = 0\n while n:\n n &= n - 1\n result += 1\n return result\n \n dp = {0: 0}\n for row in seats:\n invalid_mask = sum(1 << c for c, v in enumerate(row) if v == '#')\n new_dp = {}\n for mask1, v1 in dp.iteritems():\n for mask2 in range(1 << len(seats[0])):\n if (mask2 & invalid_mask) or \\\n (mask2 & (mask1 << 1)) or (mask2 & (mask1 >> 1)) or \\\n (mask2 & (mask2 << 1)) or (mask2 & (mask2 >> 1)):\n continue\n new_dp[mask2] = max(new_dp.get(mask2, 0), v1+popcount(mask2))\n dp = new_dp\n return max(dp.itervalues()) if dp else 0\n"}} diff --git a/cp/cp-10775.jsonl b/cp/cp-10775.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..81e7943c8c02d51f8cfbb03ba674e2c42aea7819 --- /dev/null +++ b/cp/cp-10775.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10775", "name": "LeetCode 1351: Count Negative Numbers In A Sorted Matrix"} +{"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: Count Negative Numbers in a Sorted Matrix (Difficulty: Easy)\nTags: Array, Binary Search, Matrix\n\nGiven a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.\n\nExample 1:\nInput: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]\nOutput: 8\nExplanation: There are 8 negatives number in the matrix.\n\nExample 2:\nInput: grid = [[3,2],[1,0]]\nOutput: 0\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 100\n- -100 <= grid[i][j] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n)\n# Space: O(1)\n\nclass Solution(object):\n def countNegatives(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n result, c = 0, len(grid[0])-1\n for row in grid:\n while c >= 0 and row[c] < 0:\n c -= 1\n result += len(grid[0])-1-c\n return result\n"}} diff --git a/cp/cp-10776.jsonl b/cp/cp-10776.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..87684b1ac7ba711873372098595b758bdd0ae4ff --- /dev/null +++ b/cp/cp-10776.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10776", "name": "LeetCode 1352: Product Of The Last K 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: Product of the Last K Numbers (Difficulty: Medium)\nTags: Array, Math, Design, Data Stream, Prefix Sum\n\nDesign an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream.\nImplement the ProductOfNumbers class:\nThe test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.\nExample:\n\nExample 1:\nInput\n[\"ProductOfNumbers\",\"add\",\"add\",\"add\",\"add\",\"add\",\"getProduct\",\"getProduct\",\"getProduct\",\"add\",\"getProduct\"]\n[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]\n\nOutput\n[null,null,null,null,null,null,20,40,0,null,32]\n\nExplanation\nProductOfNumbers productOfNumbers = new ProductOfNumbers();\nproductOfNumbers.add(3); // [3]\nproductOfNumbers.add(0); // [3,0]\nproductOfNumbers.add(2); // [3,0,2]\nproductOfNumbers.add(5); // [3,0,2,5]\nproductOfNumbers.add(4); // [3,0,2,5,4]\nproductOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20\nproductOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40\nproductOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0\nproductOfNumbers.add(8); // [3,0,2,5,4,8]\nproductOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32\n\nConstraints:\n- 0 <= num <= 100\n- 1 <= k <= 4 * 10^4\n- At most 4 * 10^4 calls will be made to add and getProduct.\n- The product of the stream at any point in time will fit in a 32-bit integer."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(1)\n# add : O(1)\n# get : O(1)\n# Space: O(n)\n\nclass ProductOfNumbers(object):\n\n def __init__(self):\n self.__accu = [1]\n\n def add(self, num):\n \"\"\"\n :type num: int\n :rtype: None\n \"\"\"\n if not num:\n self.__accu = [1]\n return\n self.__accu.append(self.__accu[-1]*num) \n\n def getProduct(self, k):\n \"\"\"\n :type k: int\n :rtype: int\n \"\"\"\n if len(self.__accu) <= k:\n return 0\n return self.__accu[-1] // self.__accu[-1-k]\n"}} diff --git a/cp/cp-10777.jsonl b/cp/cp-10777.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..679306181cb2348cfe7aa3c570f4ab95bf4aa224 --- /dev/null +++ b/cp/cp-10777.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10777", "name": "LeetCode 1353: Maximum Number Of Events That Can Be Attended"} +{"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 Number of Events That Can Be Attended (Difficulty: Medium)\nTags: Array, Greedy, Sorting, Heap (Priority Queue)\n\nYou are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.\nYou can attend an event i at any day d where startDayi <= d <= endDayi. You can only attend one event at any time d.\nReturn the maximum number of events you can attend.\n\nExample 1:\nInput: events = [[1,2],[2,3],[3,4]]\nOutput: 3\nExplanation: You can attend all the three events.\nOne way to attend them all is as shown.\nAttend the first event on day 1.\nAttend the second event on day 2.\nAttend the third event on day 3.\n\nExample 2:\nInput: events= [[1,2],[2,3],[3,4],[1,2]]\nOutput: 4\n\nConstraints:\n- 1 <= events.length <= 10^5\n- events[i].length == 2\n- 1 <= startDayi <= endDayi <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(r + nlogn), r is the max end day of events\n# Space: O(n)\n\nimport heapq\n\n\nclass Solution(object):\n def maxEvents(self, events):\n \"\"\"\n :type events: List[List[int]]\n :rtype: int\n \"\"\"\n events.sort(reverse=True)\n min_heap = []\n result = 0\n for d in range(1, max(events, key=lambda x:x[1])[1]+1):\n while events and events[-1][0] == d:\n heapq.heappush(min_heap, events.pop()[1])\n while min_heap and min_heap[0] == d-1:\n heapq.heappop(min_heap)\n if not min_heap:\n continue\n heapq.heappop(min_heap)\n result += 1 \n return result\n"}} diff --git a/cp/cp-10778.jsonl b/cp/cp-10778.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4e6aa2db4ae9b6cea08bdb791333a2bdce0e7339 --- /dev/null +++ b/cp/cp-10778.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10778", "name": "LeetCode 1354: Construct Target Array With Multiple Sums"} +{"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 Target Array With Multiple Sums (Difficulty: Hard)\nTags: Array, Heap (Priority Queue)\n\nYou are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure :\nReturn true if it is possible to construct the target array from arr, otherwise, return false.\n\nExample 1:\nInput: target = [9,3,5]\nOutput: true\nExplanation: Start with arr = [1, 1, 1] \n[1, 1, 1], sum = 3 choose index 1\n[1, 3, 1], sum = 5 choose index 2\n[1, 3, 5], sum = 9 choose index 0\n[9, 3, 5] Done\n\nExample 2:\nInput: target = [1,1,1,2]\nOutput: false\nExplanation: Impossible to create target array from [1,1,1,1].\n\nExample 3:\nInput: target = [8,5]\nOutput: true\n\nConstraints:\n- n == target.length\n- 1 <= n <= 5 * 10^4\n- 1 <= target[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(log(max(t)) * logn)\n# Space: O(n)\n\nimport heapq\n\n\nclass Solution(object):\n def isPossible(self, target):\n \"\"\"\n :type target: List[int]\n :rtype: bool\n \"\"\"\n # (1) x + remain = y\n # (2) y + remain = total\n # (1) - (2) => x - y = y - total\n # => x = 2*y - total\n total = sum(target)\n max_heap = [-x for x in target]\n heapq.heapify(max_heap)\n while total != len(target):\n y = -heapq.heappop(max_heap)\n remain = total-y\n x = y-remain\n if x <= 0:\n return False\n if x > remain: # for case [1, 1000000000]\n x = x%remain + remain\n heapq.heappush(max_heap, -x)\n total = x+remain\n return True\n"}} diff --git a/cp/cp-10779.jsonl b/cp/cp-10779.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9be7757d3f88666e48fb8c4b49174bded5d122e7 --- /dev/null +++ b/cp/cp-10779.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10779", "name": "LeetCode 1356: Sort Integers By The Number Of 1 Bits"} +{"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: Sort Integers by The Number of 1 Bits (Difficulty: Easy)\nTags: Array, Bit Manipulation, Sorting, Counting\n\nYou are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.\nReturn the array after sorting it.\n\nExample 1:\nInput: arr = [0,1,2,3,4,5,6,7,8]\nOutput: [0,1,2,4,8,3,5,6,7]\nExplantion: [0] is the only integer with 0 bits.\n[1,2,4,8] all have 1 bit.\n[3,5,6] have 2 bits.\n[7] has 3 bits.\nThe sorted array by bits is [0,1,2,4,8,3,5,6,7]\n\nExample 2:\nInput: arr = [1024,512,256,128,64,32,16,8,4,2,1]\nOutput: [1,2,4,8,16,32,64,128,256,512,1024]\nExplantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.\n\nConstraints:\n- 1 <= arr.length <= 500\n- 0 <= arr[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def sortByBits(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: List[int]\n \"\"\"\n def popcount(n): # Time: O(logn) ~= O(1) if n is a 32-bit number\n result = 0\n while n:\n n &= n - 1\n result += 1\n return result\n \n arr.sort(key=lambda x: (popcount(x), x))\n return arr\n"}} diff --git a/cp/cp-10780.jsonl b/cp/cp-10780.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..be122813a68e450d9d7034505bae4a39a7a3ff41 --- /dev/null +++ b/cp/cp-10780.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10780", "name": "LeetCode 1357: Apply Discount Every N Orders"} +{"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: Apply Discount Every n Orders (Difficulty: Medium)\nTags: Array, Hash Table, Design\n\nThere is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products and prices, where the ith product has an ID of products[i] and a price of prices[i].\nWhen a customer is paying, their bill is represented as two parallel integer arrays product and amount, where the jth product they purchased has an ID of product[j], and amount[j] is how much of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price of the jth product).\nThe supermarket decided to have a sale. Every nth customer paying for their groceries will be given a percentage discount. The discount amount is given by discount, where they will be given discount percent off their subtotal. More formally, if their subtotal is bill, then they would actually pay bill * ((100 - discount) / 100).\nImplement the Cashier class:\n\nExample 1:\nInput\n[\"Cashier\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\"]\n[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]\nOutput\n[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]\nExplanation\nCashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);\ncashier.getBill([1,2],[1,2]); // return 500.0. 1st customer, no discount.\n // bill = 1 * 100 + 2 * 200 = 500.\ncashier.getBill([3,7],[10,10]); // return 4000.0. 2nd customer, no discount.\n // bill = 10 * 300 + 10 * 100 = 4000.\ncashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]); // return 800.0. 3rd customer, 50% discount.\n // Original bill = 1600\n // Actual bill = 1600 * ((100 - 50) / 100) = 800.\ncashier.getBill([4],[10]); // return 4000.0. 4th customer, no discount.\ncashier.getBill([7,3],[10,10]); // return 4000.0. 5th customer, no discount.\ncashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return 7350.0. 6th customer, 50% discount.\n // Original bill = 14700, but with\n // Actual bill = 14700 * ((100 - 50) / 100) = 7350.\ncashier.getBill([2,3,5],[5,3,2]); // return 2500.0. 7th customer, no discount.\n\nConstraints:\n- 1 <= n <= 10^4\n- 0 <= discount <= 100\n- 1 <= products.length <= 200\n- prices.length == products.length\n- 1 <= products[i] <= 200\n- 1 <= prices[i] <= 1000\n- The elements in products are unique.\n- 1 <= product.length <= products.length\n- amount.length == product.length\n- product[j] exists in products.\n- 1 <= amount[j] <= 1000\n- The elements of product are unique.\n- At most 1000 calls will be made to getBill.\n- Answers within 10-5 of the actual value will be accepted."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(m), m is the number of all products\n# getBill: O(p), p is the number of products to bill\n# Space: O(m)\n\nclass Cashier(object):\n\n def __init__(self, n, discount, products, prices):\n \"\"\"\n :type n: int\n :type discount: int\n :type products: List[int]\n :type prices: List[int]\n \"\"\"\n self.__n = n\n self.__discount = discount\n self.__curr = 0\n self.__lookup = {p : prices[i] for i, p in enumerate(products)}\n\n def getBill(self, product, amount):\n \"\"\"\n :type product: List[int]\n :type amount: List[int]\n :rtype: float\n \"\"\"\n self.__curr = (self.__curr+1) % self.__n\n result = 0.0\n for i, p in enumerate(product):\n result += self.__lookup[p]*amount[i]\n return result * (1.0 - self.__discount/100.0 if self.__curr == 0 else 1.0) \n"}} diff --git a/cp/cp-10781.jsonl b/cp/cp-10781.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7e516a87da956cd3df43599bc7e677b64b96e5d8 --- /dev/null +++ b/cp/cp-10781.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10781", "name": "LeetCode 1358: Number Of Substrings Containing All Three Characters"} +{"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 Substrings Containing All Three Characters (Difficulty: Medium)\nTags: Hash Table, String, Sliding Window\n\nGiven a string s consisting only of characters a, b and c.\nReturn the number of substrings containing at least one occurrence of all these characters a, b and c.\n\nExample 1:\nInput: s = \"abcabc\"\nOutput: 10\nExplanation: The substrings containing at least one occurrence of the characters a, b and c are \"abc\", \"abca\", \"abcab\", \"abcabc\", \"bca\", \"bcab\", \"bcabc\", \"cab\", \"cabc\" and \"abc\" (again).\n\nExample 2:\nInput: s = \"aaacb\"\nOutput: 3\nExplanation: The substrings containing at least one occurrence of the characters a, b and c are \"aaacb\", \"aacb\" and \"acb\".\n\nExample 3:\nInput: s = \"abc\"\nOutput: 1\n\nConstraints:\n- 3 <= s.length <= 5 x 10^4\n- s only consists of a, b or c characters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def numberOfSubstrings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result, left = 0, [-1]*3\n for right, c in enumerate(s):\n left[ord(c)-ord('a')] = right\n result += min(left)+1\n return result\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def numberOfSubstrings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result, left, count = 0, 0, [0]*3\n for right, c in enumerate(s):\n count[ord(s[right])-ord('a')] += 1\n while all(count):\n count[ord(s[left])-ord('a')] -= 1\n left += 1\n result += left\n return result\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution3(object):\n def numberOfSubstrings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result, right, count = 0, 0, [0]*3\n for left, c in enumerate(s):\n while right < len(s) and not all(count):\n count[ord(s[right])-ord('a')] += 1\n right += 1\n if all(count):\n result += (len(s)-1) - (right-1) + 1\n count[ord(c)-ord('a')] -= 1\n return result\n"}} diff --git a/cp/cp-10782.jsonl b/cp/cp-10782.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5a79b1f1cff63cd3e4743722f0c3524612d1fe3f --- /dev/null +++ b/cp/cp-10782.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10782", "name": "LeetCode 1359: Count All Valid Pickup And Delivery Options"} +{"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: Count All Valid Pickup and Delivery Options (Difficulty: Hard)\nTags: Math, Dynamic Programming, Combinatorics\n\nGiven n orders, each order consists of a pickup and a delivery service.\nCount all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).\nSince the answer may be too large, return it modulo 10^9 + 7.\n\nExample 1:\nInput: n = 1\nOutput: 1\nExplanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.\n\nExample 2:\nInput: n = 2\nOutput: 6\nExplanation: All possible orders: \n(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).\nThis is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.\n\nExample 3:\nInput: n = 3\nOutput: 90\n\nConstraints:\n- 1 <= n <= 500"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def countOrders(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n result = 1\n for i in reversed(range(2, 2*n+1, 2)):\n result = result * i*(i-1)//2 % MOD\n return result\n"}} diff --git a/cp/cp-10783.jsonl b/cp/cp-10783.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7dbdb1cb675c1441cb1ea5ad7d6a9748d32d1584 --- /dev/null +++ b/cp/cp-10783.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10783", "name": "LeetCode 1360: Number Of Days Between Two Dates"} +{"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 Days Between Two Dates (Difficulty: Easy)\nTags: Math, String\n\nWrite a program to count the number of days between two dates.\nThe two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.\n\nExample 1:\nInput: date1 = \"2019-06-29\", date2 = \"2019-06-30\"\nOutput: 1\n\nExample 2:\nInput: date1 = \"2020-01-15\", date2 = \"2019-12-31\"\nOutput: 15\n\nConstraints:\n- The given dates are valid dates between the years 1971 and 2100."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def __init__(self):\n def dayOfMonth(M):\n return (28 if (M == 2) else 31-(M-1)%7%2)\n\n self.__lookup = [0]*12\n for M in range(1, len(self.__lookup)):\n self.__lookup[M] += self.__lookup[M-1]+dayOfMonth(M)\n\n def daysBetweenDates(self, date1, date2):\n \"\"\"\n :type date1: str\n :type date2: str\n :rtype: int\n \"\"\"\n def num_days(date):\n Y, M, D = map(int, date.split(\"-\"))\n leap = 1 if M > 2 and (((Y % 4 == 0) and (Y % 100 != 0)) or (Y % 400 == 0)) else 0\n return (Y-1)*365 + ((Y-1)//4 - (Y-1)//100 + (Y-1)//400) + self.__lookup[M-1]+D+leap\n \n return abs(num_days(date1) - num_days(date2))\n\n\n# Time: O(1)\n# Space: O(1)\nimport datetime\n\n\nclass Solution2(object):\n def daysBetweenDates(self, date1, date2): \n delta = datetime.datetime.strptime(date1, \"%Y-%m-%d\")\n delta -= datetime.datetime.strptime(date2, \"%Y-%m-%d\")\n return abs(delta.days)\n"}} diff --git a/cp/cp-10784.jsonl b/cp/cp-10784.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9bd7a87b4053f47390d82c10e0d1c182ad724244 --- /dev/null +++ b/cp/cp-10784.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10784", "name": "LeetCode 1361: Validate Binary Tree Nodes"} +{"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: Validate Binary Tree Nodes (Difficulty: Medium)\nTags: Tree, Depth-First Search, Breadth-First Search, Union Find, Graph, Binary Tree\n\nYou have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.\nIf node i has no left child then leftChild[i] will equal -1, similarly for the right child.\nNote that the nodes have no values and that we only use the node numbers in this problem.\n\nExample 1:\nInput: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]\nOutput: true\n\nExample 2:\nInput: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]\nOutput: false\n\nExample 3:\nInput: n = 2, leftChild = [1,0], rightChild = [-1,-1]\nOutput: false\n\nConstraints:\n- n == leftChild.length == rightChild.length\n- 1 <= n <= 10^4\n- -1 <= leftChild[i], rightChild[i] <= n - 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def validateBinaryTreeNodes(self, n, leftChild, rightChild):\n \"\"\"\n :type n: int\n :type leftChild: List[int]\n :type rightChild: List[int]\n :rtype: bool\n \"\"\"\n roots = set(range(n)) - set(leftChild) - set(rightChild)\n if len(roots) != 1:\n return False\n root, = roots\n stk = [root]\n lookup = set([root])\n while stk:\n node = stk.pop()\n for c in (leftChild[node], rightChild[node]):\n if c < 0:\n continue\n if c in lookup:\n return False\n lookup.add(c)\n stk.append(c)\n return len(lookup) == n\n"}} diff --git a/cp/cp-10785.jsonl b/cp/cp-10785.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5feef7a099a943d42424b747a3ce77e00b7e49a4 --- /dev/null +++ b/cp/cp-10785.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10785", "name": "LeetCode 1362: Closest Divisors"} +{"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: Closest Divisors (Difficulty: Medium)\nTags: Math\n\nGiven an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2.\nReturn the two integers in any order.\n\nExample 1:\nInput: num = 8\nOutput: [3,3]\nExplanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.\n\nExample 2:\nInput: num = 123\nOutput: [5,25]\n\nExample 3:\nInput: num = 999\nOutput: [40,25]\n\nConstraints:\n- 1 <= num <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(sqrt(n))\n# Space: O(1)\n\nclass Solution(object):\n def closestDivisors(self, num):\n \"\"\"\n :type num: int\n :rtype: List[int]\n \"\"\"\n def divisors(n):\n for d in reversed(range(1, int(n**0.5)+1)):\n if n % d == 0:\n return d, n//d\n return 1, n\n\n return min([divisors(num+1), divisors(num+2)], key=lambda x: x[1]-x[0])\n\n\n\n# Time: O(sqrt(n))\n# Space: O(1)\nclass Solution2(object):\n def closestDivisors(self, num):\n \"\"\"\n :type num: int\n :rtype: List[int]\n \"\"\"\n result, d = [1, num+1], 1\n while d*d <= num+2:\n if (num+2) % d == 0:\n result = [d, (num+2)//d]\n if (num+1) % d == 0:\n result = [d, (num+1)//d]\n d += 1\n return result\n"}} diff --git a/cp/cp-10786.jsonl b/cp/cp-10786.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a46f61d4b281658c48943dfa1942ee659b6ac76f --- /dev/null +++ b/cp/cp-10786.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10786", "name": "LeetCode 1363: Largest Multiple Of Three"} +{"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: Largest Multiple of Three (Difficulty: Hard)\nTags: Array, Math, Dynamic Programming, Greedy, Sorting\n\nGiven an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string.\nSince the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.\n\nExample 1:\nInput: digits = [8,1,9]\nOutput: \"981\"\n\nExample 2:\nInput: digits = [8,6,7,1,0]\nOutput: \"8760\"\n\nExample 3:\nInput: digits = [1]\nOutput: \"\"\n\nConstraints:\n- 1 <= digits.length <= 10^4\n- 0 <= digits[i] <= 9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def largestMultipleOfThree(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: str\n \"\"\"\n lookup = {0: [],\n 1: [(1,), (4,), (7,), (2, 2), (5, 2), (5, 5), (8, 2), (8, 5), (8, 8)],\n 2: [(2,), (5,), (8,), (1, 1), (4, 1), (4, 4), (7, 1), (7, 4), (7, 7)]}\n count = collections.Counter(digits)\n for deletes in lookup[sum(digits)%3]:\n delete_count = collections.Counter(deletes)\n if all(count[k] >= v for k, v in delete_count.iteritems()):\n for k, v in delete_count.iteritems():\n count[k] -= v\n break\n result = \"\".join(str(d)*count[d] for d in reversed(range(10)))\n return \"0\" if result and result[0] == '0' else result\n \n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def largestMultipleOfThree(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: str\n \"\"\"\n def candidates_gen(r):\n if r == 0:\n return\n for i in range(10):\n yield [i]\n for i in range(10):\n for j in range(i+1):\n yield [i, j]\n\n count, r = collections.Counter(digits), sum(digits)%3\n for deletes in candidates_gen(r):\n delete_count = collections.Counter(deletes)\n if sum(deletes)%3 == r and \\\n all(count[k] >= v for k, v in delete_count.iteritems()):\n for k, v in delete_count.iteritems():\n count[k] -= v\n break\n result = \"\".join(str(d)*count[d] for d in reversed(range(10)))\n return \"0\" if result and result[0] == '0' else result\n"}} diff --git a/cp/cp-10787.jsonl b/cp/cp-10787.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9899a4b7fe6e9303ab240f5f0321b12961180100 --- /dev/null +++ b/cp/cp-10787.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10787", "name": "LeetCode 1365: How Many Numbers Are Smaller Than The Current 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: How Many Numbers Are Smaller Than the Current Number (Difficulty: Easy)\nTags: Array, Hash Table, Sorting, Counting Sort\n\nGiven the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].\nReturn the answer in an array.\n\nExample 1:\nInput: nums = [8,1,2,2,3]\nOutput: [4,0,1,1,3]\nExplanation: \nFor nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). \nFor nums[1]=1 does not exist any smaller number than it.\nFor nums[2]=2 there exist one smaller number than it (1). \nFor nums[3]=2 there exist one smaller number than it (1). \nFor nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).\n\nExample 2:\nInput: nums = [6,5,4,8]\nOutput: [2,1,0,3]\n\nExample 3:\nInput: nums = [7,7,7,7]\nOutput: [0,0,0,0]\n\nConstraints:\n- 2 <= nums.length <= 500\n- 0 <= nums[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + m), m is the max number of nums\n# Space: O(m)\n\nimport collections\n\n\nclass Solution(object):\n def smallerNumbersThanCurrent(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n count = collections.Counter(nums)\n for i in range(max(nums)+1):\n count[i] += count[i-1]\n return [count[i-1] for i in nums]\n\n\n# Time: O(nlogn)\n# Space: O(n)\nimport bisect\n\n\nclass Solution2(object):\n def smallerNumbersThanCurrent(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n sorted_nums = sorted(nums)\n return [bisect.bisect_left(sorted_nums, i) for i in nums]\n"}} diff --git a/cp/cp-10788.jsonl b/cp/cp-10788.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..abde82c2abca678d73d3f388486023a701a57bbd --- /dev/null +++ b/cp/cp-10788.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10788", "name": "LeetCode 1366: Rank Teams By Votes"} +{"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: Rank Teams by Votes (Difficulty: Medium)\nTags: Array, Hash Table, String, Sorting, Counting\n\nIn a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.\nThe ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.\nYou are given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.\nReturn a string of all teams sorted by the ranking system.\n\nExample 1:\nInput: votes = [\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]\nOutput: \"ACB\"\nExplanation: \nTeam A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team.\nTeam B was ranked second by 2 voters and ranked third by 3 voters.\nTeam C was ranked second by 3 voters and ranked third by 2 voters.\nAs most of the voters ranked C second, team C is the second team, and team B is the third.\n\nExample 2:\nInput: votes = [\"WXYZ\",\"XYZW\"]\nOutput: \"XWYZ\"\nExplanation:\nX is the winner due to the tie-breaking rule. X has the same votes as W for the first position, but X has one vote in the second position, while W does not have any votes in the second position.\n\nExample 3:\nInput: votes = [\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"]\nOutput: \"ZMNAGUEDSJYLBOPHRQICWFXTVK\"\nExplanation: Only one voter, so their votes are used for the ranking.\n\nConstraints:\n- 1 <= votes.length <= 1000\n- 1 <= votes[i].length <= 26\n- votes[i].length == votes[j].length for 0 <= i, j < votes.length.\n- votes[i][j] is an English uppercase letter.\n- All characters of votes[i] are unique.\n- All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * (n + mlogm)), n is the number of votes\n# , m is the length of vote\n# Space: O(m^2)\n\nclass Solution(object):\n def rankTeams(self, votes):\n \"\"\"\n :type votes: List[str]\n :rtype: str\n \"\"\"\n count = {v: [0]*len(votes[0]) + [v] for v in votes[0]}\n for vote in votes:\n for i, v in enumerate(vote):\n count[v][i] -= 1\n return \"\".join(sorted(votes[0], key=count.__getitem__))\n"}} diff --git a/cp/cp-10789.jsonl b/cp/cp-10789.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4757c16c9caa052c696c9486d87e3ec17796f777 --- /dev/null +++ b/cp/cp-10789.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10789", "name": "LeetCode 1367: Linked List 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: Linked List in Binary Tree (Difficulty: Medium)\nTags: Linked List, Tree, Depth-First Search, Binary Tree\n\nGiven a binary tree root and a linked list with head as the first node.\nReturn True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False.\nIn this context downward path means a path that starts at some node and goes downwards.\n\nExample 1:\nInput: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput: true\nExplanation: Nodes in blue form a subpath in the binary Tree.\n\nExample 2:\nInput: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput: true\n\nExample 3:\nInput: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput: false\nExplanation: There is no path in the binary tree that contains all the elements of the linked list from head.\n\nConstraints:\n- The number of nodes in the tree will be in the range [1, 2500].\n- The number of nodes in the list will be in the range [1, 100].\n- 1 <= Node.val <= 100 for each node in the linked list and binary tree."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + l)\n# Space: O(h + l)\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\n# kmp solution\nclass Solution(object):\n def isSubPath(self, head, root):\n \"\"\"\n :type head: ListNode\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n def getPrefix(head):\n pattern, prefix = [head.val], [-1]\n j = -1\n node = head.next\n while node:\n while j+1 and pattern[j+1] != node.val:\n j = prefix[j]\n if pattern[j+1] == node.val:\n j += 1\n pattern.append(node.val)\n prefix.append(j)\n node = node.next\n return pattern, prefix\n \n def dfs(pattern, prefix, root, j):\n if not root:\n return False\n while j+1 and pattern[j+1] != root.val:\n j = prefix[j]\n if pattern[j+1] == root.val:\n j += 1\n if j+1 == len(pattern):\n return True\n return dfs(pattern, prefix, root.left, j) or \\\n dfs(pattern, prefix, root.right, j)\n \n if not head:\n return True\n pattern, prefix = getPrefix(head)\n return dfs(pattern, prefix, root, -1)\n \n\n# Time: O(n * min(h, l))\n# Space: O(h)\n# dfs solution\nclass Solution2(object):\n def isSubPath(self, head, root):\n \"\"\"\n :type head: ListNode\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n def dfs(head, root):\n if not head:\n return True\n if not root:\n return False\n return root.val == head.val and \\\n (dfs(head.next, root.left) or \n dfs(head.next, root.right))\n \n if not head:\n return True\n if not root:\n return False\n return dfs(head, root) or \\\n self.isSubPath(head, root.left) or \\\n self.isSubPath(head, root.right)\n"}} diff --git a/cp/cp-10790.jsonl b/cp/cp-10790.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..739af23ac89dfd1a0a87dd72299a13c5096deed9 --- /dev/null +++ b/cp/cp-10790.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10790", "name": "LeetCode 1368: Minimum Cost To Make At Least One Valid Path In A Grid"} +{"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: Minimum Cost to Make at Least One Valid Path in a Grid (Difficulty: Hard)\nTags: Array, Breadth-First Search, Graph, Heap (Priority Queue), Matrix, Shortest Path\n\nGiven an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be:\nNotice that there could be some signs on the cells of the grid that point outside the grid.\nYou will initially start at the upper left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path does not have to be the shortest.\nYou can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.\nReturn the minimum cost to make the grid have at least one valid path.\n\nExample 1:\nInput: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]\nOutput: 3\nExplanation: You will start at point (0, 0).\nThe path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)\nThe total cost = 3.\n\nExample 2:\nInput: grid = [[1,1,3],[3,2,2],[1,1,4]]\nOutput: 0\nExplanation: You can follow the path from (0, 0) to (2, 2).\n\nExample 3:\nInput: grid = [[1,2],[4,3]]\nOutput: 1\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 100\n- 1 <= grid[i][j] <= 4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m * n)\n\n# A* Search Algorithm without heap\nclass Solution(object):\n def minCost(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n def a_star(grid, b, t):\n f, dh = 0, 1\n closer, detour = [b], []\n lookup = set()\n while closer or detour:\n if not closer:\n f += dh\n closer, detour = detour, closer\n b = closer.pop()\n if b in lookup:\n continue\n lookup.add(b)\n if b == t:\n return f\n for nd, (dr, dc) in enumerate(directions, 1):\n nb = (b[0]+dr, b[1]+dc)\n if not (0 <= nb[0] < len(grid) and 0 <= nb[1] < len(grid[0]) and nb not in lookup):\n continue\n (closer if nd == grid[b[0]][b[1]] else detour).append(nb)\n return -1\n\n return a_star(grid, (0, 0), (len(grid)-1, len(grid[0])-1))\n\n\n# Time: O(m * n)\n# Space: O(m * n)\nimport collections\n\n\n# 0-1 bfs solution\nclass Solution2(object):\n def minCost(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n b, t = (0, 0), (len(grid)-1, len(grid[0])-1)\n dq = collections.deque([(b, 0)])\n lookup = set()\n while dq:\n b, d = dq.popleft()\n if b in lookup:\n continue\n lookup.add(b)\n if b == t:\n return d\n for nd, (dr, dc) in enumerate(directions, 1):\n nb = (b[0]+dr, b[1]+dc)\n if not (0 <= nb[0] < len(grid) and 0 <= nb[1] < len(grid[0]) and nb not in lookup):\n continue\n if nd == grid[b[0]][b[1]]:\n dq.appendleft((nb, d))\n else:\n dq.append((nb, d+1))\n return -1 # never reach here\n"}} diff --git a/cp/cp-10791.jsonl b/cp/cp-10791.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..863fd5db7242b7ccbacd36bbfc371715ad56e9e4 --- /dev/null +++ b/cp/cp-10791.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10791", "name": "LeetCode 1370: Increasing Decreasing 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: Increasing Decreasing String (Difficulty: Easy)\nTags: Hash Table, String, Counting\n\nYou are given a string s. Reorder the string using the following algorithm:\nIf the smallest or largest character appears more than once, you may choose any occurrence to append to the result.\nReturn the resulting string after reordering s using this algorithm.\n\nExample 1:\nInput: s = \"aaaabbbbcccc\"\nOutput: \"abccbaabccba\"\nExplanation: After steps 1, 2 and 3 of the first iteration, result = \"abc\"\nAfter steps 4, 5 and 6 of the first iteration, result = \"abccba\"\nFirst iteration is done. Now s = \"aabbcc\" and we go back to step 1\nAfter steps 1, 2 and 3 of the second iteration, result = \"abccbaabc\"\nAfter steps 4, 5 and 6 of the second iteration, result = \"abccbaabccba\"\n\nExample 2:\nInput: s = \"rat\"\nOutput: \"art\"\nExplanation: The word \"rat\" becomes \"art\" after re-ordering it with the mentioned algorithm.\n\nConstraints:\n- 1 <= s.length <= 500\n- s consists of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def sortString(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n result, count = [], [0]*26\n for c in s:\n count[ord(c)-ord('a')] += 1\n while len(result) != len(s):\n for c in range(len(count)):\n if not count[c]:\n continue\n result.append(chr(ord('a')+c))\n count[c] -= 1\n for c in reversed(range(len(count))):\n if not count[c]:\n continue\n result.append(chr(ord('a')+c))\n count[c] -= 1\n return \"\".join(result)\n\n\n# Time: O(n)\n# Space: O(1)\nimport collections\n\n\nclass Solution2(object):\n def sortString(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n result, count, desc = [], collections.Counter(s), False\n while count:\n for c in sorted(count.keys(), reverse=desc):\n result.append(c)\n count[c] -= 1\n if not count[c]:\n del count[c]\n desc = not desc\n return \"\".join(result)\n\n"}} diff --git a/cp/cp-10792.jsonl b/cp/cp-10792.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e76553ea837b4e1838a31fd2c4b91727c7bb311c --- /dev/null +++ b/cp/cp-10792.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10792", "name": "LeetCode 1371: Find The Longest Substring Containing Vowels In Even Counts"} +{"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 the Longest Substring Containing Vowels in Even Counts (Difficulty: Medium)\nTags: Hash Table, String, Bit Manipulation, Prefix Sum\n\nGiven the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.\n\nExample 1:\nInput: s = \"eleetminicoworoep\"\nOutput: 13\nExplanation: The longest substring is \"leetminicowor\" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.\n\nExample 2:\nInput: s = \"leetcodeisgreat\"\nOutput: 5\nExplanation: The longest substring is \"leetc\" which contains two e's.\n\nExample 3:\nInput: s = \"bcbcbc\"\nOutput: 6\nExplanation: In this case, the given string \"bcbcbc\" is the longest because all vowels: a, e, i, o and u appear zero times.\n\nConstraints:\n- 1 <= s.length <= 5 x 10^5\n- s contains only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def findTheLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n VOWELS = \"aeiou\"\n result, mask, lookup = 0, 0, [-2]*(2**len(VOWELS))\n lookup[0] = -1\n for i, c in enumerate(s):\n index = VOWELS.find(c)\n mask ^= (1 << index) if index >= 0 else 0\n if lookup[mask] == -2:\n lookup[mask] = i\n result = max(result, i-lookup[mask])\n return result\n"}} diff --git a/cp/cp-10793.jsonl b/cp/cp-10793.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9df791629716abbf9574400a278f27107160ff37 --- /dev/null +++ b/cp/cp-10793.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10793", "name": "LeetCode 1372: Longest Zigzag Path 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: Longest ZigZag Path in a Binary Tree (Difficulty: Medium)\nTags: Dynamic Programming, Tree, Depth-First Search, Binary Tree\n\nYou are given the root of a binary tree.\nA ZigZag path for a binary tree is defined as follow:\nZigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).\nReturn the longest ZigZag path contained in that tree.\n\nExample 1:\nInput: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]\nOutput: 3\nExplanation: Longest ZigZag path in blue nodes (right -> left -> right).\n\nExample 2:\nInput: root = [1,1,1,null,1,null,null,1,1,null,1]\nOutput: 4\nExplanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).\n\nExample 3:\nInput: root = [1]\nOutput: 0\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 5 * 10^4].\n- 1 <= Node.val <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\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 longestZigZag(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def dfs(node, result):\n if not node:\n return [-1, -1]\n left, right = dfs(node.left, result), dfs(node.right, result)\n result[0] = max(result[0], left[1]+1, right[0]+1)\n return [left[1]+1, right[0]+1]\n\n result = [0]\n dfs(root, result)\n return result[0]\n"}} diff --git a/cp/cp-10794.jsonl b/cp/cp-10794.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c3db4d649ea79bff1bd04c02649bd2e74e41a923 --- /dev/null +++ b/cp/cp-10794.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10794", "name": "LeetCode 1373: Maximum Sum Bst 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: Maximum Sum BST in Binary Tree (Difficulty: Hard)\nTags: Dynamic Programming, Tree, Depth-First Search, Binary Search Tree, Binary Tree\n\nGiven a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).\nAssume a BST is defined as follows:\n\nExample 1:\nInput: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]\nOutput: 20\nExplanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.\n\nExample 2:\nInput: root = [4,3,null,1,2]\nOutput: 2\nExplanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.\n\nExample 3:\nInput: root = [-4,-2,-5]\nOutput: 0\nExplanation: All values are negatives. Return an empty BST.\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 4 * 10^4].\n- -4 * 10^4 <= Node.val <= 4 * 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\n# dfs solution with stack\nclass Solution(object):\n def maxSumBST(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n result = 0\n stk = [[root, None, []]]\n while stk:\n node, tmp, ret = stk.pop()\n if tmp:\n lvalid, lsum, lmin, lmax = tmp[0]\n rvalid, rsum, rmin, rmax = tmp[1]\n if lvalid and rvalid and lmax < node.val < rmin:\n total = lsum + node.val + rsum\n result = max(result, total)\n ret[:] = [True, total, min(lmin, node.val), max(node.val, rmax)]\n continue\n ret[:] = [False, 0, 0, 0]\n continue\n if not node:\n ret[:] = [True, 0, float(\"inf\"), float(\"-inf\")]\n continue\n new_tmp = [[], []]\n stk.append([node, new_tmp, ret])\n stk.append([node.right, None, new_tmp[1]])\n stk.append([node.left, None, new_tmp[0]])\n return result\n\n\n# Time: O(n)\n# Space: O(h)\n# dfs solution with recursion\nclass Solution2(object):\n def maxSumBST(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def dfs(node, result):\n if not node:\n return True, 0, float(\"inf\"), float(\"-inf\")\n lvalid, lsum, lmin, lmax = dfs(node.left, result)\n rvalid, rsum, rmin, rmax = dfs(node.right, result)\n if lvalid and rvalid and lmax < node.val < rmin:\n total = lsum + node.val + rsum\n result[0] = max(result[0], total)\n return True, total, min(lmin, node.val), max(node.val, rmax)\n return False, 0, 0, 0\n\n result = [0]\n dfs(root, result)\n return result[0]\n"}} diff --git a/cp/cp-10797.jsonl b/cp/cp-10797.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5d001a913282e439a0a88f8f60de0815f086d568 --- /dev/null +++ b/cp/cp-10797.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10797", "name": "LeetCode 1376: Time Needed To Inform All Employees"} +{"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: Time Needed to Inform All Employees (Difficulty: Medium)\nTags: Tree, Depth-First Search, Breadth-First Search\n\nA company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID.\nEach employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure.\nThe head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news.\nThe i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news).\nReturn the number of minutes needed to inform all the employees about the urgent news.\n\nExample 1:\nInput: n = 1, headID = 0, manager = [-1], informTime = [0]\nOutput: 0\nExplanation: The head of the company is the only employee in the company.\n\nExample 2:\nInput: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]\nOutput: 1\nExplanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.\nThe tree structure of the employees in the company is shown.\n\nConstraints:\n- 1 <= n <= 10^5\n- 0 <= headID < n\n- manager.length == n\n- 0 <= manager[i] < n\n- manager[headID] == -1\n- informTime.length == n\n- 0 <= informTime[i] <= 1000\n- informTime[i] == 0 if employee i has no subordinates.\n- It is guaranteed that all the employees can be informed."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\n# dfs solution with stack\nclass Solution(object):\n def numOfMinutes(self, n, headID, manager, informTime):\n \"\"\"\n :type n: int\n :type headID: int\n :type manager: List[int]\n :type informTime: List[int]\n :rtype: int\n \"\"\"\n children = collections.defaultdict(list)\n for child, parent in enumerate(manager):\n if parent != -1:\n children[parent].append(child)\n\n result = 0\n stk = [(headID, 0)]\n while stk:\n node, curr = stk.pop()\n curr += informTime[node]\n result = max(result, curr)\n if node not in children:\n continue\n for c in children[node]:\n stk.append((c, curr))\n return result\n\n \n# Time: O(n)\n# Space: O(n)\n# dfs solution with recursion\nclass Solution2(object):\n def numOfMinutes(self, n, headID, manager, informTime):\n \"\"\"\n :type n: int\n :type headID: int\n :type manager: List[int]\n :type informTime: List[int]\n :rtype: int\n \"\"\"\n def dfs(informTime, children, node):\n return (max(dfs(informTime, children, c)\n for c in children[node])\n if node in children\n else 0) + informTime[node]\n\n children = collections.defaultdict(list)\n for child, parent in enumerate(manager):\n if parent != -1:\n children[parent].append(child)\n return dfs(informTime, children, headID)\n"}} diff --git a/cp/cp-10798.jsonl b/cp/cp-10798.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6704b7d67f630dd08802faa614363f4d0515baf0 --- /dev/null +++ b/cp/cp-10798.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10798", "name": "LeetCode 1377: Frog Position After T Seconds"} +{"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: Frog Position After T Seconds (Difficulty: Hard)\nTags: Tree, Depth-First Search, Breadth-First Search, Graph\n\nGiven an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex.\nThe edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi.\nReturn the probability that after t seconds the frog is on the vertex target. Answers within 10-5 of the actual answer will be accepted.\n\nExample 1:\nInput: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4\nOutput: 0.16666666666666666 \nExplanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666.\n\nExample 2:\nInput: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7\nOutput: 0.3333333333333333\nExplanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1.\n\nConstraints:\n- 1 <= n <= 100\n- edges.length == n - 1\n- edges[i].length == 2\n- 1 <= ai, bi <= n\n- 1 <= t <= 50\n- 1 <= target <= n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\n# bfs solution with better precision\nclass Solution(object):\n def frogPosition(self, n, edges, t, target):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type t: int\n :type target: int\n :rtype: float\n \"\"\" \n G = collections.defaultdict(list)\n for u, v in edges:\n G[u].append(v)\n G[v].append(u)\n\n stk = [(t, 1, 0, 1)]\n while stk:\n new_stk = []\n while stk:\n t, node, parent, choices = stk.pop()\n if not t or not (len(G[node])-(parent != 0)):\n if node == target:\n return 1.0/choices\n continue\n for child in G[node]:\n if child == parent:\n continue\n new_stk.append((t-1, child, node,\n choices*(len(G[node])-(parent != 0))))\n stk = new_stk\n return 0.0\n\n\n# Time: O(n)\n# Space: O(n)\n# dfs solution with stack with better precision\nclass Solution2(object):\n def frogPosition(self, n, edges, t, target):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type t: int\n :type target: int\n :rtype: float\n \"\"\" \n G = collections.defaultdict(list)\n for u, v in edges:\n G[u].append(v)\n G[v].append(u)\n\n stk = [(t, 1, 0, 1)]\n while stk:\n t, node, parent, choices = stk.pop()\n if not t or not (len(G[node])-(parent != 0)):\n if node == target:\n return 1.0/choices\n continue\n for child in G[node]:\n if child == parent:\n continue\n stk.append((t-1, child, node,\n choices*(len(G[node])-(parent != 0))))\n return 0.0\n\n\n# Time: O(n)\n# Space: O(n)\n# dfs solution with recursion with better precision\nclass Solution3(object):\n def frogPosition(self, n, edges, t, target):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type t: int\n :type target: int\n :rtype: float\n \"\"\" \n def dfs(G, target, t, node, parent):\n if not t or not (len(G[node])-(parent != 0)):\n return int(node == target)\n result = 0\n for child in G[node]:\n if child == parent:\n continue\n result = dfs(G, target, t-1, child, node)\n if result:\n break\n return result*(len(G[node])-(parent != 0))\n \n G = collections.defaultdict(list)\n for u, v in edges:\n G[u].append(v)\n G[v].append(u)\n choices = dfs(G, target, t, 1, 0)\n return 1.0/choices if choices else 0.0\n\n\n# Time: O(n)\n# Space: O(n)\n# dfs solution with recursion\nclass Solution4(object):\n def frogPosition(self, n, edges, t, target):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type t: int\n :type target: int\n :rtype: float\n \"\"\" \n def dfs(G, target, t, node, parent):\n if not t or not (len(G[node])-(parent != 0)):\n return float(node == target)\n for child in G[node]:\n if child == parent:\n continue\n result = dfs(G, target, t-1, child, node)\n if result:\n break\n return result/(len(G[node])-(parent != 0))\n \n G = collections.defaultdict(list)\n for u, v in edges:\n G[u].append(v)\n G[v].append(u)\n return dfs(G, target, t, 1, 0)\n"}} diff --git a/cp/cp-10799.jsonl b/cp/cp-10799.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fd2af128c2d22c29da928b1ad7be98803a86615f --- /dev/null +++ b/cp/cp-10799.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10799", "name": "LeetCode 1379: Find A Corresponding Node Of A Binary Tree In A Clone Of That 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: Find a Corresponding Node of a Binary Tree in a Clone of That Tree (Difficulty: Easy)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven two binary trees original and cloned and given a reference to a node target in the original tree.\nThe cloned tree is a copy of the original tree.\nReturn a reference to the same node in the cloned tree.\nNote that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.\nFollow up: Could you solve the problem if repeated values on the tree are allowed?\n\nExample 1:\nInput: tree = [7,4,3,null,null,6,19], target = 3\nOutput: 3\nExplanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.\n\nExample 2:\nInput: tree = [7], target = 7\nOutput: 7\n\nExample 3:\nInput: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4\nOutput: 4\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 104].\n- The values of the nodes of the tree are unique.\n- target node is a node from the original tree and is not null."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nimport itertools\n\n\n# Definition for a binary tree node.\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 getTargetCopy(self, original, cloned, target):\n \"\"\"\n :type original: TreeNode\n :type cloned: TreeNode\n :type target: TreeNode\n :rtype: TreeNode\n \"\"\"\n def preorder_gen(node):\n stk = [node]\n while stk:\n node = stk.pop()\n if not node:\n continue\n yield node\n stk.append(node.right)\n stk.append(node.left)\n \n for node1, node2 in itertools.izip(preorder_gen(original),\n preorder_gen(cloned)):\n if node1 == target:\n return node2\n"}} diff --git a/cp/cp-10800.jsonl b/cp/cp-10800.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c315a96e02f991fa518669f675f5247ddfd058eb --- /dev/null +++ b/cp/cp-10800.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10800", "name": "LeetCode 1380: Lucky Numbers In A Matrix"} +{"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: Lucky Numbers in a Matrix (Difficulty: Easy)\nTags: Array, Matrix\n\nGiven an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order.\nA lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.\n\nExample 1:\nInput: matrix = [[3,7,8],[9,11,13],[15,16,17]]\nOutput: [15]\nExplanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column.\n\nExample 2:\nInput: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]\nOutput: [12]\nExplanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.\n\nExample 3:\nInput: matrix = [[7,8],[1,2]]\nOutput: [7]\nExplanation: 7 is the only lucky number since it is the minimum in its row and the maximum in its column.\n\nConstraints:\n- m == mat.length\n- n == mat[i].length\n- 1 <= n, m <= 50\n- 1 <= matrix[i][j] <= 10^5.\n- All elements in the matrix are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m + n)\n\nimport itertools\n\n\nclass Solution(object):\n def luckyNumbers (self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: List[int]\n \"\"\"\n rows = map(min, matrix)\n cols = map(max, itertools.izip(*matrix))\n return [cell for i, row in enumerate(matrix)\n for j, cell in enumerate(row) if rows[i] == cols[j]]\n\n \n# Time: O(m * n)\n# Space: O(m + n)\nimport itertools\n\n\nclass Solution2(object):\n def luckyNumbers (self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: List[int]\n \"\"\"\n return list(set(map(min, matrix)) &\n set(map(max, itertools.izip(*matrix))))\n \n"}} diff --git a/cp/cp-10801.jsonl b/cp/cp-10801.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3367a80093663ddfa6579edd971ec2dbb15cac1c --- /dev/null +++ b/cp/cp-10801.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10801", "name": "LeetCode 1381: Design A Stack With Increment Operation"} +{"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 a Stack With Increment Operation (Difficulty: Medium)\nTags: Array, Stack, Design\n\nDesign a stack that supports increment operations on its elements.\nImplement the CustomStack class:\n\nExample 1:\nInput\n[\"CustomStack\",\"push\",\"push\",\"pop\",\"push\",\"push\",\"push\",\"increment\",\"increment\",\"pop\",\"pop\",\"pop\",\"pop\"]\n[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]\nOutput\n[null,null,null,2,null,null,null,null,null,103,202,201,-1]\nExplanation\nCustomStack stk = new CustomStack(3); // Stack is Empty []\nstk.push(1); // stack becomes [1]\nstk.push(2); // stack becomes [1, 2]\nstk.pop(); // return 2 --> Return top of the stack 2, stack becomes [1]\nstk.push(2); // stack becomes [1, 2]\nstk.push(3); // stack becomes [1, 2, 3]\nstk.push(4); // stack still [1, 2, 3], Do not add another elements as size is 4\nstk.increment(5, 100); // stack becomes [101, 102, 103]\nstk.increment(2, 100); // stack becomes [201, 202, 103]\nstk.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202]\nstk.pop(); // return 202 --> Return top of the stack 202, stack becomes [201]\nstk.pop(); // return 201 --> Return top of the stack 201, stack becomes []\nstk.pop(); // return -1 --> Stack is empty return -1.\n\nConstraints:\n- 1 <= maxSize, x, k <= 1000\n- 0 <= val <= 100\n- At most 1000 calls will be made to each method of increment, push and pop each separately."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: cotr: O(1)\n# push: O(1)\n# pop: O(1)\n# increment: O(1)\n# Space: O(n)\n\nclass CustomStack(object):\n\n def __init__(self, maxSize):\n \"\"\"\n :type maxSize: int\n \"\"\"\n self.__max_size = maxSize\n self.__stk = []\n\n def push(self, x):\n \"\"\"\n :type x: int\n :rtype: None\n \"\"\"\n if len(self.__stk) == self.__max_size:\n return\n self.__stk.append([x, 0])\n\n def pop(self):\n \"\"\"\n :rtype: int\n \"\"\"\n if not self.__stk:\n return -1\n x, inc = self.__stk.pop()\n if self.__stk:\n self.__stk[-1][1] += inc\n return x + inc\n\n def increment(self, k, val):\n \"\"\"\n :type k: int\n :type val: int\n :rtype: None\n \"\"\"\n i = min(len(self.__stk), k)-1\n if i >= 0:\n self.__stk[i][1] += val\n"}} diff --git a/cp/cp-10802.jsonl b/cp/cp-10802.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..83b0d6562aecbfa3d11f4e4225d2b995d4d84a08 --- /dev/null +++ b/cp/cp-10802.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10802", "name": "LeetCode 1382: Balance 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: Balance a Binary Search Tree (Difficulty: Medium)\nTags: Divide and Conquer, Greedy, Tree, Depth-First Search, Binary Search Tree, Binary Tree\n\nGiven the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.\nA binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.\n\nExample 1:\nInput: root = [1,null,2,null,3,null,4,null,null]\nOutput: [2,1,3,null,null,null,4]\nExplanation: This is not the only correct answer, [3,1,4,null,2] is also correct.\n\nExample 2:\nInput: root = [2,1,3]\nOutput: [2,1,3]\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 104].\n- 1 <= Node.val <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\n# dfs solution with stack\nclass Solution(object):\n def balanceBST(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n def inorderTraversal(root):\n result, stk = [], [(root, False)]\n while stk:\n node, is_visited = stk.pop()\n if node is None:\n continue\n if is_visited:\n result.append(node.val)\n else:\n stk.append((node.right, False))\n stk.append((node, True))\n stk.append((node.left, False))\n return result\n \n def sortedArrayToBst(arr):\n ROOT, LEFT, RIGHT = range(3)\n result = [None]\n stk = [(0, len(arr), ROOT, result)]\n while stk:\n i, j, update, ret = stk.pop()\n if i >= j:\n continue\n mid = i + (j-i)//2\n node = TreeNode(arr[mid])\n if update == ROOT:\n ret[0] = node\n elif update == LEFT:\n ret[0].left = node\n else:\n ret[0].right = node\n stk.append((mid+1, j, RIGHT, [node]))\n stk.append((i, mid, LEFT, [node]))\n return result[0]\n \n return sortedArrayToBst(inorderTraversal(root))\n\n\n# Time: O(n)\n# Space: O(h)\n# dfs solution with recursion\nclass Solution2(object):\n def balanceBST(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n def inorderTraversalHelper(node, arr):\n if not node:\n return\n inorderTraversalHelper(node.left, arr)\n arr.append(node.val)\n inorderTraversalHelper(node.right, arr)\n \n def sortedArrayToBstHelper(arr, i, j):\n if i >= j:\n return None\n mid = i + (j-i)//2\n node = TreeNode(arr[mid])\n node.left = sortedArrayToBstHelper(arr, i, mid)\n node.right = sortedArrayToBstHelper(arr, mid+1, j)\n return node\n \n arr = []\n inorderTraversalHelper(root, arr)\n return sortedArrayToBstHelper(arr, 0, len(arr))\n"}} diff --git a/cp/cp-10803.jsonl b/cp/cp-10803.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2478103b404fffd2e8c08c1629c87b907da9fe5e --- /dev/null +++ b/cp/cp-10803.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10803", "name": "LeetCode 1383: Maximum Performance Of A Team"} +{"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 Performance of a Team (Difficulty: Hard)\nTags: Array, Greedy, Sorting, Heap (Priority Queue)\n\nYou are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively.\nChoose at most k different engineers out of the n engineers to form a team with the maximum performance.\nThe performance of a team is the sum of its engineers' speeds multiplied by the minimum efficiency among its engineers.\nReturn the maximum performance of this team. Since the answer can be a huge number, return it modulo 109 + 7.\n\nExample 1:\nInput: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2\nOutput: 60\nExplanation: \nWe have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.\n\nExample 2:\nInput: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3\nOutput: 68\nExplanation:\nThis is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.\n\nExample 3:\nInput: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4\nOutput: 72\n\nConstraints:\n- 1 <= k <= n <= 10^5\n- speed.length == n\n- efficiency.length == n\n- 1 <= speed[i] <= 10^5\n- 1 <= efficiency[i] <= 10^8"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport itertools\nimport heapq\n\n\nclass Solution(object):\n def maxPerformance(self, n, speed, efficiency, k):\n \"\"\"\n :type n: int\n :type speed: List[int]\n :type efficiency: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n MOD = 10**9 + 7\n result, s_sum = 0, 0\n min_heap = []\n for e, s in sorted(itertools.izip(efficiency, speed), reverse=True):\n s_sum += s\n heapq.heappush(min_heap, s)\n if len(min_heap) > k:\n s_sum -= heapq.heappop(min_heap)\n result = max(result, s_sum*e)\n return result % MOD\n"}} diff --git a/cp/cp-10804.jsonl b/cp/cp-10804.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8ab962a5dd98fad20a90b1fabc08c8b35b86111f --- /dev/null +++ b/cp/cp-10804.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10804", "name": "LeetCode 1385: Find The Distance Value Between Two 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: Find the Distance Value Between Two Arrays (Difficulty: Easy)\nTags: Array, Two Pointers, Binary Search, Sorting\n\nGiven two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.\nThe distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.\n\nExample 1:\nInput: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2\nOutput: 2\nExplanation: \nFor arr1[0]=4 we have: \n|4-10|=6 > d=2 \n|4-9|=5 > d=2 \n|4-1|=3 > d=2 \n|4-8|=4 > d=2 \nFor arr1[1]=5 we have: \n|5-10|=5 > d=2 \n|5-9|=4 > d=2 \n|5-1|=4 > d=2 \n|5-8|=3 > d=2\nFor arr1[2]=8 we have:\n|8-10|=2 <= d=2\n|8-9|=1 <= d=2\n|8-1|=7 > d=2\n|8-8|=0 <= d=2\n\nExample 2:\nInput: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3\nOutput: 2\n\nExample 3:\nInput: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6\nOutput: 1\n\nConstraints:\n- 1 <= arr1.length, arr2.length <= 500\n- -1000 <= arr1[i], arr2[j] <= 1000\n- 0 <= d <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((n + m) * logm)\n# Space: O(1)\n\nimport bisect\n\n\nclass Solution(object):\n def findTheDistanceValue(self, arr1, arr2, d):\n \"\"\"\n :type arr1: List[int]\n :type arr2: List[int]\n :type d: int\n :rtype: int\n \"\"\"\n arr2.sort()\n result, i, j = 0, 0, 0\n for x in arr1:\n j = bisect.bisect_left(arr2, x)\n left = arr2[j-1] if j-1 >= 0 else float(\"-inf\")\n right = arr2[j] if j < len(arr2) else float(\"inf\")\n result += left+d < x < right-d\n return result\n\n\n# Time: O(nlogn + mlogm)\n# Space: O(1)\nclass Solution2(object):\n def findTheDistanceValue(self, arr1, arr2, d):\n \"\"\"\n :type arr1: List[int]\n :type arr2: List[int]\n :type d: int\n :rtype: int\n \"\"\"\n arr1.sort(), arr2.sort()\n result, i, j = 0, 0, 0\n while i < len(arr1) and j < len(arr2):\n if arr1[i]-arr2[j] > d:\n j += 1\n continue\n result += arr2[j]-arr1[i] > d\n i += 1\n return result+len(arr1)-i\n"}} diff --git a/cp/cp-10805.jsonl b/cp/cp-10805.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..829a23086a50e700b9a6d0d51ac6af238ad17790 --- /dev/null +++ b/cp/cp-10805.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10805", "name": "LeetCode 1386: Cinema Seat Allocation"} +{"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: Cinema Seat Allocation (Difficulty: Medium)\nTags: Array, Hash Table, Greedy, Bit Manipulation\n\nA cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.\nGiven the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved.\nReturn the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.\n\nExample 1:\nInput: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]\nOutput: 4\nExplanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.\n\nExample 2:\nInput: n = 2, reservedSeats = [[2,1],[1,8],[2,6]]\nOutput: 2\n\nExample 3:\nInput: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]\nOutput: 4\n\nConstraints:\n- 1 <= n <= 10^9\n- 1 <= reservedSeats.length <= min(10*n, 10^4)\n- reservedSeats[i].length == 2\n- 1 <= reservedSeats[i][0] <= n\n- 1 <= reservedSeats[i][1] <= 10\n- All reservedSeats[i] are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def maxNumberOfFamilies(self, n, reservedSeats):\n \"\"\"\n :type n: int\n :type reservedSeats: List[List[int]]\n :rtype: int\n \"\"\"\n lookup = collections.defaultdict(lambda: [False]*3)\n for r, c in reservedSeats:\n if 2 <= c <= 5:\n lookup[r][0] = True\n if 4 <= c <= 7:\n lookup[r][1] = True\n if 6 <= c <= 9:\n lookup[r][2] = True\n result = 2*n\n for a, b, c in lookup.itervalues():\n if not a and not c:\n continue\n if not a or not b or not c:\n result -= 1\n continue\n result -= 2\n return result\n\n\n# Time: O(nlogn)\n# Space: O(1)\nclass Solution2(object):\n def maxNumberOfFamilies(self, n, reservedSeats):\n \"\"\"\n :type n: int\n :type reservedSeats: List[List[int]]\n :rtype: int\n \"\"\"\n reservedSeats.sort()\n result, i = 2*n, 0\n while i < len(reservedSeats):\n reserved = [False]*3\n curr = reservedSeats[i][0]\n while i < len(reservedSeats) and reservedSeats[i][0] == curr:\n _, c = reservedSeats[i]\n if 2 <= c <= 5:\n reserved[0] = True\n if 4 <= c <= 7:\n reserved[1] = True\n if 6 <= c <= 9:\n reserved[2] = True\n i += 1\n if not reserved[0] and not reserved[2]:\n continue\n if not all(reserved):\n result -= 1\n continue\n result -= 2\n return result\n"}} diff --git a/cp/cp-10806.jsonl b/cp/cp-10806.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..58077fdb6dd1983ba7197add9faca8d2f5a6309c --- /dev/null +++ b/cp/cp-10806.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10806", "name": "LeetCode 1387: Sort Integers By The Power Value"} +{"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: Sort Integers by The Power Value (Difficulty: Medium)\nTags: Dynamic Programming, Memoization, Sorting\n\nThe power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps:\nFor example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1).\nGiven three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order.\nReturn the kth integer in the range [lo, hi] sorted by the power value.\nNotice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer.\n\nExample 1:\nInput: lo = 12, hi = 15, k = 2\nOutput: 13\nExplanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)\nThe power of 13 is 9\nThe power of 14 is 17\nThe power of 15 is 17\nThe interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.\nNotice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.\n\nExample 2:\nInput: lo = 7, hi = 11, k = 4\nOutput: 7\nExplanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].\nThe interval sorted by power is [8, 10, 11, 7, 9].\nThe fourth number in the sorted array is 7.\n\nConstraints:\n- 1 <= lo <= hi <= 1000\n- 1 <= k <= hi - lo + 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n) on average\n# Space: O(n)\n\nimport random\n\n\nclass Solution(object):\n dp = {}\n\n def getKth(self, lo, hi, k):\n \"\"\"\n :type lo: int\n :type hi: int\n :type k: int\n :rtype: int\n \"\"\"\n def nth_element(nums, n, compare=lambda a, b: a < b):\n def partition_around_pivot(left, right, pivot_idx, nums, compare):\n new_pivot_idx = left\n nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]\n for i in range(left, right):\n if compare(nums[i], nums[right]):\n nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]\n new_pivot_idx += 1\n\n nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]\n return new_pivot_idx\n\n left, right = 0, len(nums) - 1\n while left <= right:\n pivot_idx = random.randint(left, right)\n new_pivot_idx = partition_around_pivot(left, right, pivot_idx, nums, compare)\n if new_pivot_idx == n:\n return\n elif new_pivot_idx > n:\n right = new_pivot_idx - 1\n else: # new_pivot_idx < n\n left = new_pivot_idx + 1\n \n def power_value(x):\n y, result = x, 0\n while x > 1 and x not in Solution.dp:\n result += 1\n if x%2:\n x = 3*x + 1\n else:\n x //= 2\n Solution.dp[y] = result + (Solution.dp[x] if x > 1 else 0)\n return Solution.dp[y], y\n \n arr = map(power_value, range(lo, hi+1))\n nth_element(arr, k-1)\n return arr[k-1][1]\n\n\n# Time: O(nlogn)\n# Space: O(n)\nclass Solution2(object):\n dp = {}\n\n def getKth(self, lo, hi, k):\n \"\"\"\n :type lo: int\n :type hi: int\n :type k: int\n :rtype: int\n \"\"\"\n def power_value(x):\n y, result = x, 0\n while x > 1 and x not in Solution2.dp:\n result += 1\n if x%2:\n x = 3*x + 1\n else:\n x //= 2\n Solution2.dp[y] = result + (Solution2.dp[x] if x > 1 else 0)\n return Solution2.dp[y], y\n \n return sorted(range(lo, hi+1), key=power_value)[k-1]\n"}} diff --git a/cp/cp-10807.jsonl b/cp/cp-10807.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..10d811447cb384fe65479ce1d5d08b96d962ba1d --- /dev/null +++ b/cp/cp-10807.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10807", "name": "LeetCode 1388: Pizza With 3N Slices"} +{"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: Pizza With 3n Slices (Difficulty: Hard)\nTags: Array, Dynamic Programming, Greedy, Heap (Priority Queue)\n\nThere is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:\nGiven an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick.\n\nExample 1:\nInput: slices = [1,2,3,4,5,6]\nOutput: 10\nExplanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.\n\nExample 2:\nInput: slices = [8,9,8,6,1,1]\nOutput: 16\nExplanation: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.\n\nConstraints:\n- 3 * n == slices.length\n- 1 <= slices.length <= 500\n- 1 <= slices[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\n# [observation]\n# 1. we can never take two adjacent slices\n# 2. if we want some set of N / 3 non-adjacent slices, there is always a way to take\n#\n# [proof]\n# - for N = 3, it is obviously true.\n# - for N' = N + 3,\n# - because it's impossible to have only one unwanted slices between all wanted slices.\n# if it's true, there will be 3N'/2 unwanted slices rather than 2N' unwanted ones, -><-\n# - so we can always find a sequence of two unwanted slices with one wanted slice\n# to take firstly, then we can find a way to take the remaining N ones by induction, QED\n\n# better optimized space\nclass Solution(object):\n def maxSizeSlices(self, slices):\n \"\"\"\n :type slices: List[int]\n :rtype: int\n \"\"\"\n def maxSizeSlicesLinear(slices, start, end):\n dp = [[0]*(len(slices)//3+1) for _ in range(2)]\n for i in range(start, end):\n for j in reversed(range(1, min(((i-start+1)-1)//2+1, len(slices)//3)+1)):\n dp[i%2][j] = max(dp[(i-1)%2][j], dp[(i-2)%2][j-1] + slices[i])\n return dp[(end-1)%2][len(slices)//3]\n \n return max(maxSizeSlicesLinear(slices, 0, len(slices)-1),\n maxSizeSlicesLinear(slices, 1, len(slices)))\n\n\n# Time: O(n^2)\n# Space: O(n)\nclass Solution2(object):\n def maxSizeSlices(self, slices):\n \"\"\"\n :type slices: List[int]\n :rtype: int\n \"\"\"\n def maxSizeSlicesLinear(slices, start, end):\n dp = [[0]*(len(slices)//3+1) for _ in range(3)]\n for i in range(start, end):\n for j in range(1, min(((i-start+1)-1)//2+1, len(slices)//3)+1):\n dp[i%3][j] = max(dp[(i-1)%3][j], dp[(i-2)%3][j-1] + slices[i])\n return dp[(end-1)%3][len(slices)//3]\n \n return max(maxSizeSlicesLinear(slices, 0, len(slices)-1),\n maxSizeSlicesLinear(slices, 1, len(slices)))\n"}} diff --git a/cp/cp-10808.jsonl b/cp/cp-10808.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..89bf04f730c80b974c3455ee627a3b2d15b4343a --- /dev/null +++ b/cp/cp-10808.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10808", "name": "LeetCode 1389: Create Target Array In The Given Order"} +{"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: Create Target Array in the Given Order (Difficulty: Easy)\nTags: Array, Simulation\n\nGiven two arrays of integers nums and index. Your task is to create target array under the following rules:\nReturn the target array.\nIt is guaranteed that the insertion operations will be valid.\n\nExample 1:\nInput: nums = [0,1,2,3,4], index = [0,1,2,2,1]\nOutput: [0,4,1,3,2]\nExplanation:\nnums index target\n0 0 [0]\n1 1 [0,1]\n2 2 [0,1,2]\n3 2 [0,1,3,2]\n4 1 [0,4,1,3,2]\n\nExample 2:\nInput: nums = [1,2,3,4,0], index = [0,1,2,3,0]\nOutput: [0,1,2,3,4]\nExplanation:\nnums index target\n1 0 [1]\n2 1 [1,2]\n3 2 [1,2,3]\n4 3 [1,2,3,4]\n0 0 [0,1,2,3,4]\n\nExample 3:\nInput: nums = [1], index = [0]\nOutput: [1]\n\nConstraints:\n- 1 <= nums.length, index.length <= 100\n- nums.length == index.length\n- 0 <= nums[i] <= 100\n- 0 <= index[i] <= i"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(1)\n\nclass Solution(object):\n def createTargetArray(self, nums, index):\n \"\"\"\n :type nums: List[int]\n :type index: List[int]\n :rtype: List[int]\n \"\"\"\n for i in range(len(nums)):\n for j in range(i):\n if index[j] >= index[i]:\n index[j] += 1\n result = [0]*(len(nums))\n for i in range(len(nums)):\n result[index[i]] = nums[i]\n return result\n\n\n# Time: O(n^2)\n# Space: O(1)\nimport itertools\n\n\nclass Solution2(object):\n def createTargetArray(self, nums, index):\n \"\"\"\n :type nums: List[int]\n :type index: List[int]\n :rtype: List[int]\n \"\"\"\n result = []\n for i, x in itertools.izip(index, nums):\n result.insert(i, x)\n return result\n\n"}} diff --git a/cp/cp-10809.jsonl b/cp/cp-10809.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2f0c93c3bb73ff1a285c465b46da46c39c579c04 --- /dev/null +++ b/cp/cp-10809.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10809", "name": "LeetCode 1390: Four Divisors"} +{"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: Four Divisors (Difficulty: Medium)\nTags: Array, Math\n\nGiven an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0.\n\nExample 1:\nInput: nums = [21,4,7]\nOutput: 32\nExplanation: \n21 has 4 divisors: 1, 3, 7, 21\n4 has 3 divisors: 1, 2, 4\n7 has 2 divisors: 1, 7\nThe answer is the sum of divisors of 21 only.\n\nExample 2:\nInput: nums = [21,21]\nOutput: 64\n\nExample 3:\nInput: nums = [1,2,3,4,5]\nOutput: 0\n\nConstraints:\n- 1 <= nums.length <= 10^4\n- 1 <= nums[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * sqrt(n))\n# Space: O(1)\n\nclass Solution(object):\n def sumFourDivisors(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result = 0\n for num in nums:\n facs, i = [], 1\n while i*i <= num:\n if num % i:\n i+= 1\n continue\n facs.append(i)\n if i != num//i:\n facs.append(num//i)\n if len(facs) > 4:\n break\n i += 1\n if len(facs) == 4: \n result += sum(facs)\n return result \n\n\n# Time: O(n * sqrt(n))\n# Space: O(sqrt(n))\nimport itertools\n\n\nclass Solution2(object):\n def sumFourDivisors(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def factorize(x):\n result = []\n d = 2\n while d*d <= x:\n e = 0\n while x%d == 0:\n x //= d\n e += 1\n if e:\n result.append([d, e])\n d += 1 if d == 2 else 2\n if x > 1:\n result.append([x, 1])\n return result\n \n result = 0\n for facs in itertools.imap(factorize, nums):\n if len(facs) == 1 and facs[0][1] == 3:\n p = facs[0][0]\n result += (p**4-1)//(p-1) # p^0 + p^1 +p^2 +p^3\n elif len(facs) == 2 and facs[0][1] == facs[1][1] == 1:\n p, q = facs[0][0], facs[1][0]\n result += (1 + p) * (1 + q)\n return result\n"}} diff --git a/cp/cp-10810.jsonl b/cp/cp-10810.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7c11fb23af86279bdef53d06682d567ade133034 --- /dev/null +++ b/cp/cp-10810.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10810", "name": "LeetCode 1391: Check If There Is A Valid Path In A Grid"} +{"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: Check if There is a Valid Path in a Grid (Difficulty: Medium)\nTags: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix\n\nYou are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be:\nYou will initially start at the street of the upper-left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets.\nNotice that you are not allowed to change any street.\nReturn true if there is a valid path in the grid or false otherwise.\n\nExample 1:\nInput: grid = [[2,4,3],[6,5,2]]\nOutput: true\nExplanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).\n\nExample 2:\nInput: grid = [[1,2,1],[1,2,1]]\nOutput: false\nExplanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)\n\nExample 3:\nInput: grid = [[1,1,2]]\nOutput: false\nExplanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 300\n- 1 <= grid[i][j] <= 6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def hasValidPath(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: bool\n \"\"\"\n E, S, W, N = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n directions = [\n [W, E], [N, S],\n [W, S], [S, E],\n [W, N], [N, E]\n ]\n\n for r, c in directions[grid[0][0]-1]:\n if not (0 <= r < len(grid) and 0 <= c < len(grid[0])):\n continue\n pr, pc = 0, 0\n while r != len(grid)-1 or c != len(grid[0])-1:\n for dx, dy in directions[grid[r][c]-1]:\n nr, nc = r+dx, c+dy\n if (nr == pr and nc == pc) or \\\n not(0 <= nr < len(grid) and 0 <= nc < len(grid[0])) or \\\n (-dx, -dy) not in directions[grid[nr][nc]-1]:\n continue\n pr, pc, r, c = r, c, nr, nc\n break\n else:\n return False\n return True\n return len(grid) == len(grid[0]) == 1 \n"}} diff --git a/cp/cp-10811.jsonl b/cp/cp-10811.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8d3e6a5acb8917a5b08d43c17891e3b1c68cc06e --- /dev/null +++ b/cp/cp-10811.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10811", "name": "LeetCode 1392: Longest Happy Prefix"} +{"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 Happy Prefix (Difficulty: Hard)\nTags: String, Rolling Hash, String Matching, Hash Function\n\nA string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).\nGiven a string s, return the longest happy prefix of s. Return an empty string \"\" if no such prefix exists.\n\nExample 1:\nInput: s = \"level\"\nOutput: \"l\"\nExplanation: s contains 4 prefix excluding itself (\"l\", \"le\", \"lev\", \"leve\"), and suffix (\"l\", \"el\", \"vel\", \"evel\"). The largest prefix which is also suffix is given by \"l\".\n\nExample 2:\nInput: s = \"ababab\"\nOutput: \"abab\"\nExplanation: \"abab\" is the largest prefix which is also suffix. They can overlap in the original string.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s contains only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\n# kmp solution\nclass Solution(object):\n def longestPrefix(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n def getPrefix(pattern):\n prefix = [-1]*len(pattern)\n j = -1\n for i in range(1, len(pattern)):\n while j != -1 and pattern[j+1] != pattern[i]:\n j = prefix[j]\n if pattern[j+1] == pattern[i]:\n j += 1\n prefix[i] = j\n return prefix\n \n return s[:getPrefix(s)[-1]+1]\n\n\n# Time: O(n) on average\n# Space: O(1)\n# rolling-hash solution\nclass Solution2(object):\n def longestPrefix(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n M = 10**9+7\n D = 26\n def check(l, s):\n for i in range(l):\n if s[i] != s[len(s)-l+i]:\n return False\n return True\n \n result, prefix, suffix, power = 0, 0, 0, 1\n for i in range(len(s)-1):\n prefix = (prefix*D + (ord(s[i])-ord('a'))) % M\n suffix = (suffix + (ord(s[len(s)-(i+1)])-ord('a'))*power) % M\n power = (power*D)%M\n if prefix == suffix:\n # we assume M is a very large prime without hash collision\n # assert(check(i+1, s))\n result = i+1\n return s[:result]\n"}} diff --git a/cp/cp-10812.jsonl b/cp/cp-10812.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a6b5f49762cc4ca715eca30932f9773c3eadcfbf --- /dev/null +++ b/cp/cp-10812.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10812", "name": "LeetCode 1394: Find Lucky Integer In An 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: Find Lucky Integer in an Array (Difficulty: Easy)\nTags: Array, Hash Table, Counting\n\nGiven an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value.\nReturn the largest lucky integer in the array. If there is no lucky integer return -1.\n\nExample 1:\nInput: arr = [2,2,3,4]\nOutput: 2\nExplanation: The only lucky number in the array is 2 because frequency[2] == 2.\n\nExample 2:\nInput: arr = [1,2,2,3,3,3]\nOutput: 3\nExplanation: 1, 2 and 3 are all lucky numbers, return the largest of them.\n\nExample 3:\nInput: arr = [2,2,2,3,3]\nOutput: -1\nExplanation: There are no lucky numbers in the array.\n\nConstraints:\n- 1 <= arr.length <= 500\n- 1 <= arr[i] <= 500"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def findLucky(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n count = collections.Counter(arr)\n result = -1\n for k, v in count.iteritems():\n if k == v:\n result = max(result, k)\n return result\n"}} diff --git a/cp/cp-10813.jsonl b/cp/cp-10813.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..56fc213415361c382480b5233dd7dcd156bd573c --- /dev/null +++ b/cp/cp-10813.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10813", "name": "LeetCode 1395: Count Number Of Teams"} +{"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: Count Number of Teams (Difficulty: Medium)\nTags: Array, Dynamic Programming, Binary Indexed Tree, Segment Tree\n\nThere are n soldiers standing in a line. Each soldier is assigned a unique rating value.\nYou have to form a team of 3 soldiers amongst them under the following rules:\nReturn the number of teams you can form given the conditions. (soldiers can be part of multiple teams).\n\nExample 1:\nInput: rating = [2,5,3,4,1]\nOutput: 3\nExplanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1).\n\nExample 2:\nInput: rating = [2,1,3]\nOutput: 0\nExplanation: We can't form any team given the conditions.\n\nExample 3:\nInput: rating = [1,2,3,4]\nOutput: 4\n\nConstraints:\n- n == rating.length\n- 3 <= n <= 1000\n- 1 <= rating[i] <= 10^5\n- All the integers in rating are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(1)\n\nclass Solution(object):\n def numTeams(self, rating):\n \"\"\"\n :type rating: List[int]\n :rtype: int\n \"\"\"\n result = 0\n for i in range(1, len(rating)-1):\n less, greater = [0]*2, [0]*2\n for j in range(len(rating)):\n if rating[i] > rating[j]:\n less[i < j] += 1\n if rating[i] < rating[j]:\n greater[i < j] += 1\n result += less[0]*greater[1] + greater[0]*less[1]\n return result\n"}} diff --git a/cp/cp-10814.jsonl b/cp/cp-10814.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..705d38617129d17b067a7208462a6f4293497d61 --- /dev/null +++ b/cp/cp-10814.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10814", "name": "LeetCode 1396: Design Underground 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: Design Underground System (Difficulty: Medium)\nTags: Hash Table, String, Design\n\nAn underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.\nImplement the UndergroundSystem class:\nYou may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.\n\nExample 1:\nInput\n[\"UndergroundSystem\",\"checkIn\",\"checkIn\",\"checkIn\",\"checkOut\",\"checkOut\",\"checkOut\",\"getAverageTime\",\"getAverageTime\",\"checkIn\",\"getAverageTime\",\"checkOut\",\"getAverageTime\"]\n[[],[45,\"Leyton\",3],[32,\"Paradise\",8],[27,\"Leyton\",10],[45,\"Waterloo\",15],[27,\"Waterloo\",20],[32,\"Cambridge\",22],[\"Paradise\",\"Cambridge\"],[\"Leyton\",\"Waterloo\"],[10,\"Leyton\",24],[\"Leyton\",\"Waterloo\"],[10,\"Waterloo\",38],[\"Leyton\",\"Waterloo\"]]\n\nOutput\n[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]\n\nExplanation\nUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(45, \"Leyton\", 3);\nundergroundSystem.checkIn(32, \"Paradise\", 8);\nundergroundSystem.checkIn(27, \"Leyton\", 10);\nundergroundSystem.checkOut(45, \"Waterloo\", 15); // Customer 45 \"Leyton\" -> \"Waterloo\" in 15-3 = 12\nundergroundSystem.checkOut(27, \"Waterloo\", 20); // Customer 27 \"Leyton\" -> \"Waterloo\" in 20-10 = 10\nundergroundSystem.checkOut(32, \"Cambridge\", 22); // Customer 32 \"Paradise\" -> \"Cambridge\" in 22-8 = 14\nundergroundSystem.getAverageTime(\"Paradise\", \"Cambridge\"); // return 14.00000. One trip \"Paradise\" -> \"Cambridge\", (14) / 1 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 11.00000. Two trips \"Leyton\" -> \"Waterloo\", (10 + 12) / 2 = 11\nundergroundSystem.checkIn(10, \"Leyton\", 24);\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 11.00000\nundergroundSystem.checkOut(10, \"Waterloo\", 38); // Customer 10 \"Leyton\" -> \"Waterloo\" in 38-24 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 12.00000. Three trips \"Leyton\" -> \"Waterloo\", (10 + 12 + 14) / 3 = 12\n\nExample 2:\nInput\n[\"UndergroundSystem\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\"]\n[[],[10,\"Leyton\",3],[10,\"Paradise\",8],[\"Leyton\",\"Paradise\"],[5,\"Leyton\",10],[5,\"Paradise\",16],[\"Leyton\",\"Paradise\"],[2,\"Leyton\",21],[2,\"Paradise\",30],[\"Leyton\",\"Paradise\"]]\n\nOutput\n[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]\n\nExplanation\nUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(10, \"Leyton\", 3);\nundergroundSystem.checkOut(10, \"Paradise\", 8); // Customer 10 \"Leyton\" -> \"Paradise\" in 8-3 = 5\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.00000, (5) / 1 = 5\nundergroundSystem.checkIn(5, \"Leyton\", 10);\nundergroundSystem.checkOut(5, \"Paradise\", 16); // Customer 5 \"Leyton\" -> \"Paradise\" in 16-10 = 6\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.50000, (5 + 6) / 2 = 5.5\nundergroundSystem.checkIn(2, \"Leyton\", 21);\nundergroundSystem.checkOut(2, \"Paradise\", 30); // Customer 2 \"Leyton\" -> \"Paradise\" in 30-21 = 9\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667\n\nConstraints:\n- 1 <= id, t <= 10^6\n- 1 <= stationName.length, startStation.length, endStation.length <= 10\n- All strings consist of uppercase and lowercase English letters and digits.\n- There will be at most 2 * 10^4 calls in total to checkIn, checkOut, and getAverageTime.\n- Answers within 10-5 of the actual value will be accepted."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(1)\n# checkin: O(1)\n# checkout: O(1)\n# getaverage: O(1)\n# Space: O(n)\n\nimport collections\n\n\nclass UndergroundSystem(object):\n\n def __init__(self):\n self.__live = {}\n self.__statistics = collections.defaultdict(lambda: [0, 0])\n \n\n def checkIn(self, id, stationName, t):\n \"\"\"\n :type id: int\n :type stationName: str\n :type t: int\n :rtype: None\n \"\"\"\n self.__live[id] = (stationName, t)\n\n def checkOut(self, id, stationName, t):\n \"\"\"\n :type id: int\n :type stationName: str\n :type t: int\n :rtype: None\n \"\"\"\n startStation, startTime = self.__live.pop(id)\n self.__statistics[startStation, stationName][0] += t-startTime\n self.__statistics[startStation, stationName][1] += 1\n \n def getAverageTime(self, startStation, endStation):\n \"\"\"\n :type startStation: str\n :type endStation: str\n :rtype: float\n \"\"\"\n total_time, cnt = self.__statistics[startStation, endStation]\n return float(total_time) / cnt\n"}} diff --git a/cp/cp-10815.jsonl b/cp/cp-10815.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..aad1549f47f65a45960d52db35c0486801d526b6 --- /dev/null +++ b/cp/cp-10815.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10815", "name": "LeetCode 1397: Find All Good Strings"} +{"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 All Good Strings (Difficulty: Hard)\nTags: String, Dynamic Programming, String Matching\n\nGiven the strings s1 and s2 of size n and the string evil, return the number of good strings.\nA good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 109 + 7.\n\nExample 1:\nInput: n = 2, s1 = \"aa\", s2 = \"da\", evil = \"b\"\nOutput: 51 \nExplanation: There are 25 good strings starting with 'a': \"aa\",\"ac\",\"ad\",...,\"az\". Then there are 25 good strings starting with 'c': \"ca\",\"cc\",\"cd\",...,\"cz\" and finally there is one good string starting with 'd': \"da\".\n\nExample 2:\nInput: n = 8, s1 = \"leetcode\", s2 = \"leetgoes\", evil = \"leet\"\nOutput: 0 \nExplanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix \"leet\", therefore, there is not any good string.\n\nExample 3:\nInput: n = 2, s1 = \"gx\", s2 = \"gz\", evil = \"x\"\nOutput: 2\n\nConstraints:\n- s1.length == n\n- s2.length == n\n- s1 <= s2\n- 1 <= n <= 500\n- 1 <= evil.length <= 50\n- All strings consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m)\n\nclass Solution(object):\n def findGoodStrings(self, n, s1, s2, evil):\n \"\"\"\n :type n: int\n :type s1: str\n :type s2: str\n :type evil: str\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n def getPrefix(pattern):\n prefix = [-1]*len(pattern)\n j = -1\n for i in range(1, len(pattern)):\n while j != -1 and pattern[j+1] != pattern[i]:\n j = prefix[j]\n if pattern[j+1] == pattern[i]:\n j += 1\n prefix[i] = j\n return prefix\n \n prefix = getPrefix(evil)\n dp = [[[[0]*len(evil) for _ in range(2)] for _ in range(2)] for _ in range(2)]\n dp[0][0][0][0] = 1\n for i in range(n):\n dp[(i+1)%2] = [[[0]*len(evil) for _ in range(2)] for _ in range(2)]\n for j in range(2):\n for k in range(2):\n min_c = 'a' if j else s1[i]\n max_c = 'z' if k else s2[i]\n for l in range(len(evil)):\n if not dp[i%2][j][k][l]:\n continue\n for c in range(ord(min_c)-ord('a'), ord(max_c)-ord('a')+1):\n c = chr(c+ord('a'))\n m = l-1\n while m != -1 and evil[m+1] != c:\n m = prefix[m]\n if evil[m+1] == c:\n m += 1\n if m+1 == len(evil):\n continue\n dp[(i+1)%2][j or (s1[i] != c)][k or (s2[i] != c)][m+1] = \\\n (dp[(i+1)%2][j or (s1[i] != c)][k or (s2[i] != c)][m+1] + dp[i%2][j][k][l]) % MOD\n result = 0\n for j in range(2):\n for k in range(2):\n for l in range(len(evil)):\n result = (result + dp[n%2][j][k][l]) % MOD\n return result\n"}} diff --git a/cp/cp-10816.jsonl b/cp/cp-10816.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2defbab016fd9ad5aeda3b52a5a3189d87b2ccdf --- /dev/null +++ b/cp/cp-10816.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10816", "name": "LeetCode 1399: Count Largest Group"} +{"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: Count Largest Group (Difficulty: Easy)\nTags: Hash Table, Math\n\nYou are given an integer n.\nWe need to group the numbers from 1 to n according to the sum of its digits. For example, the numbers 14 and 5 belong to the same group, whereas 13 and 3 belong to different groups.\nReturn the number of groups that have the largest size, i.e. the maximum number of elements.\n\nExample 1:\nInput: n = 13\nOutput: 4\nExplanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:\n[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].\nThere are 4 groups with largest size.\n\nExample 2:\nInput: n = 2\nOutput: 2\nExplanation: There are 2 groups [1], [2] of size 1.\n\nConstraints:\n- 1 <= n <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def countLargestGroup(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n count = collections.Counter()\n for x in range(1, n+1):\n count[sum(map(int, str(x)))] += 1\n max_count = max(count.itervalues())\n return sum(v == max_count for v in count.itervalues())\n"}} diff --git a/cp/cp-10817.jsonl b/cp/cp-10817.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f07fb41e82785892012957bbbedb4a042758499b --- /dev/null +++ b/cp/cp-10817.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10817", "name": "LeetCode 1400: Construct K Palindrome Strings"} +{"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 K Palindrome Strings (Difficulty: Medium)\nTags: Hash Table, String, Greedy, Counting\n\nGiven a string s and an integer k, return true if you can use all the characters in s to construct non-empty k palindrome strings or false otherwise.\n\nExample 1:\nInput: s = \"annabelle\", k = 2\nOutput: true\nExplanation: You can construct two palindromes using all characters in s.\nSome possible constructions \"anna\" + \"elble\", \"anbna\" + \"elle\", \"anellena\" + \"b\"\n\nExample 2:\nInput: s = \"leetcode\", k = 3\nOutput: false\nExplanation: It is impossible to construct 3 palindromes using all the characters of s.\n\nExample 3:\nInput: s = \"true\", k = 4\nOutput: true\nExplanation: The only possible solution is to put each character in a separate string.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s consists of lowercase English letters.\n- 1 <= k <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def canConstruct(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: bool\n \"\"\"\n count = collections.Counter(s)\n odd = sum(v%2 for v in count.itervalues())\n return odd <= k <= len(s)\n"}} diff --git a/cp/cp-10818.jsonl b/cp/cp-10818.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..68f0d4dbcf1c750b60344d5769880e86cabdf040 --- /dev/null +++ b/cp/cp-10818.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10818", "name": "LeetCode 1401: Circle And Rectangle Overlapping"} +{"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: Circle and Rectangle Overlapping (Difficulty: Medium)\nTags: Math, Geometry\n\nYou are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle.\nReturn true if the circle and rectangle are overlapped otherwise return false. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time.\n\nExample 1:\nInput: radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1\nOutput: true\nExplanation: Circle and rectangle share the point (1,0).\n\nExample 2:\nInput: radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1\nOutput: false\n\nExample 3:\nInput: radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1\nOutput: true\n\nConstraints:\n- 1 <= radius <= 2000\n- -10^4 <= xCenter, yCenter <= 10^4\n- -10^4 <= x1 < x2 <= 10^4\n- -10^4 <= y1 < y2 <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def checkOverlap(self, radius, x_center, y_center, x1, y1, x2, y2):\n \"\"\"\n :type radius: int\n :type x_center: int\n :type y_center: int\n :type x1: int\n :type y1: int\n :type x2: int\n :type y2: int\n :rtype: bool\n \"\"\"\n x1 -= x_center\n y1 -= y_center\n x2 -= x_center\n y2 -= y_center\n x = x1 if x1 > 0 else x2 if x2 < 0 else 0\n y = y1 if y1 > 0 else y2 if y2 < 0 else 0\n return x**2 + y**2 <= radius**2\n\n\n# Time: O(1)\n# Space: O(1)\nclass Solution2(object):\n def checkOverlap(self, radius, x_center, y_center, x1, y1, x2, y2):\n \"\"\"\n :type radius: int\n :type x_center: int\n :type y_center: int\n :type x1: int\n :type y1: int\n :type x2: int\n :type y2: int\n :rtype: bool\n \"\"\"\n x1 -= x_center\n y1 -= y_center\n x2 -= x_center\n y2 -= y_center \n x = min(abs(x1), abs(x2)) if x1*x2 > 0 else 0\n y = min(abs(y1), abs(y2)) if y1*y2 > 0 else 0\n return x**2 + y**2 <= radius**2\n"}} diff --git a/cp/cp-10819.jsonl b/cp/cp-10819.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..86ae754cb83175de046ecaf4f63e7ce94abe4788 --- /dev/null +++ b/cp/cp-10819.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10819", "name": "LeetCode 1402: Reducing Dishes"} +{"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: Reducing Dishes (Difficulty: Hard)\nTags: Array, Dynamic Programming, Greedy, Sorting\n\nA chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.\nLike-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i].\nReturn the maximum sum of like-time coefficient that the chef can obtain after preparing some amount of dishes.\nDishes can be prepared in any order and the chef can discard some dishes to get this maximum value.\n\nExample 1:\nInput: satisfaction = [-1,-8,0,5,-9]\nOutput: 14\nExplanation: After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14).\nEach dish is prepared in one unit of time.\n\nExample 2:\nInput: satisfaction = [4,3,2]\nOutput: 20\nExplanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)\n\nExample 3:\nInput: satisfaction = [-1,-4,-5]\nOutput: 0\nExplanation: People do not like the dishes. No dish is prepared.\n\nConstraints:\n- n == satisfaction.length\n- 1 <= n <= 500\n- -1000 <= satisfaction[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def maxSatisfaction(self, satisfaction):\n \"\"\"\n :type satisfaction: List[int]\n :rtype: int\n \"\"\"\n satisfaction.sort(reverse=True)\n result, curr = 0, 0\n for x in satisfaction:\n curr += x\n if curr <= 0:\n break\n result += curr\n return result\n"}} diff --git a/cp/cp-10820.jsonl b/cp/cp-10820.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f7d4d9e6219605cd34eadf62d96f3bacdfeb3f95 --- /dev/null +++ b/cp/cp-10820.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10820", "name": "LeetCode 1403: Minimum Subsequence In Non Increasing Order"} +{"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: Minimum Subsequence in Non-Increasing Order (Difficulty: Easy)\nTags: Array, Greedy, Sorting\n\nGiven the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence.\nIf there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array.\nNote that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order.\n\nExample 1:\nInput: nums = [4,3,10,9,8]\nOutput: [10,9] \nExplanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements.\n\nExample 2:\nInput: nums = [4,4,7,6,7]\nOutput: [7,7,6] \nExplanation: The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-increasing order.\n\nConstraints:\n- 1 <= nums.length <= 500\n- 1 <= nums[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def minSubsequence(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n result, total, curr = [], sum(nums), 0\n nums.sort(reverse=True)\n for i, x in enumerate(nums):\n curr += x\n if curr > total-curr:\n break\n return nums[:i+1]\n"}} diff --git a/cp/cp-10821.jsonl b/cp/cp-10821.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f3ff5581444ac5cff79de147e0bde1c12fe06685 --- /dev/null +++ b/cp/cp-10821.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10821", "name": "LeetCode 1404: Number Of Steps To Reduce A Number In Binary Representation To One"} +{"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 Steps to Reduce a Number in Binary Representation to One (Difficulty: Medium)\nTags: String, Bit Manipulation, Simulation\n\nGiven the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:\nIt is guaranteed that you can always reach one for all test cases.\n\nExample 1:\nInput: s = \"1101\"\nOutput: 6\nExplanation: \"1101\" corressponds to number 13 in their decimal representation.\nStep 1) 13 is odd, add 1 and obtain 14. \nStep 2) 14 is even, divide by 2 and obtain 7.\nStep 3) 7 is odd, add 1 and obtain 8.\nStep 4) 8 is even, divide by 2 and obtain 4.  \nStep 5) 4 is even, divide by 2 and obtain 2. \nStep 6) 2 is even, divide by 2 and obtain 1.\n\nExample 2:\nInput: s = \"10\"\nOutput: 1\nExplanation: \"10\" corresponds to number 2 in their decimal representation.\nStep 1) 2 is even, divide by 2 and obtain 1.\n\nExample 3:\nInput: s = \"1\"\nOutput: 0\n\nConstraints:\n- 1 <= s.length <= 500\n- s consists of characters '0' or '1'\n- s[0] == '1'"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def numSteps(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result, carry = 0, 0\n for i in reversed(range(1, len(s))):\n if int(s[i]) + carry == 1:\n carry = 1 # once it was set, it would keep carrying forever\n result += 2\n else:\n result += 1\n return result+carry\n"}} diff --git a/cp/cp-10822.jsonl b/cp/cp-10822.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..493e7ad3eec91a4403ccfd2d9bcd961649c6d2da --- /dev/null +++ b/cp/cp-10822.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10822", "name": "LeetCode 1405: Longest Happy 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: Longest Happy String (Difficulty: Medium)\nTags: String, Greedy, Heap (Priority Queue)\n\nA string s is called happy if it satisfies the following conditions:\nGiven three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string \"\".\nA substring is a contiguous sequence of characters within a string.\n\nExample 1:\nInput: a = 1, b = 1, c = 7\nOutput: \"ccaccbcc\"\nExplanation: \"ccbccacc\" would also be a correct answer.\n\nExample 2:\nInput: a = 7, b = 1, c = 0\nOutput: \"aabaa\"\nExplanation: It is the only correct answer in this case.\n\nConstraints:\n- 0 <= a, b, c <= 100\n- a + b + c > 0"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport heapq\n\n\nclass Solution(object):\n def longestDiverseString(self, a, b, c):\n \"\"\"\n :type a: int\n :type b: int\n :type c: int\n :rtype: str\n \"\"\"\n max_heap = []\n if a:\n heapq.heappush(max_heap, (-a, 'a'))\n if b:\n heapq.heappush(max_heap, (-b, 'b'))\n if c:\n heapq.heappush(max_heap, (-c, 'c'))\n result = []\n while max_heap:\n count1, c1 = heapq.heappop(max_heap)\n if len(result) >= 2 and result[-1] == result[-2] == c1:\n if not max_heap:\n return \"\".join(result)\n count2, c2 = heapq.heappop(max_heap)\n result.append(c2)\n count2 += 1\n if count2:\n heapq.heappush(max_heap, (count2, c2))\n heapq.heappush(max_heap, (count1, c1))\n continue\n result.append(c1)\n count1 += 1\n if count1 != 0:\n heapq.heappush(max_heap, (count1, c1))\n return \"\".join(result)\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def longestDiverseString(self, a, b, c):\n \"\"\"\n :type a: int\n :type b: int\n :type c: int\n :rtype: str\n \"\"\"\n choices = [[a, 'a'], [b, 'b'], [c, 'c']]\n result = []\n for _ in range(a+b+c):\n choices.sort(reverse=True)\n for i, (x, c) in enumerate(choices):\n if x and result[-2:] != [c, c]:\n result.append(c)\n choices[i][0] -= 1\n break\n else:\n break\n return \"\".join(result)\n"}} diff --git a/cp/cp-10823.jsonl b/cp/cp-10823.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1ed82a26d4fd0f19fb5f4b27d65451b8c85581f8 --- /dev/null +++ b/cp/cp-10823.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10823", "name": "LeetCode 1406: Stone Game 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: Stone Game III (Difficulty: Hard)\nTags: Array, Math, Dynamic Programming, Game Theory\n\nAlice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.\nAlice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row.\nThe score of each player is the sum of the values of the stones taken. The score of each player is 0 initially.\nThe objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.\nAssume Alice and Bob play optimally.\nReturn \"Alice\" if Alice will win, \"Bob\" if Bob will win, or \"Tie\" if they will end the game with the same score.\n\nExample 1:\nInput: stoneValue = [1,2,3,7]\nOutput: \"Bob\"\nExplanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.\n\nExample 2:\nInput: stoneValue = [1,2,3,-9]\nOutput: \"Alice\"\nExplanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score.\nIf Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.\nIf Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.\nRemember that both play optimally so here Alice will choose the scenario that makes her win.\n\nExample 3:\nInput: stoneValue = [1,2,3,6]\nOutput: \"Tie\"\nExplanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.\n\nConstraints:\n- 1 <= stoneValue.length <= 5 * 10^4\n- -1000 <= stoneValue[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def stoneGameIII(self, stoneValue):\n \"\"\"\n :type stoneValue: List[int]\n :rtype: str\n \"\"\"\n dp = [float(\"-inf\")]*3\n dp[len(stoneValue)%3] = 0\n for i in reversed(range(len(stoneValue))):\n max_dp, curr = float(\"-inf\"), 0\n for j in range(min(3, len(stoneValue)-i)):\n curr += stoneValue[i+j]\n max_dp = max(max_dp, curr-dp[(i+j+1)%3])\n dp[i%3] = max_dp\n return [\"Tie\", \"Alice\", \"Bob\"][cmp(dp[0], 0)]\n"}} diff --git a/cp/cp-10824.jsonl b/cp/cp-10824.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..099325241e4a145f4573872883ddfd866a840002 --- /dev/null +++ b/cp/cp-10824.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10824", "name": "LeetCode 1408: String Matching In An 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: String Matching in an Array (Difficulty: Easy)\nTags: Array, String, String Matching\n\nGiven an array of string words, return all strings in words that are a substring of another word. You can return the answer in any order.\n\nExample 1:\nInput: words = [\"mass\",\"as\",\"hero\",\"superhero\"]\nOutput: [\"as\",\"hero\"]\nExplanation: \"as\" is substring of \"mass\" and \"hero\" is substring of \"superhero\".\n[\"hero\",\"as\"] is also a valid answer.\n\nExample 2:\nInput: words = [\"leetcode\",\"et\",\"code\"]\nOutput: [\"et\",\"code\"]\nExplanation: \"et\", \"code\" are substring of \"leetcode\".\n\nExample 3:\nInput: words = [\"blue\",\"green\",\"bu\"]\nOutput: []\nExplanation: No string of words is substring of another string.\n\nConstraints:\n- 1 <= words.length <= 100\n- 1 <= words[i].length <= 30\n- words[i] contains only lowercase English letters.\n- All the strings of words are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + m + z) = O(n), n is the total size of patterns\n# , m is the total size of query string\n# , z is the number of all matched strings\n# , O(n) = O(m) = O(z) in this problem\n# Space: O(t), t is the total size of ac automata trie\n\nimport collections\n\n\nclass AhoNode(object):\n def __init__(self):\n self.children = collections.defaultdict(AhoNode)\n self.indices = []\n self.suffix = None\n self.output = None\n\n\nclass AhoTrie(object):\n\n def step(self, letter):\n while self.__node and letter not in self.__node.children:\n self.__node = self.__node.suffix\n self.__node = self.__node.children[letter] if self.__node else self.__root\n return self.__get_ac_node_outputs(self.__node)\n \n def reset(self):\n self.__node = self.__root\n \n def __init__(self, patterns):\n self.__root = self.__create_ac_trie(patterns)\n self.__node = self.__create_ac_suffix_and_output_links(self.__root)\n \n def __create_ac_trie(self, patterns): # Time: O(n), Space: O(t)\n root = AhoNode()\n for i, pattern in enumerate(patterns):\n node = root\n for c in pattern:\n node = node.children[c]\n node.indices.append(i)\n return root\n\n def __create_ac_suffix_and_output_links(self, root): # Time: O(n), Space: O(t)\n queue = collections.deque()\n for node in root.children.itervalues():\n queue.append(node)\n node.suffix = root\n\n while queue:\n node = queue.popleft()\n for c, child in node.children.iteritems():\n queue.append(child)\n suffix = node.suffix\n while suffix and c not in suffix.children:\n suffix = suffix.suffix\n child.suffix = suffix.children[c] if suffix else root\n child.output = child.suffix if child.suffix.indices else child.suffix.output\n \n return root\n\n def __get_ac_node_outputs(self, node): # Time: O(z)\n result = []\n for i in node.indices:\n result.append(i)\n output = node.output\n while output:\n for i in output.indices:\n result.append(i)\n output = output.output\n return result\n \n \nclass Solution(object):\n def stringMatching(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: List[str]\n \"\"\"\n trie = AhoTrie(words)\n lookup = set()\n for i in range(len(words)):\n trie.reset()\n for c in words[i]:\n for j in trie.step(c):\n if j != i:\n lookup.add(j)\n return [words[i] for i in lookup]\n\n\n# Time: O(n^2 * l), n is the number of strings\n# Space: O(l) , l is the max length of strings\nclass Solution2(object):\n def stringMatching(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: List[str]\n \"\"\"\n def getPrefix(pattern):\n prefix = [-1]*len(pattern)\n j = -1\n for i in range(1, len(pattern)):\n while j != -1 and pattern[j+1] != pattern[i]:\n j = prefix[j]\n if pattern[j+1] == pattern[i]:\n j += 1\n prefix[i] = j\n return prefix\n \n def kmp(text, pattern, prefix):\n if not pattern:\n return 0\n if len(text) < len(pattern):\n return -1\n j = -1\n for i in range(len(text)):\n while j != -1 and pattern[j+1] != text[i]:\n j = prefix[j]\n if pattern[j+1] == text[i]:\n j += 1\n if j+1 == len(pattern):\n return i-j\n return -1\n \n result = []\n for i, pattern in enumerate(words):\n prefix = getPrefix(pattern)\n for j, text in enumerate(words):\n if i != j and kmp(text, pattern, prefix) != -1:\n result.append(pattern)\n break\n return result\n\n\n# Time: O(n^2 * l^2), n is the number of strings\n# Space: O(1) , l is the max length of strings\nclass Solution3(object):\n def stringMatching(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: List[str]\n \"\"\"\n result = []\n for i, pattern in enumerate(words):\n for j, text in enumerate(words):\n if i != j and pattern in text:\n result.append(pattern)\n break\n return result\n"}} diff --git a/cp/cp-10825.jsonl b/cp/cp-10825.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5ff73378f60fe89281d343454be290f4e7597774 --- /dev/null +++ b/cp/cp-10825.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10825", "name": "LeetCode 1409: Queries On A Permutation With Key"} +{"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: Queries on a Permutation With Key (Difficulty: Medium)\nTags: Array, Binary Indexed Tree, Simulation\n\nGiven the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:\nReturn an array containing the result for the given queries.\n\nExample 1:\nInput: queries = [3,1,2,1], m = 5\nOutput: [2,1,2,1] \nExplanation: The queries are processed as follow: \nFor i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. \nFor i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. \nFor i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. \nFor i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. \nTherefore, the array containing the result is [2,1,2,1].\n\nExample 2:\nInput: queries = [4,1,2,2], m = 4\nOutput: [3,1,2,0]\n\nExample 3:\nInput: queries = [7,5,5,8,3], m = 8\nOutput: [6,5,0,7,5]\n\nConstraints:\n- 1 <= m <= 10^3\n- 1 <= queries.length <= m\n- 1 <= queries[i] <= m"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass BIT(object): # Fenwick Tree, 1-indexed\n def __init__(self, n):\n self.__bit = [0] * n\n\n def add(self, i, val):\n while i < len(self.__bit):\n self.__bit[i] += val\n i += (i & -i)\n\n def sum(self, i):\n result = 0\n while i > 0:\n result += self.__bit[i]\n i -= (i & -i)\n return result\n\n\nclass Solution(object):\n def processQueries(self, queries, m):\n \"\"\"\n :type queries: List[int]\n :type m: int\n :rtype: List[int]\n \"\"\"\n bit = BIT(2*m+1)\n lookup = {}\n for i in range(1, m+1):\n bit.add(m+i, 1)\n lookup[i] = m+i\n result, curr = [], m\n for q in queries:\n i = lookup.pop(q)\n result.append(bit.sum(i-1))\n bit.add(i, -1)\n lookup[q] = curr\n bit.add(curr, 1)\n curr -= 1\n return result\n"}} diff --git a/cp/cp-10826.jsonl b/cp/cp-10826.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..de7ad55a01fa0071fb8f93ec91878ed1bf17b7b3 --- /dev/null +++ b/cp/cp-10826.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10826", "name": "LeetCode 1410: Html Entity Parser"} +{"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: HTML Entity Parser (Difficulty: Medium)\nTags: Hash Table, String\n\nHTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.\nThe special characters and their entities for HTML are:\nGiven the input text string to the HTML parser, you have to implement the entity parser.\nReturn the text after replacing the entities by the special characters.\n\nExample 1:\nInput: text = \"& is an HTML entity but &ambassador; is not.\"\nOutput: \"& is an HTML entity but &ambassador; is not.\"\nExplanation: The parser will replace the & entity by &\n\nExample 2:\nInput: text = \"and I quote: "..."\"\nOutput: \"and I quote: \\\"...\\\"\"\n\nConstraints:\n- 1 <= text.length <= 10^5\n- The string may contain any possible characters out of all the 256 ASCII characters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + m + z) = O(m), n is the total size of patterns\n# , m is the total size of query string\n# , z is the number of all matched strings\n# , O(n) = O(1), O(z) = O(m) in this problem\n# Space: O(t) = O(1), t is the total size of ac automata trie\n# , O(t) = O(1) in this problem\n\nimport collections\n\n\nclass AhoNode(object):\n def __init__(self):\n self.children = collections.defaultdict(AhoNode)\n self.indices = []\n self.suffix = None\n self.output = None\n\n\nclass AhoTrie(object):\n\n def step(self, letter):\n while self.__node and letter not in self.__node.children:\n self.__node = self.__node.suffix\n self.__node = self.__node.children[letter] if self.__node else self.__root\n return self.__get_ac_node_outputs(self.__node)\n \n def __init__(self, patterns):\n self.__root = self.__create_ac_trie(patterns)\n self.__node = self.__create_ac_suffix_and_output_links(self.__root)\n \n def __create_ac_trie(self, patterns): # Time: O(n), Space: O(t)\n root = AhoNode()\n for i, pattern in enumerate(patterns):\n node = root\n for c in pattern:\n node = node.children[c]\n node.indices.append(i)\n return root\n\n def __create_ac_suffix_and_output_links(self, root): # Time: O(n), Space: O(t)\n queue = collections.deque()\n for node in root.children.itervalues():\n queue.append(node)\n node.suffix = root\n\n while queue:\n node = queue.popleft()\n for c, child in node.children.iteritems():\n queue.append(child)\n suffix = node.suffix\n while suffix and c not in suffix.children:\n suffix = suffix.suffix\n child.suffix = suffix.children[c] if suffix else root\n child.output = child.suffix if child.suffix.indices else child.suffix.output\n \n return root\n\n def __get_ac_node_outputs(self, node): # Time: O(z)\n result = []\n for i in node.indices:\n result.append(i)\n output = node.output\n while output:\n for i in output.indices:\n result.append(i)\n output = output.output\n return result\n\n\nclass Solution(object):\n def entityParser(self, text):\n \"\"\"\n :type text: str\n :rtype: str\n \"\"\"\n patterns = [\""\", \"'\", \"&\", \">\", \"<\", \"⁄\"]\n chars = [\"\\\"\", \"'\", \"&\", \">\", \"<\", \"/\"]\n trie = AhoTrie(patterns)\n positions = []\n for i in range(len(text)):\n for j in trie.step(text[i]):\n positions.append([i-len(patterns[j])+1, j])\n result = []\n i, j = 0, 0\n while i != len(text):\n if j == len(positions) or i != positions[j][0]: \n result.append(text[i])\n i += 1\n else:\n result.append(chars[positions[j][1]])\n i += len(patterns[positions[j][1]])\n j += 1\n return \"\".join(result)\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def entityParser(self, text):\n \"\"\"\n :type text: str\n :rtype: str\n \"\"\"\n patterns = [\""\", \"'\", \"&\", \">\", \"<\", \"⁄\"]\n chars = [\"\\\"\", \"'\", \"&\", \">\", \"<\", \"/\"]\n result = []\n i, j = 0, 0\n while i != len(text):\n if text[i] != '&': \n result.append(text[i])\n i += 1\n else:\n for j, pattern in enumerate(patterns):\n if pattern == text[i:i+len(pattern)]:\n result.append(chars[j])\n i += len(pattern)\n break\n else:\n result.append(text[i])\n i += 1\n return \"\".join(result)\n"}} diff --git a/cp/cp-10827.jsonl b/cp/cp-10827.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bafbde74b77f8f0b3f82fc9efe1e8ffc39aba20e --- /dev/null +++ b/cp/cp-10827.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10827", "name": "LeetCode 1411: Number Of Ways To Paint N 3 Grid"} +{"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 Ways to Paint N × 3 Grid (Difficulty: Hard)\nTags: Dynamic Programming\n\nYou have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).\nGiven n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 109 + 7.\n\nExample 1:\nInput: n = 1\nOutput: 12\nExplanation: There are 12 possible way to paint the grid as shown.\n\nExample 2:\nInput: n = 5000\nOutput: 30228214\n\nConstraints:\n- n == grid.length\n- 1 <= n <= 5000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def numOfWays(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n def matrix_expo(A, K):\n result = [[int(i==j) for j in range(len(A))]\n for i in range(len(A))]\n while K:\n if K % 2:\n result = matrix_mult(result, A)\n A = matrix_mult(A, A)\n K /= 2\n return result\n\n def matrix_mult(A, B):\n ZB = zip(*B)\n return [[sum(a*b % MOD for a, b in itertools.izip(row, col)) % MOD\n for col in ZB] for row in A]\n \n MOD = 10**9 + 7\n T = [[3, 2],\n [2, 2]]\n return sum(matrix_mult([[6, 6]], matrix_expo(T, n-1))[0]) % MOD # [a1, a0] * T^(n-1)\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def numOfWays(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n MOD = 10**9 + 7\n aba, abc = 6, 6\n for _ in range(n-1):\n aba, abc = (3*aba%MOD + 2*abc%MOD)%MOD, \\\n (2*abc%MOD + 2*aba%MOD)%MOD\n return (aba+abc)%MOD\n"}} diff --git a/cp/cp-10828.jsonl b/cp/cp-10828.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5b85e086a8a0130c80780bd4de27cb29aa6b1ea6 --- /dev/null +++ b/cp/cp-10828.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10828", "name": "LeetCode 1413: Minimum Value To Get Positive Step By Step Sum"} +{"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: Minimum Value to Get Positive Step by Step Sum (Difficulty: Easy)\nTags: Array, Prefix Sum\n\nGiven an array of integers nums, you start with an initial positive value startValue.\nIn each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).\nReturn the minimum positive value of startValue such that the step by step sum is never less than 1.\n\nExample 1:\nInput: nums = [-3,2,-3,4,2]\nOutput: 5\nExplanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.\nstep by step sum\nstartValue = 4 | startValue = 5 | nums\n (4 -3 ) = 1 | (5 -3 ) = 2 | -3\n (1 +2 ) = 3 | (2 +2 ) = 4 | 2\n (3 -3 ) = 0 | (4 -3 ) = 1 | -3\n (0 +4 ) = 4 | (1 +4 ) = 5 | 4\n (4 +2 ) = 6 | (5 +2 ) = 7 | 2\n\nExample 2:\nInput: nums = [1,2]\nOutput: 1\nExplanation: Minimum start value should be positive.\n\nExample 3:\nInput: nums = [1,-2,-3]\nOutput: 5\n\nConstraints:\n- 1 <= nums.length <= 100\n- -100 <= nums[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minStartValue(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n min_prefix, prefix = 0, 0\n for num in nums:\n prefix += num\n min_prefix = min(min_prefix, prefix)\n return 1-min_prefix\n"}} diff --git a/cp/cp-10829.jsonl b/cp/cp-10829.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7f248033aff2922a3d0c7b46157860cefe354d6e --- /dev/null +++ b/cp/cp-10829.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10829", "name": "LeetCode 1414: Find The Minimum Number Of Fibonacci Numbers Whose Sum Is K"} +{"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 the Minimum Number of Fibonacci Numbers Whose Sum Is K (Difficulty: Medium)\nTags: Math, Greedy\n\nGiven an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.\nThe Fibonacci numbers are defined as:\n\nExample 1:\nInput: k = 7\nOutput: 2 \nExplanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... \nFor k = 7 we can use 2 + 5 = 7.\n\nExample 2:\nInput: k = 10\nOutput: 2 \nExplanation: For k = 10 we can use 2 + 8 = 10.\n\nExample 3:\nInput: k = 19\nOutput: 3 \nExplanation: For k = 19 we can use 1 + 5 + 13 = 19.\n\nConstraints:\n- 1 <= k <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logk)\n# Space: O(1)\n\nclass Solution(object):\n def findMinFibonacciNumbers(self, k):\n \"\"\"\n :type k: int\n :rtype: int\n \"\"\"\n result, a, b = 0, 1, 1\n while b <= k:\n b, a = a+b, b\n while k:\n if a <= k:\n k -= a\n result += 1\n a, b = b-a, a\n return result\n"}} diff --git a/cp/cp-10830.jsonl b/cp/cp-10830.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9cc977705d585ab9e412ae24bd4fb88017f9781f --- /dev/null +++ b/cp/cp-10830.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10830", "name": "LeetCode 1415: The K Th Lexicographical String Of All Happy Strings Of Length N"} +{"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: The k-th Lexicographical String of All Happy Strings of Length n (Difficulty: Medium)\nTags: String, Backtracking\n\nA happy string is a string that:\nFor example, strings \"abc\", \"ac\", \"b\" and \"abcbabcbcb\" are all happy strings and strings \"aa\", \"baa\" and \"ababbc\" are not happy strings.\nGiven two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order.\nReturn the kth string of this list or return an empty string if there are less than k happy strings of length n.\n\nExample 1:\nInput: n = 1, k = 3\nOutput: \"c\"\nExplanation: The list [\"a\", \"b\", \"c\"] contains all happy strings of length 1. The third string is \"c\".\n\nExample 2:\nInput: n = 1, k = 4\nOutput: \"\"\nExplanation: There are only 3 happy strings of length 1.\n\nExample 3:\nInput: n = 3, k = 9\nOutput: \"cab\"\nExplanation: There are 12 different happy string of length 3 [\"aba\", \"abc\", \"aca\", \"acb\", \"bab\", \"bac\", \"bca\", \"bcb\", \"cab\", \"cac\", \"cba\", \"cbc\"]. You will find the 9th string = \"cab\"\n\nConstraints:\n- 1 <= n <= 10\n- 1 <= k <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def getHappyString(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n base = 2**(n-1)\n if k > 3*base:\n return \"\"\n result = [chr(ord('a')+(k-1)//base)]\n while base > 1:\n k -= (k-1)//base*base\n base //= 2\n result.append(('a' if result[-1] != 'a' else 'b') if (k-1)//base == 0 else\n ('c' if result[-1] != 'c' else 'b'))\n return \"\".join(result)\n"}} diff --git a/cp/cp-10831.jsonl b/cp/cp-10831.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2f33fe2953735a304845aa66885e24e0ea55e63f --- /dev/null +++ b/cp/cp-10831.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10831", "name": "LeetCode 1416: Restore The 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: Restore The Array (Difficulty: Hard)\nTags: String, Dynamic Programming\n\nA program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array.\nGiven the string s and the integer k, return the number of the possible arrays that can be printed as s using the mentioned program. Since the answer may be very large, return it modulo 109 + 7.\n\nExample 1:\nInput: s = \"1000\", k = 10000\nOutput: 1\nExplanation: The only possible array is [1000]\n\nExample 2:\nInput: s = \"1000\", k = 10\nOutput: 0\nExplanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.\n\nExample 3:\nInput: s = \"1317\", k = 2000\nOutput: 8\nExplanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s consists of only digits and does not contain leading zeros.\n- 1 <= k <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogk)\n# Space: O(logk)\n\nclass Solution(object):\n def numberOfArrays(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: int\n \"\"\"\n MOD = 10**9 + 7\n klen = len(str(k))\n dp = [0]*(klen+1)\n dp[len(s)%len(dp)] = 1\n for i in reversed(range(len(s))):\n dp[i%len(dp)] = 0\n if s[i] == '0':\n continue\n curr = 0\n for j in range(i, min(i+klen, len(s))):\n curr = 10*curr + int(s[j])\n if curr > k:\n break\n dp[i%len(dp)] = (dp[i%len(dp)] + dp[(j+1)%len(dp)])%MOD\n return dp[0]\n"}} diff --git a/cp/cp-10832.jsonl b/cp/cp-10832.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fb7884d5d7a4f77476c44c449548b3a97ffd2383 --- /dev/null +++ b/cp/cp-10832.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10832", "name": "LeetCode 1417: Reformat The 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: Reformat The String (Difficulty: Easy)\nTags: String\n\nYou are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).\nYou have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.\nReturn the reformatted string or return an empty string if it is impossible to reformat the string.\n\nExample 1:\nInput: s = \"a0b1c2\"\nOutput: \"0a1b2c\"\nExplanation: No two adjacent characters have the same type in \"0a1b2c\". \"a0b1c2\", \"0a1b2c\", \"0c2a1b\" are also valid permutations.\n\nExample 2:\nInput: s = \"leetcode\"\nOutput: \"\"\nExplanation: \"leetcode\" has only characters so we cannot separate them by digits.\n\nExample 3:\nInput: s = \"1229857369\"\nOutput: \"\"\nExplanation: \"1229857369\" has only digits so we cannot separate them by characters.\n\nConstraints:\n- 1 <= s.length <= 500\n- s consists of only lowercase English letters and/or digits."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def reformat(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n def char_gen(start, end, count):\n for c in range(ord(start), ord(end)+1):\n c = chr(c)\n for i in range(count[c]):\n yield c\n yield ''\n \n count = collections.defaultdict(int)\n alpha_cnt = 0\n for c in s:\n count[c] += 1\n if c.isalpha():\n alpha_cnt += 1\n if abs(len(s)-2*alpha_cnt) > 1:\n return \"\"\n\n result = []\n it1, it2 = char_gen('a', 'z', count), char_gen('0', '9', count)\n if alpha_cnt < len(s)-alpha_cnt:\n it1, it2 = it2, it1\n while len(result) < len(s):\n result.append(next(it1))\n result.append(next(it2))\n return \"\".join(result)\n"}} diff --git a/cp/cp-10833.jsonl b/cp/cp-10833.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9bea0821e113545457b2d4296552d1c59d4072a7 --- /dev/null +++ b/cp/cp-10833.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10833", "name": "LeetCode 1418: Display Table Of Food Orders In A Restaurant"} +{"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: Display Table of Food Orders in a Restaurant (Difficulty: Medium)\nTags: Array, Hash Table, String, Sorting, Ordered Set\n\nGiven the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.\nReturn the restaurant's “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.\n\nExample 1:\nInput: orders = [[\"David\",\"3\",\"Ceviche\"],[\"Corina\",\"10\",\"Beef Burrito\"],[\"David\",\"3\",\"Fried Chicken\"],[\"Carla\",\"5\",\"Water\"],[\"Carla\",\"5\",\"Ceviche\"],[\"Rous\",\"3\",\"Ceviche\"]]\r\nOutput: [[\"Table\",\"Beef Burrito\",\"Ceviche\",\"Fried Chicken\",\"Water\"],[\"3\",\"0\",\"2\",\"1\",\"0\"],[\"5\",\"0\",\"1\",\"0\",\"1\"],[\"10\",\"1\",\"0\",\"0\",\"0\"]] \r\nExplanation:\r\nThe displaying table looks like:\r\nTable,Beef Burrito,Ceviche,Fried Chicken,Water\r\n3 ,0 ,2 ,1 ,0\r\n5 ,0 ,1 ,0 ,1\r\n10 ,1 ,0 ,0 ,0\r\nFor the table 3: David orders \"Ceviche\" and \"Fried Chicken\", and Rous orders \"Ceviche\".\r\nFor the table 5: Carla orders \"Water\" and \"Ceviche\".\r\nFor the table 10: Corina orders \"Beef Burrito\".\n\nExample 2:\nInput: orders = [[\"James\",\"12\",\"Fried Chicken\"],[\"Ratesh\",\"12\",\"Fried Chicken\"],[\"Amadeus\",\"12\",\"Fried Chicken\"],[\"Adam\",\"1\",\"Canadian Waffles\"],[\"Brianna\",\"1\",\"Canadian Waffles\"]]\r\nOutput: [[\"Table\",\"Canadian Waffles\",\"Fried Chicken\"],[\"1\",\"2\",\"0\"],[\"12\",\"0\",\"3\"]] \r\nExplanation: \r\nFor the table 1: Adam and Brianna order \"Canadian Waffles\".\r\nFor the table 12: James, Ratesh and Amadeus order \"Fried Chicken\".\n\nExample 3:\nInput: orders = [[\"Laura\",\"2\",\"Bean Burrito\"],[\"Jhon\",\"2\",\"Beef Burrito\"],[\"Melissa\",\"2\",\"Soda\"]]\r\nOutput: [[\"Table\",\"Bean Burrito\",\"Beef Burrito\",\"Soda\"],[\"2\",\"1\",\"1\",\"1\"]]\n\nConstraints:\n- 1 <= orders.length <= 5 * 10^4\n- orders[i].length == 3\n- 1 <= customerNamei.length, foodItemi.length <= 20\n- customerNamei and foodItemi consist of lowercase and uppercase English letters and the space character.\n- tableNumberi is a valid integer between 1 and 500."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + tlogt + flogf)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def displayTable(self, orders):\n \"\"\"\n :type orders: List[List[str]]\n :rtype: List[List[str]]\n \"\"\"\n table_count = collections.defaultdict(collections.Counter)\n for _, table, food in orders:\n table_count[int(table)][food] += 1\n foods = sorted({food for _, _, food in orders})\n result = [[\"Table\"]]\n result[0].extend(foods)\n for table in sorted(table_count):\n result.append([str(table)])\n result[-1].extend(str(table_count[table][food]) for food in foods)\n return result\n"}} diff --git a/cp/cp-10834.jsonl b/cp/cp-10834.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fa92a72730a1a70aec015c165efbe72738fe8833 --- /dev/null +++ b/cp/cp-10834.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10834", "name": "LeetCode 1419: Minimum Number Of Frogs Croaking"} +{"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: Minimum Number of Frogs Croaking (Difficulty: Medium)\nTags: String, Counting\n\nYou are given the string croakOfFrogs, which represents a combination of the string \"croak\" from different frogs, that is, multiple frogs can croak at the same time, so multiple \"croak\" are mixed.\nReturn the minimum number of different frogs to finish all the croaks in the given string.\nA valid \"croak\" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid \"croak\" return -1.\n\nExample 1:\nInput: croakOfFrogs = \"croakcroak\"\nOutput: 1 \nExplanation: One frog yelling \"croak\" twice.\n\nExample 2:\nInput: croakOfFrogs = \"crcoakroak\"\nOutput: 2 \nExplanation: The minimum number of frogs is two. \nThe first frog could yell \"crcoakroak\".\nThe second frog could yell later \"crcoakroak\".\n\nExample 3:\nInput: croakOfFrogs = \"croakcrook\"\nOutput: -1\nExplanation: The given string is an invalid combination of \"croak\" from different frogs.\n\nConstraints:\n- 1 <= croakOfFrogs.length <= 10^5\n- croakOfFrogs is either 'c', 'r', 'o', 'a', or 'k'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minNumberOfFrogs(self, croakOfFrogs):\n \"\"\"\n :type croakOfFrogs: str\n :rtype: int\n \"\"\"\n S = \"croak\"\n lookup = [0]*len(S)\n result = 0\n for c in croakOfFrogs:\n i = S.find(c)\n lookup[i] += 1\n if lookup[i-1]:\n lookup[i-1] -= 1\n elif i == 0:\n result += 1\n else:\n return -1\n return result if result == lookup[-1] else -1\n"}} diff --git a/cp/cp-10835.jsonl b/cp/cp-10835.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9e2dd028d0e75c4660c41775a70e4a79744e9007 --- /dev/null +++ b/cp/cp-10835.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10835", "name": "LeetCode 1420: Build Array Where You Can Find The Maximum Exactly K Comparisons"} +{"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: Build Array Where You Can Find The Maximum Exactly K Comparisons (Difficulty: Hard)\nTags: Dynamic Programming, Prefix Sum\n\nYou are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:\nYou should build the array arr which has the following properties:\nReturn the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 109 + 7.\n\nExample 1:\nInput: n = 2, m = 3, k = 1\nOutput: 6\nExplanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]\n\nExample 2:\nInput: n = 5, m = 2, k = 3\nOutput: 0\nExplanation: There are no possible arrays that satisfy the mentioned conditions.\n\nExample 3:\nInput: n = 9, m = 1, k = 1\nOutput: 1\nExplanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]\n\nConstraints:\n- 1 <= n <= 50\n- 1 <= m <= 100\n- 0 <= k <= n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * m * k)\n# Space: O(m * k)\n\nclass Solution(object):\n def numOfArrays(self, n, m, k):\n \"\"\"\n :type n: int\n :type m: int\n :type k: int\n :rtype: int\n \"\"\"\n MOD = 10**9 + 7\n # dp[l][i][j] = number of ways of constructing array length l with max element i at search cost j\n dp = [[[0]*(k+1) for _ in range(m+1)] for _ in range(2)]\n # prefix_dp[l][i][j] = sum(dp[l][i][j] for i in [1..i])\n prefix_dp = [[[0]*(k+1) for _ in range(m+1)] for _ in range(2)]\n for i in range(1, m+1):\n dp[1][i][1] = 1\n prefix_dp[1][i][1] = (prefix_dp[1][i-1][1] + dp[1][i][1])%MOD\n for l in range(2, n+1):\n for i in range(1, m+1):\n for j in range(1, k+1):\n dp[l%2][i][j] = (i*dp[(l-1)%2][i][j]%MOD + prefix_dp[(l-1)%2][i-1][j-1])%MOD\n prefix_dp[l%2][i][j] = (prefix_dp[l%2][i-1][j] + dp[l%2][i][j])%MOD\n return prefix_dp[n%2][m][k]\n"}} diff --git a/cp/cp-10836.jsonl b/cp/cp-10836.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..80ee048222b611d29188629c3b56ade9a2df63ce --- /dev/null +++ b/cp/cp-10836.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10836", "name": "LeetCode 1422: Maximum Score After Splitting A 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: Maximum Score After Splitting a String (Difficulty: Easy)\nTags: String, Prefix Sum\n\nGiven a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).\nThe score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.\n\nExample 1:\nInput: s = \"011101\"\nOutput: 5 \nExplanation: \nAll possible ways of splitting s into two non-empty substrings are:\nleft = \"0\" and right = \"11101\", score = 1 + 4 = 5 \nleft = \"01\" and right = \"1101\", score = 1 + 3 = 4 \nleft = \"011\" and right = \"101\", score = 1 + 2 = 3 \nleft = \"0111\" and right = \"01\", score = 1 + 1 = 2 \nleft = \"01110\" and right = \"1\", score = 2 + 1 = 3\n\nExample 2:\nInput: s = \"00111\"\nOutput: 5\nExplanation: When left = \"00\" and right = \"111\", we get the maximum score = 2 + 3 = 5\n\nExample 3:\nInput: s = \"1111\"\nOutput: 3\n\nConstraints:\n- 2 <= s.length <= 500\n- The string s consists of characters '0' and '1' only."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxScore(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result, zeros, ones = 0, 0, 0\n for i in range(1, len(s)-1):\n if s[i] == '0':\n zeros += 1\n else:\n ones += 1\n result = max(result, zeros-ones)\n return result + ones + (s[0] == '0') + (s[-1] == '1')\n"}} diff --git a/cp/cp-10837.jsonl b/cp/cp-10837.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e9c1926f7d0ac7c945bc97df3477574dc70eeef0 --- /dev/null +++ b/cp/cp-10837.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10837", "name": "LeetCode 1423: Maximum Points You Can Obtain From Cards"} +{"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 Points You Can Obtain from Cards (Difficulty: Medium)\nTags: Array, Sliding Window, Prefix Sum\n\nThere are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.\nIn one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.\nYour score is the sum of the points of the cards you have taken.\nGiven the integer array cardPoints and the integer k, return the maximum score you can obtain.\n\nExample 1:\nInput: cardPoints = [1,2,3,4,5,6,1], k = 3\nOutput: 12\nExplanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.\n\nExample 2:\nInput: cardPoints = [2,2,2], k = 2\nOutput: 4\nExplanation: Regardless of which two cards you take, your score will always be 4.\n\nExample 3:\nInput: cardPoints = [9,7,7,9,7,7,9], k = 7\nOutput: 55\nExplanation: You have to take all the cards. Your score is the sum of points of all cards.\n\nConstraints:\n- 1 <= cardPoints.length <= 10^5\n- 1 <= cardPoints[i] <= 10^4\n- 1 <= k <= cardPoints.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxScore(self, cardPoints, k):\n \"\"\"\n :type cardPoints: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n result, total, curr, left = float(\"inf\"), 0, 0, 0\n for right, point in enumerate(cardPoints):\n total += point\n curr += point\n if right-left+1 > len(cardPoints)-k:\n curr -= cardPoints[left]\n left += 1\n if right-left+1 == len(cardPoints)-k:\n result = min(result, curr)\n return total-result\n"}} diff --git a/cp/cp-10838.jsonl b/cp/cp-10838.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..95ec0a30bb320a0264c517ddef428e1652236622 --- /dev/null +++ b/cp/cp-10838.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10838", "name": "LeetCode 1424: Diagonal Traverse 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: Diagonal Traverse II (Difficulty: Medium)\nTags: Array, Sorting, Heap (Priority Queue)\n\nGiven a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.\n\nExample 1:\nInput: nums = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [1,4,2,7,5,3,8,6,9]\n\nExample 2:\nInput: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]\nOutput: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i].length <= 10^5\n- 1 <= sum(nums[i].length) <= 10^5\n- 1 <= nums[i][j] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m)\n\nimport itertools\nimport collections\n\n\nclass Solution(object):\n def findDiagonalOrder(self, nums):\n \"\"\"\n :type nums: List[List[int]]\n :rtype: List[int]\n \"\"\"\n result, dq, col = [], collections.deque(), 0\n for i in range(len(nums)+max(itertools.imap(len, nums))-1):\n new_dq = collections.deque()\n if i < len(nums):\n dq.appendleft((i, 0))\n for r, c in dq:\n result.append(nums[r][c])\n if c+1 < len(nums[r]):\n new_dq.append((r, c+1))\n dq = new_dq\n return result\n\n\n# Time: O(m * n)\n# Space: O(m * n)\nclass Solution2(object):\n def findDiagonalOrder(self, nums):\n \"\"\"\n :type nums: List[List[int]]\n :rtype: List[int]\n \"\"\"\n result = []\n for r, row in enumerate(nums):\n for c, num in enumerate(row):\n if len(result) <= r+c:\n result.append([])\n result[r+c].append(num)\n return [num for row in result for num in reversed(row)]\n"}} diff --git a/cp/cp-10839.jsonl b/cp/cp-10839.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a5ab3e50a08395604c5c5d12a7278bb1505a5a21 --- /dev/null +++ b/cp/cp-10839.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10839", "name": "LeetCode 1425: Constrained Subset Sum"} +{"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: Constrained Subsequence Sum (Difficulty: Hard)\nTags: Array, Dynamic Programming, Queue, Sliding Window, Heap (Priority Queue), Monotonic Queue\n\nGiven an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.\nA subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.\n\nExample 1:\nInput: nums = [10,2,-10,5,20], k = 2\nOutput: 37\nExplanation: The subsequence is [10, 2, 5, 20].\n\nExample 2:\nInput: nums = [-1,-2,-3], k = 1\nOutput: -1\nExplanation: The subsequence must be non-empty, so we choose the largest number.\n\nExample 3:\nInput: nums = [10,-2,-10,-5,20], k = 2\nOutput: 23\nExplanation: The subsequence is [10, -2, -5, 20].\n\nConstraints:\n- 1 <= k <= nums.length <= 10^5\n- -10^4 <= nums[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(k)\n\nimport collections\n\n\nclass Solution(object):\n def constrainedSubsetSum(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n result, dq = float(\"-inf\"), collections.deque()\n for i in range(len(nums)):\n if dq and i-dq[0][0] == k+1:\n dq.popleft()\n curr = nums[i] + (dq[0][1] if dq else 0)\n while dq and dq[-1][1] <= curr:\n dq.pop()\n if curr > 0:\n dq.append((i, curr))\n result = max(result, curr)\n return result\n"}} diff --git a/cp/cp-10845.jsonl b/cp/cp-10845.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9e9a227033dfc1b61aec4f591ce8dabecae7af1e --- /dev/null +++ b/cp/cp-10845.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10845", "name": "LeetCode 1431: Kids With The Greatest Number Of Candies"} +{"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: Kids With the Greatest Number of Candies (Difficulty: Easy)\nTags: Array\n\nThere are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.\nReturn a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.\nNote that multiple kids can have the greatest number of candies.\n\nExample 1:\nInput: candies = [2,3,5,1,3], extraCandies = 3\nOutput: [true,true,true,false,true] \nExplanation: If you give all extraCandies to:\n- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n\nExample 2:\nInput: candies = [4,2,1,1,2], extraCandies = 1\nOutput: [true,false,false,false,false] \nExplanation: There is only 1 extra candy.\nKid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.\n\nExample 3:\nInput: candies = [12,1,12], extraCandies = 10\nOutput: [true,false,true]\n\nConstraints:\n- n == candies.length\n- 2 <= n <= 100\n- 1 <= candies[i] <= 100\n- 1 <= extraCandies <= 50"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def kidsWithCandies(self, candies, extraCandies):\n \"\"\"\n :type candies: List[int]\n :type extraCandies: int\n :rtype: List[bool]\n \"\"\"\n max_num = max(candies)\n return [x + extraCandies >= max_num for x in candies]\n"}} diff --git a/cp/cp-10846.jsonl b/cp/cp-10846.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d408c2bd33643f4273289bb5ecd1d34b678d9264 --- /dev/null +++ b/cp/cp-10846.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10846", "name": "LeetCode 1432: Max Difference You Can Get From Changing An Integer"} +{"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: Max Difference You Can Get From Changing an Integer (Difficulty: Medium)\nTags: Math, Greedy\n\nYou are given an integer num. You will apply the following steps to num two separate times:\nLet a and b be the two results from applying the operation to num independently.\nReturn the max difference between a and b.\nNote that neither a nor b may have any leading zeros, and must not be 0.\n\nExample 1:\nInput: num = 555\nOutput: 888\nExplanation: The first time pick x = 5 and y = 9 and store the new integer in a.\nThe second time pick x = 5 and y = 1 and store the new integer in b.\nWe have now a = 999 and b = 111 and max difference = 888\n\nExample 2:\nInput: num = 9\nOutput: 8\nExplanation: The first time pick x = 9 and y = 9 and store the new integer in a.\nThe second time pick x = 9 and y = 1 and store the new integer in b.\nWe have now a = 9 and b = 1 and max difference = 8\n\nConstraints:\n- 1 <= num <= 10^8"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\n# greedy\nclass Solution(object):\n def maxDiff(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n def find(num, check):\n result = 0\n while num:\n num, d = divmod(num, 10)\n if check(d):\n result = d\n return result\n\n def reverse(num, l):\n result = 0\n while num or l > 0:\n num, d = divmod(num, 10)\n result = result*10+d\n l -= 1\n return result\n\n def replace(num, x, y):\n result = l = 0\n while num:\n num, d = divmod(num, 10)\n if d == x:\n d = y\n result = result*10+d\n l += 1\n return reverse(result, l)\n \n b = find(num, lambda x: x < 9)\n a = find(num, lambda x: x > 1)\n return replace(num, b, 9)-replace(num, a, 1 if reverse(num, 0)%10 != 1 else 0)\n\n\n# Time: O(logn)\n# Space: O(logn)\n# greedy\nclass Solution2(object):\n def maxDiff(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n digits = str(num)\n b = next((x for x in digits if x < '9'), '0')\n a = next((x for x in digits if x > '1'), '0')\n return int(digits.replace(b, '9'))-int(digits.replace(a, '1' if digits[0] != '1' else '0'))\n"}} diff --git a/cp/cp-10847.jsonl b/cp/cp-10847.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d5ffdd7390799a9d401e8611d25517b278c3ea7c --- /dev/null +++ b/cp/cp-10847.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10847", "name": "LeetCode 1433: Check If A String Can Break Another 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: Check If a String Can Break Another String (Difficulty: Medium)\nTags: String, Greedy, Sorting\n\nGiven two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa.\nA string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.\n\nExample 1:\nInput: s1 = \"abc\", s2 = \"xya\"\nOutput: true\nExplanation: \"ayx\" is a permutation of s2=\"xya\" which can break to string \"abc\" which is a permutation of s1=\"abc\".\n\nExample 2:\nInput: s1 = \"abe\", s2 = \"acd\"\nOutput: false \nExplanation: All permutations for s1=\"abe\" are: \"abe\", \"aeb\", \"bae\", \"bea\", \"eab\" and \"eba\" and all permutation for s2=\"acd\" are: \"acd\", \"adc\", \"cad\", \"cda\", \"dac\" and \"dca\". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.\n\nExample 3:\nInput: s1 = \"leetcodee\", s2 = \"interview\"\nOutput: true\n\nConstraints:\n- s1.length == n\n- s2.length == n\n- 1 <= n <= 10^5\n- All strings consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\nimport string\n\n\nclass Solution(object):\n def checkIfCanBreak(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: bool\n \"\"\"\n def is_break(count1, count2):\n curr1, curr2 = 0, 0\n for c in string.ascii_lowercase:\n curr1 += count1[c]\n curr2 += count2[c]\n if curr1 < curr2:\n return False\n return True\n\n count1, count2 = collections.Counter(s1), collections.Counter(s2)\n return is_break(count1, count2) or is_break(count2, count1)\n \n\n# Time: O(nlogn)\n# Space: O(1)\nimport itertools\n\n\nclass Solution2(object):\n def checkIfCanBreak(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: bool\n \"\"\"\n return not {1, -1}.issubset(set(cmp(a, b) for a, b in itertools.izip(sorted(s1), sorted(s2))))\n\n\n# Time: O(nlogn)\n# Space: O(1)\nimport itertools\n\n\nclass Solution3(object):\n def checkIfCanBreak(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: bool\n \"\"\"\n s1, s2 = sorted(s1), sorted(s2)\n return all(a >= b for a, b in itertools.izip(s1, s2)) or \\\n all(a <= b for a, b in itertools.izip(s1, s2))\n"}} diff --git a/cp/cp-10848.jsonl b/cp/cp-10848.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..591ebb498632638c9d84898e7c124e77c5bf93f7 --- /dev/null +++ b/cp/cp-10848.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10848", "name": "LeetCode 1434: Number Of Ways To Wear Different Hats To Each Other"} +{"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 Ways to Wear Different Hats to Each Other (Difficulty: Hard)\nTags: Array, Dynamic Programming, Bit Manipulation, Bitmask\n\nThere are n people and 40 types of hats labeled from 1 to 40.\nGiven a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person.\nReturn the number of ways that n people can wear different hats from each other.\nSince the answer may be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: hats = [[3,4],[4,5],[5]]\nOutput: 1\nExplanation: There is only one way to choose hats given the conditions. \nFirst person choose hat 3, Second person choose hat 4 and last one hat 5.\n\nExample 2:\nInput: hats = [[3,5,1],[3,5]]\nOutput: 4\nExplanation: There are 4 ways to choose hats:\n(3,5), (5,3), (1,3) and (1,5)\n\nExample 3:\nInput: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]\nOutput: 24\nExplanation: Each person can choose hats labeled from 1 to 4.\nNumber of Permutations of (1,2,3,4) = 24.\n\nConstraints:\n- n == hats.length\n- 1 <= n <= 10\n- 1 <= hats[i].length <= 40\n- 1 <= hats[i][j] <= 40\n- hats[i] contains a list of unique integers."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(h * 2^n)\n# Space: O(2^n)\n\nclass Solution(object):\n def numberWays(self, hats):\n \"\"\"\n :type hats: List[List[int]]\n :rtype: int\n \"\"\"\n MOD = 10**9 + 7\n HAT_SIZE = 40\n hat_to_people = [[] for _ in range(HAT_SIZE)]\n for i in range(len(hats)):\n for h in hats[i]:\n hat_to_people[h-1].append(i)\n dp = [0]*(1< 4. \n[8,2,4] with maximum absolute diff |8-2| = 6 > 4.\n[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.\n[2] with maximum absolute diff |2-2| = 0 <= 4.\n[2,4] with maximum absolute diff |2-4| = 2 <= 4.\n[2,4,7] with maximum absolute diff |2-7| = 5 > 4.\n[4] with maximum absolute diff |4-4| = 0 <= 4.\n[4,7] with maximum absolute diff |4-7| = 3 <= 4.\n[7] with maximum absolute diff |7-7| = 0 <= 4. \nTherefore, the size of the longest subarray is 2.\n\nExample 2:\nInput: nums = [10,1,2,4,7,2], limit = 5\nOutput: 4 \nExplanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.\n\nExample 3:\nInput: nums = [4,2,2,2,4,4,2,2], limit = 0\nOutput: 3\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i] <= 10^9\n- 0 <= limit <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def longestSubarray(self, nums, limit):\n \"\"\"\n :type nums: List[int]\n :type limit: int\n :rtype: int\n \"\"\"\n max_dq, min_dq = collections.deque(), collections.deque()\n left = 0\n for right, num in enumerate(nums):\n while max_dq and nums[max_dq[-1]] <= num:\n max_dq.pop()\n max_dq.append(right)\n while min_dq and nums[min_dq[-1]] >= num:\n min_dq.pop()\n min_dq.append(right)\n if nums[max_dq[0]]-nums[min_dq[0]] > limit:\n if max_dq[0] == left:\n max_dq.popleft()\n if min_dq[0] == left:\n min_dq.popleft()\n left += 1 # advance left by one to not count in result\n return len(nums)-left\n\n\n# Time: O(n)\n# Space: O(n)\nimport collections\n\n\nclass Solution2(object):\n def longestSubarray(self, nums, limit):\n \"\"\"\n :type nums: List[int]\n :type limit: int\n :rtype: int\n \"\"\"\n max_dq, min_dq = collections.deque(), collections.deque()\n result, left = 0, 0\n for right, num in enumerate(nums):\n while max_dq and nums[max_dq[-1]] <= num:\n max_dq.pop()\n max_dq.append(right)\n while min_dq and nums[min_dq[-1]] >= num:\n min_dq.pop()\n min_dq.append(right)\n while nums[max_dq[0]]-nums[min_dq[0]] > limit: # both always exist \"right\" element\n if max_dq[0] == left:\n max_dq.popleft()\n if min_dq[0] == left:\n min_dq.popleft()\n left += 1\n result = max(result, right-left+1)\n return result\n"}} diff --git a/cp/cp-10852.jsonl b/cp/cp-10852.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3e148e7be41566ff3eb76340d30eb0712d267c90 --- /dev/null +++ b/cp/cp-10852.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10852", "name": "LeetCode 1439: Find The Kth Smallest Sum Of A Matrix With Sorted Rows"} +{"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 the Kth Smallest Sum of a Matrix With Sorted Rows (Difficulty: Hard)\nTags: Array, Binary Search, Heap (Priority Queue), Matrix\n\nYou are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k.\nYou are allowed to choose exactly one element from each row to form an array.\nReturn the kth smallest array sum among all possible arrays.\n\nExample 1:\nInput: mat = [[1,3,11],[2,4,6]], k = 5\nOutput: 7\nExplanation: Choosing one element from each row, the first k smallest sum are:\n[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.\n\nExample 2:\nInput: mat = [[1,3,11],[2,4,6]], k = 9\nOutput: 17\n\nExample 3:\nInput: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7\nOutput: 9\nExplanation: Choosing one element from each row, the first k smallest sum are:\n[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.\n\nConstraints:\n- m == mat.length\n- n == mat.length[i]\n- 1 <= m, n <= 40\n- 1 <= mat[i][j] <= 5000\n- 1 <= k <= min(200, nm)\n- mat[i] is a non-decreasing array."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * klogk)\n# Space: O(k)\n\nimport heapq\n\n\nclass Solution(object):\n def kthSmallest(self, mat, k):\n \"\"\"\n :type mat: List[List[int]]\n :type k: int\n :rtype: int\n \"\"\"\n def kSmallestPairs(nums1, nums2, k):\n result, min_heap = [], []\n for c in range(min(len(nums1), k)):\n heapq.heappush(min_heap, (nums1[c]+nums2[0], 0))\n c += 1\n while len(result) != k and min_heap:\n total, c = heapq.heappop(min_heap)\n result.append(total)\n if c+1 == len(nums2):\n continue\n heapq.heappush(min_heap, (total-nums2[c]+nums2[c+1], c+1))\n return result\n\n result = mat[0]\n for r in range(1, len(mat)):\n result = kSmallestPairs(result, mat[r], k)\n return result[k-1]\n\n\n# Time: O((k + m) * log(m * MAX_NUM)) ~ O(k * m * log(m * MAX_NUM))\n# Space: O(m)\nclass Solution2(object):\n def kthSmallest(self, mat, k):\n \"\"\"\n :type mat: List[List[int]]\n :type k: int\n :rtype: int\n \"\"\" \n def countArraysHaveSumLessOrEqual(mat, k, r, target): # Time: O(k + m) ~ O(k * m)\n if target < 0:\n return 0\n if r == len(mat):\n return 1\n result = 0\n for c in range(len(mat[0])):\n cnt = countArraysHaveSumLessOrEqual(mat, k-result, r+1, target-mat[r][c])\n if not cnt:\n break\n result += cnt\n if result > k:\n break\n return result\n \n max_num = max(x for row in mat for x in row)\n left, right = len(mat), len(mat)*max_num\n while left <= right:\n mid = left + (right-left)//2\n cnt = countArraysHaveSumLessOrEqual(mat, k, 0, mid)\n if cnt >= k:\n right = mid-1\n else:\n left = mid+1\n return left\n\n"}} diff --git a/cp/cp-10853.jsonl b/cp/cp-10853.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7f0460cf909c1ba114fa596efd02ea66bf01e61f --- /dev/null +++ b/cp/cp-10853.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10853", "name": "LeetCode 1441: Build An Array With Stack Operations"} +{"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: Build an Array With Stack Operations (Difficulty: Medium)\nTags: Array, Stack, Simulation\n\nYou are given an integer array target and an integer n.\nYou have an empty stack with the two following operations:\nYou also have a stream of the integers in the range [1, n].\nUse the two stack operations to make the numbers in the stack (from the bottom to the top) equal to target. You should follow the following rules:\nReturn the stack operations needed to build target following the mentioned rules. If there are multiple valid answers, return any of them.\n\nExample 1:\nInput: target = [1,3], n = 3\nOutput: [\"Push\",\"Push\",\"Pop\",\"Push\"]\nExplanation: Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nPop the integer on the top of the stack. s = [1].\nRead 3 from the stream and push it to the stack. s = [1,3].\n\nExample 2:\nInput: target = [1,2,3], n = 3\nOutput: [\"Push\",\"Push\",\"Push\"]\nExplanation: Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nRead 3 from the stream and push it to the stack. s = [1,2,3].\n\nExample 3:\nInput: target = [1,2], n = 4\nOutput: [\"Push\",\"Push\"]\nExplanation: Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nSince the stack (from the bottom to the top) is equal to target, we stop the stack operations.\nThe answers that read integer 3 from the stream are not accepted.\n\nConstraints:\n- 1 <= target.length <= 100\n- 1 <= n <= 100\n- 1 <= target[i] <= n\n- target is strictly increasing."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def buildArray(self, target, n):\n \"\"\"\n :type target: List[int]\n :type n: int\n :rtype: List[str]\n \"\"\"\n result, curr = [], 1\n for t in target:\n result.extend([\"Push\", \"Pop\"]*(t-curr))\n result.append(\"Push\")\n curr = t+1\n return result\n"}} diff --git a/cp/cp-10854.jsonl b/cp/cp-10854.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..61d870bc45b04151f8a00c461e86b4748e948efc --- /dev/null +++ b/cp/cp-10854.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10854", "name": "LeetCode 1442: Count Triplets That Can Form Two Arrays Of Equal Xor"} +{"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: Count Triplets That Can Form Two Arrays of Equal XOR (Difficulty: Medium)\nTags: Array, Hash Table, Math, Bit Manipulation, Prefix Sum\n\nGiven an array of integers arr.\nWe want to select three indices i, j and k where (0 <= i < j <= k < arr.length).\nLet's define a and b as follows:\nNote that ^ denotes the bitwise-xor operation.\nReturn the number of triplets (i, j and k) Where a == b.\n\nExample 1:\nInput: arr = [2,3,1,6,7]\nOutput: 4\nExplanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)\n\nExample 2:\nInput: arr = [1,1,1,1,1]\nOutput: 10\n\nConstraints:\n- 1 <= arr.length <= 300\n- 1 <= arr[i] <= 10^8"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def countTriplets(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n count_sum = collections.defaultdict(lambda: [0, 0])\n count_sum[0] = [1, 0]\n result, prefix = 0, 0\n for i, x in enumerate(arr):\n prefix ^= x\n c, t = count_sum[prefix]\n # sum(i-(j+1) for j in index[prefix])\n # = len(index[prefix])*i - sum((j+1) for j in index[prefix])\n result += c*i - t\n count_sum[prefix] = [c+1, t+i+1]\n return result\n"}} diff --git a/cp/cp-10855.jsonl b/cp/cp-10855.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4ffe34b953e80fa6fae617f484eeacb33c4f48e3 --- /dev/null +++ b/cp/cp-10855.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10855", "name": "LeetCode 1443: Minimum Time To Collect All Apples In A 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: Minimum Time to Collect All Apples in a Tree (Difficulty: Medium)\nTags: Hash Table, Tree, Depth-First Search, Breadth-First Search\n\nGiven an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.\nThe edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.\n\nExample 1:\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]\nOutput: 8 \nExplanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.\n\nExample 2:\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]\nOutput: 6\nExplanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.\n\nExample 3:\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]\nOutput: 0\n\nConstraints:\n- 1 <= n <= 10^5\n- edges.length == n - 1\n- edges[i].length == 2\n- 0 <= ai < bi <= n - 1\n- hasApple.length == n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def minTime(self, n, edges, hasApple):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type hasApple: List[bool]\n :rtype: int\n \"\"\"\n graph = collections.defaultdict(list)\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n \n result = [0, 0]\n s = [(1, (-1, 0, result))]\n while s:\n step, params = s.pop()\n if step == 1:\n par, node, ret = params\n ret[:] = [0, int(hasApple[node])]\n for nei in reversed(graph[node]):\n if nei == par:\n continue\n new_ret = [0, 0]\n s.append((2, (new_ret, ret)))\n s.append((1, (node, nei, new_ret)))\n else:\n new_ret, ret = params\n ret[0] += new_ret[0]+new_ret[1]\n ret[1] |= bool(new_ret[0]+new_ret[1])\n return 2*result[0]\n\n\n# Time: O(n)\n# Space: O(n)\nclass Solution_Recu(object):\n def minTime(self, n, edges, hasApple):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type hasApple: List[bool]\n :rtype: int\n \"\"\"\n def dfs(graph, par, node, hasApple):\n result, extra = 0, int(hasApple[node])\n for nei in graph[node]:\n if nei == par:\n continue\n count, found = dfs(graph, node, nei, hasApple)\n result += count+found\n extra |= bool(count+found)\n return result, extra\n \n graph = collections.defaultdict(list)\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n return 2*dfs(graph, -1, 0, hasApple)[0]\n\n\n# Time: O(n)\n# Space: O(n)\nclass Solution2(object):\n def minTime(self, n, edges, hasApple):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type hasApple: List[bool]\n :rtype: int\n \"\"\"\n graph = collections.defaultdict(list)\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n \n result = [0]\n s = [(1, (-1, 0, result))]\n while s:\n step, params = s.pop()\n if step == 1:\n par, node, ret = params\n tmp = [int(hasApple[node])]\n s.append((3, (tmp, ret)))\n for nei in reversed(graph[node]):\n if nei == par:\n continue\n new_ret = [0]\n s.append((2, (new_ret, tmp, ret)))\n s.append((1, (node, nei, new_ret)))\n elif step == 2:\n new_ret, tmp, ret = params\n ret[0] += new_ret[0]\n tmp[0] |= bool(new_ret[0])\n else:\n tmp, ret = params\n ret[0] += tmp[0]\n return 2*max(result[0]-1, 0)\n\n\n# Time: O(n)\n# Space: O(n)\nclass Solution2_Recu(object):\n def minTime(self, n, edges, hasApple):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type hasApple: List[bool]\n :rtype: int\n \"\"\"\n def dfs(graph, par, node, has_subtree):\n result, extra = 0, int(hasApple[node])\n for nei in graph[node]:\n if nei == par:\n continue\n count = dfs(graph, node, nei, hasApple)\n result += count\n extra |= bool(count)\n return result+extra\n \n graph = collections.defaultdict(list)\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n return 2*max(dfs(graph, -1, 0, hasApple)-1, 0)\n"}} diff --git a/cp/cp-10856.jsonl b/cp/cp-10856.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd5ecd3a2f208aa8e1593ea647094913a2430eca --- /dev/null +++ b/cp/cp-10856.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10856", "name": "LeetCode 1444: Number Of Ways Of Cutting A Pizza"} +{"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 Ways of Cutting a Pizza (Difficulty: Hard)\nTags: Array, Dynamic Programming, Memoization, Matrix, Prefix Sum\n\nGiven a rectangular pizza represented as a rows x cols matrix containing the following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts.\nFor each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.\nReturn the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.\n\nExample 1:\nInput: pizza = [\"A..\",\"AAA\",\"...\"], k = 3\nOutput: 3 \nExplanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.\n\nExample 2:\nInput: pizza = [\"A..\",\"AA.\",\"...\"], k = 3\nOutput: 1\n\nExample 3:\nInput: pizza = [\"A..\",\"A..\",\"...\"], k = 1\nOutput: 1\n\nConstraints:\n- 1 <= rows, cols <= 50\n- rows == pizza.length\n- cols == pizza[i].length\n- 1 <= k <= 10\n- pizza consists of characters 'A' and '.' only."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n * k * (m + n))\n# Space: O(m * n * k)\n\nclass Solution(object):\n def ways(self, pizza, k):\n \"\"\"\n :type pizza: List[str]\n :type k: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n prefix = [[0]*len(pizza[0]) for _ in range(len(pizza))]\n for j in reversed(range(len(pizza[0]))):\n accu = 0\n for i in reversed(range(len(pizza))):\n accu += int(pizza[i][j] == 'A')\n prefix[i][j] = (prefix[i][j+1] if (j+1 < len(pizza[0])) else 0) + accu\n dp = [[[0]*k for _ in range(len(pizza[0]))] for _ in range(len(pizza))]\n for i in reversed(range(len(pizza))):\n for j in reversed(range(len(pizza[0]))):\n dp[i][j][0] = 1\n for m in range(1, k):\n for n in range(i+1, len(pizza)):\n if prefix[i][j] == prefix[n][j]:\n continue\n if prefix[n][j] == 0:\n break\n dp[i][j][m] = (dp[i][j][m] + dp[n][j][m-1]) % MOD\n for n in range(j+1, len(pizza[0])):\n if prefix[i][j] == prefix[i][n]:\n continue\n if prefix[i][n] == 0:\n break\n dp[i][j][m] = (dp[i][j][m] + dp[i][n][m-1]) % MOD\n return dp[0][0][k-1]\n"}} diff --git a/cp/cp-10857.jsonl b/cp/cp-10857.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a508b6806c9c461c15250b8988b89abf0612d678 --- /dev/null +++ b/cp/cp-10857.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10857", "name": "LeetCode 1446: Consecutive Characters"} +{"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: Consecutive Characters (Difficulty: Easy)\nTags: String\n\nThe power of the string is the maximum length of a non-empty substring that contains only one unique character.\nGiven a string s, return the power of s.\n\nExample 1:\nInput: s = \"leetcode\"\nOutput: 2\nExplanation: The substring \"ee\" is of length 2 with the character 'e' only.\n\nExample 2:\nInput: s = \"abbcccddddeeeeedcba\"\nOutput: 5\nExplanation: The substring \"eeeee\" is of length 5 with the character 'e' only.\n\nConstraints:\n- 1 <= s.length <= 500\n- s consists of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxPower(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result, count = 1, 1\n for i in range(1, len(s)):\n if s[i] == s[i-1]:\n count += 1\n else:\n count = 1\n result = max(result, count)\n return result\n\n\n# Time: O(n)\n# Space: O(n)\nimport itertools\n\n\nclass Solution2(object):\n def maxPower(self, s):\n return max(len(list(v)) for _, v in itertools.groupby(s))\n"}} diff --git a/cp/cp-10858.jsonl b/cp/cp-10858.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..841ce413c5b91959632047be59ab02b91ad816e4 --- /dev/null +++ b/cp/cp-10858.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10858", "name": "LeetCode 1447: Simplified Fractions"} +{"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: Simplified Fractions (Difficulty: Medium)\nTags: Math, String, Number Theory\n\nGiven an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order.\n\nExample 1:\nInput: n = 2\nOutput: [\"1/2\"]\nExplanation: \"1/2\" is the only unique fraction with a denominator less-than-or-equal-to 2.\n\nExample 2:\nInput: n = 3\nOutput: [\"1/2\",\"1/3\",\"2/3\"]\n\nExample 3:\nInput: n = 4\nOutput: [\"1/2\",\"1/3\",\"1/4\",\"2/3\",\"3/4\"]\nExplanation: \"2/4\" is not a simplified fraction because it can be simplified to \"1/2\".\n\nConstraints:\n- 1 <= n <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2 * logn)\n# Space: O(n^2)\n\nimport fractions\n\nclass Solution(object):\n def simplifiedFractions(self, n):\n \"\"\"\n :type n: int\n :rtype: List[str]\n \"\"\"\n lookup = set()\n for b in range(1, n+1):\n for a in range(1, b):\n g = fractions.gcd(a, b)\n lookup.add((a//g, b//g))\n return map(lambda x: \"{}/{}\".format(*x), lookup)\n"}} diff --git a/cp/cp-10859.jsonl b/cp/cp-10859.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6ffa7a3e849c75f5aba781ed660585d0ca9a9eed --- /dev/null +++ b/cp/cp-10859.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10859", "name": "LeetCode 1448: Count Good Nodes 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: Count Good Nodes in Binary Tree (Difficulty: Medium)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.\nReturn the number of good nodes in the binary tree.\n\nExample 1:\nInput: root = [3,1,4,3,null,1,5]\r\nOutput: 4\r\nExplanation: Nodes in blue are good.\r\nRoot Node (3) is always a good node.\r\nNode 4 -> (3,4) is the maximum value in the path starting from the root.\r\nNode 5 -> (3,4,5) is the maximum value in the path\r\nNode 3 -> (3,1,3) is the maximum value in the path.\n\nExample 2:\nInput: root = [3,3,null,4,2]\r\nOutput: 3\r\nExplanation: Node 2 -> (3, 3, 2) is not good, because \"3\" is higher than it.\n\nExample 3:\nInput: root = [1]\r\nOutput: 1\r\nExplanation: Root is considered as good.\n\nConstraints:\n- The number of nodes in the binary tree is in the range [1, 10^5].\n- Each node's value is between [-10^4, 10^4]."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution(object):\n def goodNodes(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n result = 0\n stk = [(root, root.val)]\n while stk:\n node, curr_max = stk.pop()\n if not node:\n continue\n curr_max = max(curr_max, node.val)\n result += int(curr_max <= node.val)\n stk.append((node.right, curr_max))\n stk.append((node.left, curr_max))\n return result\n\n\n# Time: O(n)\n# Space: O(h)\nclass Solution2(object):\n def goodNodes(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def dfs(node, curr_max):\n if not node:\n return 0\n curr_max = max(curr_max, node.val)\n return (int(curr_max <= node.val) +\n dfs(node.left, curr_max) + dfs(node.right, curr_max))\n \n return dfs(root, root.val)\n"}} diff --git a/cp/cp-10860.jsonl b/cp/cp-10860.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..834ecdc6b2698fca86b54df0669ed7aa5fc66a1a --- /dev/null +++ b/cp/cp-10860.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10860", "name": "LeetCode 1449: Form Largest Integer With Digits That Add Up To Target"} +{"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: Form Largest Integer With Digits That Add up to Target (Difficulty: Hard)\nTags: Array, Dynamic Programming\n\nGiven an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:\nSince the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return \"0\".\n\nExample 1:\nInput: cost = [4,3,2,5,6,7,2,5,5], target = 9\nOutput: \"7772\"\nExplanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost(\"7772\") = 2*3+ 3*1 = 9. You could also paint \"977\", but \"7772\" is the largest number.\nDigit cost\n 1 -> 4\n 2 -> 3\n 3 -> 2\n 4 -> 5\n 5 -> 6\n 6 -> 7\n 7 -> 2\n 8 -> 5\n 9 -> 5\n\nExample 2:\nInput: cost = [7,6,5,5,5,6,8,7,8], target = 12\nOutput: \"85\"\nExplanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost(\"85\") = 7 + 5 = 12.\n\nExample 3:\nInput: cost = [2,4,6,2,4,6,4,4,4], target = 5\nOutput: \"0\"\nExplanation: It is impossible to paint any integer with total cost equal to target.\n\nConstraints:\n- cost.length == 9\n- 1 <= cost[i], target <= 5000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(t)\n# Space: O(t)\n\nclass Solution(object):\n def largestNumber(self, cost, target):\n \"\"\"\n :type cost: List[int]\n :type target: int\n :rtype: str\n \"\"\"\n dp = [0]\n for t in range(1, target+1):\n dp.append(-1)\n for i, c in enumerate(cost):\n if t-c < 0 or dp[t-c] < 0:\n continue\n dp[t] = max(dp[t], dp[t-c]+1)\n if dp[target] < 0:\n return \"0\"\n result = []\n for i in reversed(range(9)):\n while target >= cost[i] and dp[target] == dp[target-cost[i]]+1:\n target -= cost[i]\n result.append(i+1)\n return \"\".join(map(str, result))\n\n\n# Time: O(t)\n# Space: O(t)\nclass Solution2(object):\n def largestNumber(self, cost, target):\n \"\"\"\n :type cost: List[int]\n :type target: int\n :rtype: str\n \"\"\"\n def key(bag):\n return sum(bag), bag\n \n dp = [[0]*9]\n for t in range(1, target+1):\n dp.append([])\n for d, c in enumerate(cost):\n if t < c or not dp[t-c]:\n continue\n curr = dp[t-c][:]\n curr[~d] += 1\n if key(curr) > key(dp[t]):\n dp[-1] = curr \n if not dp[-1]:\n return \"0\"\n return \"\".join(str(9-i)*c for i, c in enumerate(dp[-1]))\n\n\n# Time: O(t^2)\n# Space: O(t^2)\nclass Solution3(object):\n def largestNumber(self, cost, target):\n \"\"\"\n :type cost: List[int]\n :type target: int\n :rtype: str\n \"\"\"\n dp = [0]\n for t in range(1, target+1):\n dp.append(-1)\n for i, c in enumerate(cost):\n if t-c < 0:\n continue\n dp[t] = max(dp[t], dp[t-c]*10 + i+1)\n return str(max(dp[t], 0))\n"}} diff --git a/cp/cp-10861.jsonl b/cp/cp-10861.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8c5b9e368772b2bc0dcc54951d25baf60f196008 --- /dev/null +++ b/cp/cp-10861.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10861", "name": "LeetCode 1450: Number Of Students Doing Homework At A Given Time"} +{"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 Students Doing Homework at a Given Time (Difficulty: Easy)\nTags: Array\n\nGiven two integer arrays startTime and endTime and given an integer queryTime.\nThe ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].\nReturn the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.\n\nExample 1:\nInput: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4\nOutput: 1\nExplanation: We have 3 students where:\nThe first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.\nThe second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.\nThe third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.\n\nExample 2:\nInput: startTime = [4], endTime = [4], queryTime = 4\nOutput: 1\nExplanation: The only student was doing their homework at the queryTime.\n\nConstraints:\n- startTime.length == endTime.length\n- 1 <= startTime.length <= 100\n- 1 <= startTime[i] <= endTime[i] <= 1000\n- 1 <= queryTime <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def busyStudent(self, startTime, endTime, queryTime):\n \"\"\"\n :type startTime: List[int]\n :type endTime: List[int]\n :type queryTime: int\n :rtype: int\n \"\"\"\n return sum(s <= queryTime <= e for s, e in itertools.izip(startTime, endTime))\n"}} diff --git a/cp/cp-10862.jsonl b/cp/cp-10862.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fbb4de2154bbdf298eea28b6c3e2be55408e591a --- /dev/null +++ b/cp/cp-10862.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10862", "name": "LeetCode 1451: Rearrange Words In A Sentence"} +{"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: Rearrange Words in a Sentence (Difficulty: Medium)\nTags: String, Sorting\n\nGiven a sentence text (A sentence is a string of space-separated words) in the following format:\nYour task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.\nReturn the new text following the format shown above.\n\nExample 1:\nInput: text = \"Leetcode is cool\"\nOutput: \"Is cool leetcode\"\nExplanation: There are 3 words, \"Leetcode\" of length 8, \"is\" of length 2 and \"cool\" of length 4.\nOutput is ordered by length and the new first word starts with capital letter.\n\nExample 2:\nInput: text = \"Keep calm and code on\"\nOutput: \"On and keep calm code\"\nExplanation: Output is ordered as follows:\n\"On\" 2 letters.\n\"and\" 3 letters.\n\"keep\" 4 letters in case of tie order by position in original text.\n\"calm\" 4 letters.\n\"code\" 4 letters.\n\nExample 3:\nInput: text = \"To be or not to be\"\nOutput: \"To be or to be not\"\n\nConstraints:\n- text begins with a capital letter and then contains lowercase letters and single space between words.\n- 1 <= text.length <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass Solution(object):\n def arrangeWords(self, text):\n \"\"\"\n :type text: str\n :rtype: str\n \"\"\"\n result = text.split()\n result[0] = result[0].lower()\n result.sort(key=len) \n result[0] = result[0].title()\n return \" \".join(result)\n"}} diff --git a/cp/cp-10863.jsonl b/cp/cp-10863.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..36d58520e64a3c610f833b01ec6c1f9a6f9cb714 --- /dev/null +++ b/cp/cp-10863.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10863", "name": "LeetCode 1452: People Whose List Of Favorite Companies Is Not A Subset Of Another List"} +{"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: People Whose List of Favorite Companies Is Not a Subset of Another List (Difficulty: Medium)\nTags: Array, Hash Table, String\n\nGiven the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).\nReturn the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.\n\nExample 1:\nInput: favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"google\",\"microsoft\"],[\"google\",\"facebook\"],[\"google\"],[\"amazon\"]]\nOutput: [0,1,4] \nExplanation: \nPerson with index=2 has favoriteCompanies[2]=[\"google\",\"facebook\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] corresponding to the person with index 0. \nPerson with index=3 has favoriteCompanies[3]=[\"google\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] and favoriteCompanies[1]=[\"google\",\"microsoft\"]. \nOther lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].\n\nExample 2:\nInput: favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"leetcode\",\"amazon\"],[\"facebook\",\"google\"]]\nOutput: [0,1] \nExplanation: In this case favoriteCompanies[2]=[\"facebook\",\"google\"] is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"], therefore, the answer is [0,1].\n\nExample 3:\nInput: favoriteCompanies = [[\"leetcode\"],[\"google\"],[\"facebook\"],[\"amazon\"]]\nOutput: [0,1,2,3]\n\nConstraints:\n- 1 <= favoriteCompanies.length <= 100\n- 1 <= favoriteCompanies[i].length <= 500\n- 1 <= favoriteCompanies[i][j].length <= 20\n- All strings in favoriteCompanies[i] are distinct.\n- All lists of favorite companies are distinct, that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].\n- All strings consist of lowercase English letters only."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * m * l + n^2 * m), n is favoriteCompanies.length\n# , m is the max of favoriteCompanies[i].length\n# , l is the max of favoriteCompanies[i][j].length\n# Space: O(n * m * l)\n\nclass Solution(object):\n def peopleIndexes(self, favoriteCompanies):\n \"\"\"\n :type favoriteCompanies: List[List[str]]\n :rtype: List[int]\n \"\"\"\n lookup, comps = {}, []\n for cs in favoriteCompanies:\n comps.append(set())\n for c in cs:\n if c not in lookup:\n lookup[c] = len(lookup)\n comps[-1].add(lookup[c])\n return [i for i, c1 in enumerate(comps)\n if not any(i != j and len(c1) < len(c2) and c1 < c2\n for j, c2 in enumerate(comps))]\n \n\n\n# Time: O(n * m * l + n^2 * m * log*(n)), n is favoriteCompanies.length\n# , m is the max of favoriteCompanies[i].length\n# , l is the max of favoriteCompanies[i][j].length\n# Space: O(n * m * l)\nclass UnionFind(object):\n def __init__(self, data):\n self.data = [set(d) for d in data]\n self.set = range(len(data))\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return\n if len(self.data[x_root]) > len(self.data[y_root]) and \\\n self.data[x_root] > self.data[y_root]:\n self.set[y_root] = x_root\n elif len(self.data[x_root]) < len(self.data[y_root]) and \\\n self.data[x_root] < self.data[y_root]:\n self.set[x_root] = y_root\n\n\nclass Solution2(object):\n def peopleIndexes(self, favoriteCompanies):\n \"\"\"\n :type favoriteCompanies: List[List[str]]\n :rtype: List[int]\n \"\"\"\n lookup, comps = {}, []\n for cs in favoriteCompanies:\n comps.append(set())\n for c in cs:\n if c not in lookup:\n lookup[c] = len(lookup)\n comps[-1].add(lookup[c])\n union_find = UnionFind(comps)\n for i in range(len(comps)):\n for j in range(len(comps)):\n if j == i:\n continue\n union_find.union_set(i, j)\n return [x for i, x in enumerate(union_find.set) if x == i]\n"}} diff --git a/cp/cp-10864.jsonl b/cp/cp-10864.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ea07a94b2096888d5410dcf99fc86ad4f7d7d700 --- /dev/null +++ b/cp/cp-10864.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10864", "name": "LeetCode 1453: Maximum Number Of Darts Inside Of A Circular Dartboard"} +{"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 Number of Darts Inside of a Circular Dartboard (Difficulty: Hard)\nTags: Array, Math, Geometry\n\nAlice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall.\nBob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Alice throws lie on the dartboard.\nGiven the integer r, return the maximum number of darts that can lie on the dartboard.\n\nExample 1:\nInput: darts = [[-2,0],[2,0],[0,2],[0,-2]], r = 2\nOutput: 4\nExplanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.\n\nExample 2:\nInput: darts = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5\nOutput: 5\nExplanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).\n\nConstraints:\n- 1 <= darts.length <= 100\n- darts[i].length == 2\n- -10^4 <= xi, yi <= 10^4\n- All the darts are unique\n- 1 <= r <= 5000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2 * logn)\n# Space: O(n)\n\nimport math\n\n\n# angle sweep solution\n# great explanation:\n# https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/discuss/636345/Python-O(n3)-and-O(n2logn)-solution-explained-in-detail-with-pictures\nclass Solution(object):\n def numPoints(self, points, r):\n \"\"\"\n :type points: List[List[int]]\n :type r: int\n :rtype: int\n \"\"\"\n def count_points(points, r, i):\n angles = []\n for j in range(len(points)):\n if i == j:\n continue\n dx, dy = points[i][0]-points[j][0], points[i][1]-points[j][1]\n d = math.sqrt(dx**2 + dy**2)\n if d > 2*r:\n continue\n delta, angle = math.acos(d/(2*r)), math.atan2(dy, dx)\n angles.append((angle-delta, 0)), angles.append((angle+delta, 1))\n angles.sort()\n result, count = 1, 1\n for _, is_closed in angles: # angle sweep\n if not is_closed:\n count += 1\n else:\n count -= 1\n result = max(result, count)\n return result\n\n return max(count_points(points, r, i) for i in range(len(points)))\n"}} diff --git a/cp/cp-10865.jsonl b/cp/cp-10865.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c6fd45bff55d1686d63d92c6b4c743d336b08b6c --- /dev/null +++ b/cp/cp-10865.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10865", "name": "LeetCode 1455: Check If A Word Occurs As A Prefix Of Any Word In A Sentence"} +{"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: Check If a Word Occurs As a Prefix of Any Word in a Sentence (Difficulty: Easy)\nTags: Two Pointers, String, String Matching\n\nGiven a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence.\nReturn the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.\nA prefix of a string s is any leading contiguous substring of s.\n\nExample 1:\nInput: sentence = \"i love eating burger\", searchWord = \"burg\"\nOutput: 4\nExplanation: \"burg\" is prefix of \"burger\" which is the 4th word in the sentence.\n\nExample 2:\nInput: sentence = \"this problem is an easy problem\", searchWord = \"pro\"\nOutput: 2\nExplanation: \"pro\" is prefix of \"problem\" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.\n\nExample 3:\nInput: sentence = \"i am tired\", searchWord = \"you\"\nOutput: -1\nExplanation: \"you\" is not a prefix of any word in the sentence.\n\nConstraints:\n- 1 <= sentence.length <= 100\n- 1 <= searchWord.length <= 10\n- sentence consists of lowercase English letters and spaces.\n- searchWord consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def isPrefixOfWord(self, sentence, searchWord):\n \"\"\"\n :type sentence: str\n :type searchWord: str\n :rtype: int\n \"\"\"\n def KMP(text, pattern):\n def getPrefix(pattern):\n prefix = [-1] * len(pattern)\n j = -1\n for i in range(1, len(pattern)):\n while j > -1 and pattern[j + 1] != pattern[i]:\n j = prefix[j]\n if pattern[j + 1] == pattern[i]:\n j += 1\n prefix[i] = j\n return prefix\n \n prefix = getPrefix(pattern)\n j = -1\n for i in range(len(text)):\n while j != -1 and pattern[j+1] != text[i]:\n j = prefix[j]\n if pattern[j+1] == text[i]:\n j += 1\n if j+1 == len(pattern):\n return i-j\n return -1\n \n if sentence.startswith(searchWord):\n return 1\n p = KMP(sentence, ' ' + searchWord)\n if p == -1:\n return -1\n return 1+sum(sentence[i] == ' ' for i in range(p+1))\n"}} diff --git a/cp/cp-10866.jsonl b/cp/cp-10866.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e2d0b8bafd905110f7cfe929c4d7f8c5581b6f69 --- /dev/null +++ b/cp/cp-10866.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10866", "name": "LeetCode 1456: Maximum Number Of Vowels In A Substring Of Given Length"} +{"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 Number of Vowels in a Substring of Given Length (Difficulty: Medium)\nTags: String, Sliding Window\n\nGiven a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.\nVowel letters in English are 'a', 'e', 'i', 'o', and 'u'.\n\nExample 1:\nInput: s = \"abciiidef\", k = 3\nOutput: 3\nExplanation: The substring \"iii\" contains 3 vowel letters.\n\nExample 2:\nInput: s = \"aeiou\", k = 2\nOutput: 2\nExplanation: Any substring of length 2 contains 2 vowels.\n\nExample 3:\nInput: s = \"leetcode\", k = 3\nOutput: 2\nExplanation: \"lee\", \"eet\" and \"ode\" contain 2 vowels.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s consists of lowercase English letters.\n- 1 <= k <= s.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxVowels(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: int\n \"\"\"\n VOWELS = set(\"aeiou\")\n result = curr = 0\n for i, c in enumerate(s):\n curr += c in VOWELS\n if i >= k:\n curr -= s[i-k] in VOWELS\n result = max(result, curr)\n return result\n"}} diff --git a/cp/cp-10867.jsonl b/cp/cp-10867.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6c44fc38f0840f829dfc2e390d2c561f8e47e0d3 --- /dev/null +++ b/cp/cp-10867.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10867", "name": "LeetCode 1457: Pseudo Palindromic Paths 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: Pseudo-Palindromic Paths in a Binary Tree (Difficulty: Medium)\nTags: Bit Manipulation, Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.\nReturn the number of pseudo-palindromic paths going from the root node to leaf nodes.\n\nExample 1:\nInput: root = [2,3,1,3,1,null,1]\nOutput: 2 \nExplanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).\n\nExample 2:\nInput: root = [2,1,1,1,3,null,null,null,null,null,1]\nOutput: 1 \nExplanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).\n\nExample 3:\nInput: root = [9]\nOutput: 1\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 105].\n- 1 <= Node.val <= 9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution(object):\n def pseudoPalindromicPaths (self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n result = 0\n stk = [(root, 0)]\n while stk:\n node, count = stk.pop()\n if not node:\n continue\n count ^= 1 << (node.val-1)\n result += int(node.left == node.right and count&(count-1) == 0)\n stk.append((node.right, count))\n stk.append((node.left, count))\n return result\n \n\n# Time: O(n)\n# Space: O(h)\nclass Solution2(object):\n def pseudoPalindromicPaths (self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def dfs(node, count):\n if not root:\n return 0\n count ^= 1 << (node.val-1)\n return int(node.left == node.right and count&(count-1) == 0) + \\\n dfs(node.left, count) + dfs(node.right, count)\n return dfs(root, 0)\n"}} diff --git a/cp/cp-10868.jsonl b/cp/cp-10868.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..130c89aec7d6429d9620a6935b73d868f8c8b5d1 --- /dev/null +++ b/cp/cp-10868.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10868", "name": "LeetCode 1458: Max Dot Product Of Two 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: Max Dot Product of Two Subsequences (Difficulty: Hard)\nTags: Array, Dynamic Programming\n\nGiven two arrays nums1 and nums2.\nReturn the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.\nA subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).\n\nExample 1:\nInput: nums1 = [2,1,-2,5], nums2 = [3,0,-6]\nOutput: 18\nExplanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\nTheir dot product is (2*3 + (-2)*(-6)) = 18.\n\nExample 2:\nInput: nums1 = [3,-2], nums2 = [2,-6,7]\nOutput: 21\nExplanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.\nTheir dot product is (3*7) = 21.\n\nExample 3:\nInput: nums1 = [-1,-1], nums2 = [1,1]\nOutput: -1\nExplanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.\nTheir dot product is -1.\n\nConstraints:\n- 1 <= nums1.length, nums2.length <= 500\n- -1000 <= nums1[i], nums2[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(min(m, n))\n\nclass Solution(object):\n def maxDotProduct(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: int\n \"\"\"\n if len(nums1) < len(nums2):\n return self.maxDotProduct(nums2, nums1)\n dp = [[0]*len(nums2) for i in range(2)]\n for i in range(len(nums1)):\n for j in range(len(nums2)):\n dp[i%2][j] = nums1[i]*nums2[j]\n if i and j:\n dp[i%2][j] += max(dp[(i-1)%2][j-1], 0)\n if i:\n dp[i%2][j] = max(dp[i%2][j], dp[(i-1)%2][j])\n if j:\n dp[i%2][j] = max(dp[i%2][j], dp[i%2][j-1])\n return dp[(len(nums1)-1)%2][-1]\n"}} diff --git a/cp/cp-10869.jsonl b/cp/cp-10869.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4346674b4dbc829364e9a4561bb9d8849dc05f69 --- /dev/null +++ b/cp/cp-10869.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10869", "name": "LeetCode 1460: Make Two Arrays Equal By Reversing Sub 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: Make Two Arrays Equal by Reversing Subarrays (Difficulty: Easy)\nTags: Array, Hash Table, Sorting\n\nYou are given two integer arrays of equal length target and arr. In one step, you can select any non-empty subarray of arr and reverse it. You are allowed to make any number of steps.\nReturn true if you can make arr equal to target or false otherwise.\n\nExample 1:\nInput: target = [1,2,3,4], arr = [2,4,1,3]\nOutput: true\nExplanation: You can follow the next steps to convert arr to target:\n1- Reverse subarray [2,4,1], arr becomes [1,4,2,3]\n2- Reverse subarray [4,2], arr becomes [1,2,4,3]\n3- Reverse subarray [4,3], arr becomes [1,2,3,4]\nThere are multiple ways to convert arr to target, this is not the only way to do so.\n\nExample 2:\nInput: target = [7], arr = [7]\nOutput: true\nExplanation: arr is equal to target without any reverses.\n\nExample 3:\nInput: target = [3,7,9], arr = [3,7,11]\nOutput: false\nExplanation: arr does not have value 9 and it can never be converted to target.\n\nConstraints:\n- target.length == arr.length\n- 1 <= target.length <= 1000\n- 1 <= target[i] <= 1000\n- 1 <= arr[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def canBeEqual(self, target, arr):\n \"\"\"\n :type target: List[int]\n :type arr: List[int]\n :rtype: bool\n \"\"\"\n return collections.Counter(target) == collections.Counter(arr)\n\n\n# Time: O(nlogn)\n# Space: O(1)\nclass Solution2(object):\n def canBeEqual(self, target, arr):\n \"\"\"\n :type target: List[int]\n :type arr: List[int]\n :rtype: bool\n \"\"\"\n target.sort(), arr.sort()\n return target == arr\n"}} diff --git a/cp/cp-10870.jsonl b/cp/cp-10870.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..19fc6976e5c4511e68768503d2ccc436c4346021 --- /dev/null +++ b/cp/cp-10870.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10870", "name": "LeetCode 1461: Check If A String Contains All Binary Codes Of Size K"} +{"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: Check If a String Contains All Binary Codes of Size K (Difficulty: Medium)\nTags: Hash Table, String, Bit Manipulation, Rolling Hash, Hash Function\n\nGiven a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.\n\nExample 1:\nInput: s = \"00110110\", k = 2\nOutput: true\nExplanation: The binary codes of length 2 are \"00\", \"01\", \"10\" and \"11\". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.\n\nExample 2:\nInput: s = \"0110\", k = 1\nOutput: true\nExplanation: The binary codes of length 1 are \"0\" and \"1\", it is clear that both exist as a substring.\n\nExample 3:\nInput: s = \"0110\", k = 2\nOutput: false\nExplanation: The binary code \"00\" is of length 2 and does not exist in the array.\n\nConstraints:\n- 1 <= s.length <= 5 * 10^5\n- s[i] is either '0' or '1'.\n- 1 <= k <= 20"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * k)\n# Space: O(k * 2^k)\n\nclass Solution(object):\n def hasAllCodes(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: bool\n \"\"\"\n return 2**k <= len(s) and len({s[i:i+k] for i in range(len(s)-k+1)}) == 2**k\n \n\n# Time: O(n * k)\n# Space: O(2^k)\nclass Solution2(object):\n def hasAllCodes(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: bool\n \"\"\"\n lookup = set()\n base = 2**k\n if base > len(s):\n return False\n num = 0\n for i in range(len(s)):\n num = (num << 1) + (s[i] == '1')\n if i >= k-1:\n lookup.add(num)\n num -= (s[i-k+1] == '1') * (base//2)\n return len(lookup) == base\n"}} diff --git a/cp/cp-10871.jsonl b/cp/cp-10871.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fd30fefa528923382473a193c6504c12a7c1b4f6 --- /dev/null +++ b/cp/cp-10871.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10871", "name": "LeetCode 1462: Course Schedule Iv"} +{"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 IV (Difficulty: Medium)\nTags: Depth-First Search, Breadth-First Search, Graph, Topological Sort\n\nThere are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi.\nPrerequisites can also be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c.\nYou are also given an array queries where queries[j] = [uj, vj]. For the jth query, you should answer whether course uj is a prerequisite of course vj or not.\nReturn a boolean array answer, where answer[j] is the answer to the jth query.\n\nExample 1:\nInput: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]\nOutput: [false,true]\nExplanation: The pair [1, 0] indicates that you have to take course 1 before you can take course 0.\nCourse 0 is not a prerequisite of course 1, but the opposite is true.\n\nExample 2:\nInput: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]\nOutput: [false,false]\nExplanation: There are no prerequisites, and each course is independent.\n\nExample 3:\nInput: numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]\nOutput: [true,true]\n\nConstraints:\n- 2 <= numCourses <= 100\n- 0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)\n- prerequisites[i].length == 2\n- 0 <= ai, bi <= numCourses - 1\n- ai != bi\n- All the pairs [ai, bi] are unique.\n- The prerequisites graph has no cycles.\n- 1 <= queries.length <= 10^4\n- 0 <= ui, vi <= numCourses - 1\n- ui != vi"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(n^2)\n\nclass Solution(object):\n def checkIfPrerequisite(self, n, prerequisites, queries):\n \"\"\"\n :type n: int\n :type prerequisites: List[List[int]]\n :type queries: List[List[int]]\n :rtype: List[bool]\n \"\"\"\n def floydWarshall(n, graph): \n reachable = set(map(lambda x: x[0]*n+x[1], graph)) \n for k in range(n): \n for i in range(n): \n for j in range(n): \n if i*n+j not in reachable and (i*n+k in reachable and k*n+j in reachable):\n reachable.add(i*n+j)\n return reachable\n\n reachable = floydWarshall(n, prerequisites)\n return [i*n+j in reachable for i, j in queries]\n\n\n# Time: O(n * q)\n# Space: O(p + n)\nimport collections\n\n\nclass Solution2(object):\n def checkIfPrerequisite(self, n, prerequisites, queries):\n \"\"\"\n :type n: int\n :type prerequisites: List[List[int]]\n :type queries: List[List[int]]\n :rtyp\n \"\"\"\n graph = collections.defaultdict(list)\n for u, v in prerequisites:\n graph[u].append(v)\n result = []\n for i, j in queries:\n stk, lookup = [i], set([i])\n while stk:\n node = stk.pop()\n for nei in graph[node]:\n if nei in lookup:\n continue\n stk.append(nei)\n lookup.add(nei)\n result.append(j in lookup)\n return result\n"}} diff --git a/cp/cp-10872.jsonl b/cp/cp-10872.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8c1c31a852f4a2f973c820fb5aa4fc56a3cbe8ae --- /dev/null +++ b/cp/cp-10872.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10872", "name": "LeetCode 1463: Cherry Pickup 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: Cherry Pickup II (Difficulty: Hard)\nTags: Array, Dynamic Programming, Matrix\n\nYou are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell.\nYou have two robots that can collect cherries for you:\nReturn the maximum number of cherries collection using both robots by following the rules below:\n\nExample 1:\nInput: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]\nOutput: 24\nExplanation: Path of robot #1 and #2 are described in color green and blue respectively.\nCherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.\nCherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.\nTotal of cherries: 12 + 12 = 24.\n\nExample 2:\nInput: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]\nOutput: 28\nExplanation: Path of robot #1 and #2 are described in color green and blue respectively.\nCherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.\nCherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.\nTotal of cherries: 17 + 11 = 28.\n\nConstraints:\n- rows == grid.length\n- cols == grid[i].length\n- 2 <= rows, cols <= 70\n- 0 <= grid[i][j] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n^2)\n# Space: O(n^2)\n\nimport itertools\n\n\nclass Solution(object):\n def cherryPickup(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n dp = [[[float(\"-inf\")]*(len(grid[0])+2) for _ in range(len(grid[0])+2)] for _ in range(2)]\n dp[0][1][len(grid[0])] = grid[0][0] + grid[0][len(grid[0])-1]\n for i in range(1, len(grid)):\n for j in range(1, len(grid[0])+1):\n for k in range(1, len(grid[0])+1):\n dp[i%2][j][k] = max(dp[(i-1)%2][j+d1][k+d2] for d1 in range(-1, 2) for d2 in range(-1, 2)) + \\\n ((grid[i][j-1]+grid[i][k-1]) if j != k else grid[i][j-1])\n return max(itertools.imap(max, *dp[(len(grid)-1)%2]))\n\n\n# Time: O(m * n^2)\n# Space: O(n^2)\nimport itertools\n\n\nclass Solution2(object):\n def cherryPickup(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n dp = [[[float(\"-inf\")]*len(grid[0]) for _ in range(len(grid[0]))] for _ in range(2)]\n dp[0][0][len(grid[0])-1] = grid[0][0] + grid[0][len(grid[0])-1]\n for i in range(1, len(grid)):\n for j in range(len(grid[0])):\n for k in range(len(grid[0])):\n dp[i%2][j][k] = max(dp[(i-1)%2][j+d1][k+d2] for d1 in range(-1, 2) for d2 in range(-1, 2)\n if 0 <= j+d1 < len(grid[0]) and 0 <= k+d2 < len(grid[0])) + \\\n ((grid[i][j]+grid[i][k]) if j != k else grid[i][j])\n return max(itertools.imap(max, *dp[(len(grid)-1)%2]))\n"}} diff --git a/cp/cp-10873.jsonl b/cp/cp-10873.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..20867ed861445ae799464be26683a31b02ef6373 --- /dev/null +++ b/cp/cp-10873.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10873", "name": "LeetCode 1464: Maximum Product Of Two Elements In An 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: Maximum Product of Two Elements in an Array (Difficulty: Easy)\nTags: Array, Sorting, Heap (Priority Queue)\n\nExample 1:\nInput: nums = [3,4,5,2]\nOutput: 12 \nExplanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.\n\nExample 2:\nInput: nums = [1,5,4,5]\nOutput: 16\nExplanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.\n\nExample 3:\nInput: nums = [3,7]\nOutput: 12\n\nConstraints:\n- 2 <= nums.length <= 500\n- 1 <= nums[i] <= 10^3"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n m1 = m2 = 0\n for num in nums:\n if num > m1:\n m1, m2 = num, m1\n elif num > m2:\n m2 = num\n return (m1-1)*(m2-1)\n"}} diff --git a/cp/cp-10874.jsonl b/cp/cp-10874.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..53024979efefde94d6807414ebc88ecdc175e882 --- /dev/null +++ b/cp/cp-10874.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10874", "name": "LeetCode 1465: Maximum Area Of A Piece Of Cake After Horizontal And Vertical Cuts"} +{"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 Area of a Piece of Cake After Horizontal and Vertical Cuts (Difficulty: Medium)\nTags: Array, Greedy, Sorting\n\nYou are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where:\nReturn the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, return this modulo 109 + 7.\n\nExample 1:\nInput: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]\nOutput: 4 \nExplanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.\n\nExample 2:\nInput: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]\nOutput: 6\nExplanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.\n\nExample 3:\nInput: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]\nOutput: 9\n\nConstraints:\n- 2 <= h, w <= 10^9\n- 1 <= horizontalCuts.length <= min(h - 1, 105)\n- 1 <= verticalCuts.length <= min(w - 1, 105)\n- 1 <= horizontalCuts[i] < h\n- 1 <= verticalCuts[i] < w\n- All the elements in horizontalCuts are distinct.\n- All the elements in verticalCuts are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(hlogh + wlogw)\n# Space: O(1)\n\nclass Solution(object):\n def maxArea(self, h, w, horizontalCuts, verticalCuts):\n \"\"\"\n :type h: int\n :type w: int\n :type horizontalCuts: List[int]\n :type verticalCuts: List[int]\n :rtype: int\n \"\"\"\n def max_len(l, cuts):\n cuts.sort()\n l = max(cuts[0]-0, l-cuts[-1])\n for i in range(1, len(cuts)):\n l = max(l, cuts[i]-cuts[i-1])\n return l\n\n MOD = 10**9+7\n return max_len(h, horizontalCuts) * max_len(w, verticalCuts) % MOD\n"}} diff --git a/cp/cp-10875.jsonl b/cp/cp-10875.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..17642dc757a92fba86010b9f08e0917a71da236f --- /dev/null +++ b/cp/cp-10875.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10875", "name": "LeetCode 1466: Reorder Routes To Make All Paths Lead To The City Zero"} +{"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: Reorder Routes to Make All Paths Lead to the City Zero (Difficulty: Medium)\nTags: Depth-First Search, Breadth-First Search, Graph\n\nThere are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.\nRoads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.\nThis year, there will be a big event in the capital (city 0), and many people want to travel to this city.\nYour task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.\nIt's guaranteed that each city can reach city 0 after reorder.\n\nExample 1:\nInput: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]\nOutput: 3\nExplanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).\n\nExample 2:\nInput: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]\nOutput: 2\nExplanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).\n\nExample 3:\nInput: n = 3, connections = [[1,0],[2,0]]\nOutput: 0\n\nConstraints:\n- 2 <= n <= 5 * 10^4\n- connections.length == n - 1\n- connections[i].length == 2\n- 0 <= ai, bi <= n - 1\n- ai != bi"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def minReorder(self, n, connections):\n \"\"\"\n :type n: int\n :type connections: List[List[int]]\n :rtype: int\n \"\"\"\n lookup, graph = set(), collections.defaultdict(list)\n for u, v in connections:\n lookup.add(u*n+v)\n graph[v].append(u)\n graph[u].append(v) \n result = 0\n stk = [(-1, 0)]\n while stk:\n parent, u = stk.pop()\n result += (parent*n+u in lookup)\n for v in reversed(graph[u]):\n if v == parent:\n continue\n stk.append((u, v))\n return result\n\n\n# Time: O(n)\n# Space: O(n)\nimport collections\n\n\nclass Solution2(object):\n def minReorder(self, n, connections):\n \"\"\"\n :type n: int\n :type connections: List[List[int]]\n :rtype: int\n \"\"\"\n def dfs(n, lookup, graph, parent, u):\n result = (parent*n+u in lookup)\n for v in graph[u]:\n if v == parent:\n continue\n result += dfs(n, lookup, graph, u, v) \n return result\n\n lookup, graph = set(), collections.defaultdict(list)\n for u, v in connections:\n lookup.add(u*n+v)\n graph[v].append(u)\n graph[u].append(v) \n return dfs(n, lookup, graph, -1, 0)\n"}} diff --git a/cp/cp-10876.jsonl b/cp/cp-10876.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..56b8e3739f55b678b151870a58d09099a226723e --- /dev/null +++ b/cp/cp-10876.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10876", "name": "LeetCode 1467: Probability Of A Two Boxes Having The Same Number Of Distinct Balls"} +{"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: Probability of a Two Boxes Having The Same Number of Distinct Balls (Difficulty: Hard)\nTags: Array, Math, Dynamic Programming, Backtracking, Combinatorics, Probability and Statistics\n\nGiven 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i.\nAll the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully).\nPlease note that the two boxes are considered different. For example, if we have two balls of colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully).\nReturn the probability that the two boxes have the same number of distinct balls. Answers within 10-5 of the actual value will be accepted as correct.\n\nExample 1:\nInput: balls = [1,1]\nOutput: 1.00000\nExplanation: Only 2 ways to divide the balls equally:\n- A ball of color 1 to box 1 and a ball of color 2 to box 2\n- A ball of color 2 to box 1 and a ball of color 1 to box 2\nIn both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1\n\nExample 2:\nInput: balls = [2,1,1]\nOutput: 0.66667\nExplanation: We have the set of balls [1, 1, 2, 3]\nThis set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):\n[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]\nAfter that, we add the first two balls to the first box and the second two balls to the second box.\nWe can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.\nProbability is 8/12 = 0.66667\n\nExample 3:\nInput: balls = [1,2,1,2]\nOutput: 0.60000\nExplanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.\nProbability = 108 / 180 = 0.6\n\nConstraints:\n- 1 <= balls.length <= 8\n- 1 <= balls[i] <= 6\n- sum(balls) is even."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(k^3 * n^2)\n# Space: O(k^2 * n)\n\nimport collections\n\n\nclass Solution(object):\n def getProbability(self, balls):\n \"\"\"\n :type balls: List[int]\n :rtype: float\n \"\"\"\n def nCrs(n): # Time: O(n), Space: O(1)\n c = 1\n for k in range(n+1):\n yield c\n c *= n-(k+1)+1\n c //= k+1\n \n def nCr(n, r): # Time: O(n), Space: O(1)\n if n-r < r:\n return nCr(n, n-r)\n c = 1\n for k in range(1, r+1):\n c *= n-k+1\n c //= k\n return c\n \n dp = collections.defaultdict(int)\n dp[0, 0] = 1 # dp[i, j] is the number of ways with number difference i and color difference j\n for n in balls: # O(k) times\n new_dp = collections.defaultdict(int)\n for (ndiff, cdiff), count in dp.iteritems(): # O(k^2 * n) times\n for k, new_count in enumerate(nCrs(n)): # O(n) times\n new_ndiff = ndiff+(k-(n-k))\n new_cdiff = cdiff-1 if k == 0 else (cdiff+1 if k == n else cdiff)\n new_dp[new_ndiff, new_cdiff] += count*new_count\n dp = new_dp\n total = sum(balls)\n return float(dp[0, 0])/nCr(total, total//2)\n"}} diff --git a/cp/cp-10878.jsonl b/cp/cp-10878.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..89553ff2da5e384a5739e464324943b48b6dd0e8 --- /dev/null +++ b/cp/cp-10878.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10878", "name": "LeetCode 1470: Shuffle The 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: Shuffle the Array (Difficulty: Easy)\nTags: Array\n\nGiven the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].\nReturn the array in the form [x1,y1,x2,y2,...,xn,yn].\n\nExample 1:\nInput: nums = [2,5,1,3,4,7], n = 3\r\nOutput: [2,3,5,4,1,7] \r\nExplanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].\n\nExample 2:\nInput: nums = [1,2,3,4,4,3,2,1], n = 4\r\nOutput: [1,4,2,3,3,2,4,1]\n\nExample 3:\nInput: nums = [1,1,2,2], n = 2\r\nOutput: [1,2,1,2]\n\nConstraints:\n- 1 <= n <= 500\n- nums.length == 2n\n- 1 <= nums[i] <= 10^3"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def shuffle(self, nums, n):\n \"\"\"\n :type nums: List[int]\n :type n: int\n :rtype: List[int]\n \"\"\"\n def index(i):\n return 2*i if i < n else 2*(i-n)+1\n \n for i in range(len(nums)):\n j = i\n while nums[i] >= 0:\n j = index(j)\n nums[i], nums[j] = nums[j], ~nums[i] # processed\n for i in range(len(nums)):\n nums[i] = ~nums[i]\n return nums\n"}} diff --git a/cp/cp-10879.jsonl b/cp/cp-10879.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..791ed467b31f7c1352ad78e136de47ee52413b0c --- /dev/null +++ b/cp/cp-10879.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10879", "name": "LeetCode 1471: The K Strongest Values In An 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: The k Strongest Values in an Array (Difficulty: Medium)\nTags: Array, Two Pointers, Sorting\n\nGiven an array of integers arr and an integer k.\nA value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the centre of the array.\nIf |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j].\nReturn a list of the strongest k values in the array. return the answer in any arbitrary order.\nThe centre is the middle value in an ordered integer list. More formally, if the length of the list is n, the centre is the element in position ((n - 1) / 2) in the sorted list (0-indexed).\n\nExample 1:\nInput: arr = [1,2,3,4,5], k = 2\nOutput: [5,1]\nExplanation: Centre is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.\nPlease note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.\n\nExample 2:\nInput: arr = [1,1,3,5,5], k = 2\nOutput: [5,5]\nExplanation: Centre is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].\n\nExample 3:\nInput: arr = [6,7,11,7,6,8], k = 5\nOutput: [11,8,6,6,7]\nExplanation: Centre is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].\nAny permutation of [11,8,6,6,7] is accepted.\n\nConstraints:\n- 1 <= arr.length <= 10^5\n- -10^5 <= arr[i] <= 10^5\n- 1 <= k <= arr.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def getStrongest(self, arr, k):\n \"\"\"\n :type arr: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n arr.sort()\n m = arr[(len(arr)-1)//2]\n result = []\n left, right = 0, len(arr)-1\n while len(result) < k:\n if m-arr[left] > arr[right]-m:\n result.append(arr[left])\n left += 1\n else:\n result.append(arr[right])\n right -= 1\n return result\n\n\n# Time: O(nlogn)\n# Space: O(1)\nclass Solution2(object):\n def getStrongest(self, arr, k):\n \"\"\"\n :type arr: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n arr.sort()\n m = arr[(len(arr)-1)//2]\n arr.sort(key=lambda x: (-abs(x-m), -x))\n return arr[:k]\n\n\n# Time: O(n)\n# Space: O(1)\nimport random\n\n\nclass Solution_TLE(object):\n def getStrongest(self, arr, k):\n \"\"\"\n :type arr: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n def nth_element(nums, n, compare=lambda a, b: a < b):\n def partition_around_pivot(left, right, pivot_idx, nums, compare):\n new_pivot_idx = left\n nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]\n for i in range(left, right):\n if compare(nums[i], nums[right]):\n nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]\n new_pivot_idx += 1\n\n nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]\n return new_pivot_idx\n\n left, right = 0, len(nums) - 1\n while left <= right:\n pivot_idx = random.randint(left, right)\n new_pivot_idx = partition_around_pivot(left, right, pivot_idx, nums, compare)\n if new_pivot_idx == n:\n return\n elif new_pivot_idx > n:\n right = new_pivot_idx - 1\n else: # new_pivot_idx < n\n left = new_pivot_idx + 1\n \n nth_element(arr, (len(arr)-1)//2)\n m = arr[(len(arr)-1)//2]\n nth_element(arr, k, lambda a, b: abs(a-m) > abs(b-m) if abs(a-m) != abs(b-m) else a > b)\n return arr[:k]\n"}} diff --git a/cp/cp-10880.jsonl b/cp/cp-10880.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b1726739a4dcbc245675f766ccb62de9b451e4cd --- /dev/null +++ b/cp/cp-10880.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10880", "name": "LeetCode 1472: Design Browser History"} +{"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 Browser History (Difficulty: Medium)\nTags: Array, Linked List, Stack, Design, Doubly-Linked List, Data Stream\n\nYou have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps.\nImplement the BrowserHistory class:\nExample:\n\nExample 1:\nInput:\n[\"BrowserHistory\",\"visit\",\"visit\",\"visit\",\"back\",\"back\",\"forward\",\"visit\",\"forward\",\"back\",\"back\"]\n[[\"leetcode.com\"],[\"google.com\"],[\"facebook.com\"],[\"youtube.com\"],[1],[1],[1],[\"linkedin.com\"],[2],[2],[7]]\nOutput:\n[null,null,null,null,\"facebook.com\",\"google.com\",\"facebook.com\",null,\"linkedin.com\",\"google.com\",\"leetcode.com\"]\n\nExplanation:\nBrowserHistory browserHistory = new BrowserHistory(\"leetcode.com\");\nbrowserHistory.visit(\"google.com\"); // You are in \"leetcode.com\". Visit \"google.com\"\nbrowserHistory.visit(\"facebook.com\"); // You are in \"google.com\". Visit \"facebook.com\"\nbrowserHistory.visit(\"youtube.com\"); // You are in \"facebook.com\". Visit \"youtube.com\"\nbrowserHistory.back(1); // You are in \"youtube.com\", move back to \"facebook.com\" return \"facebook.com\"\nbrowserHistory.back(1); // You are in \"facebook.com\", move back to \"google.com\" return \"google.com\"\nbrowserHistory.forward(1); // You are in \"google.com\", move forward to \"facebook.com\" return \"facebook.com\"\nbrowserHistory.visit(\"linkedin.com\"); // You are in \"facebook.com\". Visit \"linkedin.com\"\nbrowserHistory.forward(2); // You are in \"linkedin.com\", you cannot move forward any steps.\nbrowserHistory.back(2); // You are in \"linkedin.com\", move back two steps to \"facebook.com\" then to \"google.com\". return \"google.com\"\nbrowserHistory.back(7); // You are in \"google.com\", you can move back only one step to \"leetcode.com\". return \"leetcode.com\"\n\nConstraints:\n- 1 <= homepage.length <= 20\n- 1 <= url.length <= 20\n- 1 <= steps <= 100\n- homepage and url consist of  '.' or lower case English letters.\n- At most 5000 calls will be made to visit, back, and forward."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor : O(1)\n# visit : O(n)\n# back : O(1)\n# foward: O(1)\n# Space: O(n)\n\nclass BrowserHistory(object):\n\n def __init__(self, homepage):\n \"\"\"\n :type homepage: str\n \"\"\"\n self.__history = [homepage]\n self.__curr = 0 \n\n def visit(self, url):\n \"\"\"\n :type url: str\n :rtype: None\n \"\"\"\n while len(self.__history) > self.__curr+1:\n self.__history.pop()\n self.__history.append(url)\n self.__curr += 1\n\n def back(self, steps):\n \"\"\"\n :type steps: int\n :rtype: str\n \"\"\"\n self.__curr = max(self.__curr-steps, 0)\n return self.__history[self.__curr]\n\n def forward(self, steps):\n \"\"\"\n :type steps: int\n :rtype: str\n \"\"\"\n self.__curr = min(self.__curr+steps, len(self.__history)-1)\n return self.__history[self.__curr]\n"}} diff --git a/cp/cp-10881.jsonl b/cp/cp-10881.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..29d1e216abb60972e8cd8d39a93f5e352f15841d --- /dev/null +++ b/cp/cp-10881.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10881", "name": "LeetCode 1473: Paint House 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: Paint House III (Difficulty: Hard)\nTags: Array, Dynamic Programming\n\nThere is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again.\nA neighborhood is a maximal group of continuous houses that are painted with the same color.\nGiven an array houses, an m x n matrix cost and an integer target where:\nReturn the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods. If it is not possible, return -1.\n\nExample 1:\nInput: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\nOutput: 9\nExplanation: Paint houses of this way [1,2,2,1,1]\nThis array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].\nCost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.\n\nExample 2:\nInput: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\nOutput: 11\nExplanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2]\nThis array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. \nCost of paint the first and last house (10 + 1) = 11.\n\nExample 3:\nInput: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3\nOutput: -1\nExplanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.\n\nConstraints:\n- m == houses.length == cost.length\n- n == cost[i].length\n- 1 <= m <= 100\n- 1 <= n <= 20\n- 1 <= target <= m\n- 0 <= houses[i] <= n\n- 1 <= cost[i][j] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * t * n^2)\n# Space: O(t * n)\n\nclass Solution(object):\n def minCost(self, houses, cost, m, n, target):\n \"\"\"\n :type houses: List[int]\n :type cost: List[List[int]]\n :type m: int\n :type n: int\n :type target: int\n :rtype: int\n \"\"\"\n # dp[i][j][k]: cost of covering i+1 houses with j+1 neighbor groups and the (k+1)th color\n dp = [[[float(\"inf\") for _ in range(n)] for _ in range(target)] for _ in range(2)]\n for i in range(m):\n dp[i%2] = [[float(\"inf\") for _ in range(n)] for _ in range(target)]\n for j in range(min(target, i+1)):\n for k in range(n):\n if houses[i] and houses[i]-1 != k:\n continue\n same = dp[(i-1)%2][j][k] if i-1 >= 0 else 0\n diff = (min([dp[(i-1)%2][j-1][nk] for nk in range(n) if nk != k] or [float(\"inf\")]) if j-1 >= 0 else float(\"inf\")) if i-1 >= 0 else 0\n paint = cost[i][k] if not houses[i] else 0\n dp[i%2][j][k] = min(same, diff)+paint\n result = min(dp[(m-1)%2][-1])\n return result if result != float(\"inf\") else -1\n\n\n# Time: O(m * t * n^2)\n# Space: O(t * n)\nclass Solution2(object):\n def minCost(self, houses, cost, m, n, target):\n \"\"\"\n :type houses: List[int]\n :type cost: List[List[int]]\n :type m: int\n :type n: int\n :type target: int\n :rtype: int\n \"\"\"\n dp = {(0, 0): 0}\n for i, p in enumerate(houses):\n new_dp = {}\n for nk in (range(1, n+1) if not p else [p]):\n for j, k in dp:\n nj = j + (k != nk)\n if nj > target:\n continue\n new_dp[nj, nk] = min(new_dp.get((nj, nk), float(\"inf\")), dp[j, k] + (cost[i][nk-1] if nk != p else 0))\n dp = new_dp\n return min([dp[j, k] for j, k in dp if j == target] or [-1])\n"}} diff --git a/cp/cp-10883.jsonl b/cp/cp-10883.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8d3dc43a05ebbc1d6cba6ae7237a8b1c0326881a --- /dev/null +++ b/cp/cp-10883.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10883", "name": "LeetCode 1475: Final Prices With A Special Discount In A Shop"} +{"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: Final Prices With a Special Discount in a Shop (Difficulty: Easy)\nTags: Array, Stack, Monotonic Stack\n\nYou are given an integer array prices where prices[i] is the price of the ith item in a shop.\nThere is a special discount for items in the shop. If you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i]. Otherwise, you will not receive any discount at all.\nReturn an integer array answer where answer[i] is the final price you will pay for the ith item of the shop, considering the special discount.\n\nExample 1:\nInput: prices = [8,4,6,2,3]\nOutput: [4,2,4,2,3]\nExplanation: \nFor item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.\nFor item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.\nFor item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.\nFor items 3 and 4 you will not receive any discount at all.\n\nExample 2:\nInput: prices = [1,2,3,4,5]\nOutput: [1,2,3,4,5]\nExplanation: In this case, for all items, you will not receive any discount at all.\n\nExample 3:\nInput: prices = [10,1,1,6]\nOutput: [9,0,1,6]\n\nConstraints:\n- 1 <= prices.length <= 500\n- 1 <= prices[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def finalPrices(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: List[int]\n \"\"\"\n stk = []\n for i, p in enumerate(prices):\n while stk and prices[stk[-1]] >= p:\n prices[stk.pop()] -= p\n stk.append(i)\n return prices\n"}} diff --git a/cp/cp-10884.jsonl b/cp/cp-10884.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ded45d0aca7e899d65593f67c563be50a1f808cd --- /dev/null +++ b/cp/cp-10884.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10884", "name": "LeetCode 1476: Subrectangle Queries"} +{"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: Subrectangle Queries (Difficulty: Medium)\nTags: Array, Design, Matrix\n\nImplement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods:\n1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)\n2. getValue(int row, int col)\n\nExample 1:\nInput\n[\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\"]\n[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]\nOutput\n[null,1,null,5,5,null,10,5]\nExplanation\nSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]); \n// The initial rectangle (4x3) looks like:\n// 1 2 1\n// 4 3 4\n// 3 2 1\n// 1 1 1\nsubrectangleQueries.getValue(0, 2); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);\n// After this update the rectangle looks like:\n// 5 5 5\n// 5 5 5\n// 5 5 5\n// 5 5 5 \nsubrectangleQueries.getValue(0, 2); // return 5\nsubrectangleQueries.getValue(3, 1); // return 5\nsubrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);\n// After this update the rectangle looks like:\n// 5 5 5\n// 5 5 5\n// 5 5 5\n// 10 10 10 \nsubrectangleQueries.getValue(3, 1); // return 10\nsubrectangleQueries.getValue(0, 2); // return 5\n\nExample 2:\nInput\n[\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\"]\n[[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]]\nOutput\n[null,1,null,100,100,null,20]\nExplanation\nSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]);\nsubrectangleQueries.getValue(0, 0); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100);\nsubrectangleQueries.getValue(0, 0); // return 100\nsubrectangleQueries.getValue(2, 2); // return 100\nsubrectangleQueries.updateSubrectangle(1, 1, 2, 2, 20);\nsubrectangleQueries.getValue(2, 2); // return 20\n\nConstraints:\n- There will be at most 500 operations considering both methods: updateSubrectangle and getValue.\n- 1 <= rows, cols <= 100\n- rows == rectangle.length\n- cols == rectangle[i].length\n- 0 <= row1 <= row2 < rows\n- 0 <= col1 <= col2 < cols\n- 1 <= newValue, rectangle[i][j] <= 10^9\n- 0 <= row < rows\n- 0 <= col < cols"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(1)\n# update: O(1)\n# get: O(u), u is the number of updates\n# Space: O(u)\n\nclass SubrectangleQueries(object):\n\n def __init__(self, rectangle):\n \"\"\"\n :type rectangle: List[List[int]]\n \"\"\"\n self.__rectangle = rectangle\n self.__updates = []\n \n\n def updateSubrectangle(self, row1, col1, row2, col2, newValue):\n \"\"\"\n :type row1: int\n :type col1: int\n :type row2: int\n :type col2: int\n :type newValue: int\n :rtype: None\n \"\"\"\n self.__updates.append((row1, col1, row2, col2, newValue))\n\n def getValue(self, row, col):\n \"\"\"\n :type row: int\n :type col: int\n :rtype: int\n \"\"\"\n for (row1, col1, row2, col2, newValue) in reversed(self.__updates):\n if row1 <= row <= row2 and col1 <= col <= col2:\n return newValue\n return self.__rectangle[row][col]\n\n\n# Time: ctor: O(1)\n# update: O(m * n)\n# get: O(1)\n# Space: O(1)\nclass SubrectangleQueries2(object):\n\n def __init__(self, rectangle):\n \"\"\"\n :type rectangle: List[List[int]]\n \"\"\"\n self.__rectangle = rectangle\n \n\n def updateSubrectangle(self, row1, col1, row2, col2, newValue):\n \"\"\"\n :type row1: int\n :type col1: int\n :type row2: int\n :type col2: int\n :type newValue: int\n :rtype: None\n \"\"\"\n for r in range(row1, row2+1):\n for c in range(col1, col2+1):\n self.__rectangle[r][c] = newValue\n\n def getValue(self, row, col):\n \"\"\"\n :type row: int\n :type col: int\n :rtype: int\n \"\"\"\n return self.__rectangle[row][col]\n"}} diff --git a/cp/cp-10885.jsonl b/cp/cp-10885.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b320046d9d57f42f8d329889ddd14426460c6667 --- /dev/null +++ b/cp/cp-10885.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10885", "name": "LeetCode 1477: Find Two Non Overlapping Sub Arrays Each With Target Sum"} +{"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 Two Non-overlapping Sub-arrays Each With Target Sum (Difficulty: Medium)\nTags: Array, Hash Table, Binary Search, Dynamic Programming, Sliding Window\n\nYou are given an array of integers arr and an integer target.\nYou have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.\nReturn the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.\n\nExample 1:\nInput: arr = [3,2,2,4,3], target = 3\nOutput: 2\nExplanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.\n\nExample 2:\nInput: arr = [7,3,4,7], target = 7\nOutput: 2\nExplanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.\n\nExample 3:\nInput: arr = [4,3,2,6,2,3,4], target = 6\nOutput: -1\nExplanation: We have only one sub-array of sum = 6.\n\nConstraints:\n- 1 <= arr.length <= 10^5\n- 1 <= arr[i] <= 1000\n- 1 <= target <= 10^8"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def minSumOfLengths(self, arr, target):\n \"\"\"\n :type arr: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n prefix, dp = {0: -1}, [0]*len(arr) # dp[i], min len of target subarray until i\n result = min_len = float(\"inf\")\n accu = 0\n for right in range(len(arr)):\n accu += arr[right]\n prefix[accu] = right\n if accu-target in prefix:\n left = prefix[accu-target]\n min_len = min(min_len, right-left)\n if left != -1:\n result = min(result, dp[left] + (right-left))\n dp[right] = min_len\n return result if result != float(\"inf\") else -1\n"}} diff --git a/cp/cp-10886.jsonl b/cp/cp-10886.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dfcebb378624d4e6de6bc875772f337f88aa0e5f --- /dev/null +++ b/cp/cp-10886.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10886", "name": "LeetCode 1478: Allocate Mailboxes"} +{"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: Allocate Mailboxes (Difficulty: Hard)\nTags: Array, Math, Dynamic Programming, Sorting\n\nGiven the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street.\nReturn the minimum total distance between each house and its nearest mailbox.\nThe test cases are generated so that the answer fits in a 32-bit integer.\n\nExample 1:\nInput: houses = [1,4,8,10,20], k = 3\nOutput: 5\nExplanation: Allocate mailboxes in position 3, 9 and 20.\nMinimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5\n\nExample 2:\nInput: houses = [2,3,5,12,18], k = 2\nOutput: 9\nExplanation: Allocate mailboxes in position 3 and 14.\nMinimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.\n\nConstraints:\n- 1 <= k <= houses.length <= 100\n- 1 <= houses[i] <= 10^4\n- All the integers of houses are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n^2)\n# Space: O(n)\n\nclass Solution(object):\n def minDistance(self, houses, k):\n \"\"\"\n :type houses: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n def cost(prefix, i, j):\n return (prefix[j+1]-prefix[(i+j+1)//2])-(prefix[(i+j)//2+1]-prefix[i])\n\n houses.sort()\n prefix = [0]*(len(houses)+1)\n for i, h in enumerate(houses):\n prefix[i+1] = prefix[i]+h\n dp = [cost(prefix, 0, j) for j in range(len(houses))]\n for m in range(1, k):\n for j in reversed(range(m, len(houses))):\n for i in range(m, j+1):\n dp[j] = min(dp[j], dp[i-1]+cost(prefix, i, j))\n return dp[-1]\n"}} diff --git a/cp/cp-10888.jsonl b/cp/cp-10888.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..61a75f2610cc8fb4b4e4deb9ee55a86e3c703eae --- /dev/null +++ b/cp/cp-10888.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10888", "name": "LeetCode 1481: Least Number Of Unique Integers After K Removals"} +{"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: Least Number of Unique Integers after K Removals (Difficulty: Medium)\nTags: Array, Hash Table, Greedy, Sorting, Counting\n\nGiven an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.\n\nExample 1:\nInput: arr = [5,5,4], k = 1\r\nOutput: 1\r\nExplanation: Remove the single 4, only 5 is left.\n\nExample 2:\nInput: arr = [4,3,1,1,3,3,2], k = 3\r\nOutput: 2\r\nExplanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.\n\nConstraints:\n- 1 <= arr.length <= 10^5\n- 1 <= arr[i] <= 10^9\n- 0 <= k <= arr.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def findLeastNumOfUniqueInts(self, arr, k):\n \"\"\"\n :type arr: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n count = collections.Counter(arr)\n result, count_count = len(count), collections.Counter(count.itervalues())\n for c in range(1, len(arr)+1): \n if k < c*count_count[c]:\n result -= k//c\n break\n k -= c*count_count[c]\n result -= count_count[c] \n return result\n"}} diff --git a/cp/cp-10889.jsonl b/cp/cp-10889.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..de18a4c2ee045f9d9f4d9d4117e4e720745ce04f --- /dev/null +++ b/cp/cp-10889.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10889", "name": "LeetCode 1482: Minimum Number Of Days To Make M Bouquets"} +{"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: Minimum Number of Days to Make m Bouquets (Difficulty: Medium)\nTags: Array, Binary Search\n\nYou are given an integer array bloomDay, an integer m and an integer k.\nYou want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.\nThe garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.\nReturn the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.\n\nExample 1:\nInput: bloomDay = [1,10,3,10,2], m = 3, k = 1\nOutput: 3\nExplanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.\nWe need 3 bouquets each should contain 1 flower.\nAfter day 1: [x, _, _, _, _] // we can only make one bouquet.\nAfter day 2: [x, _, _, _, x] // we can only make two bouquets.\nAfter day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.\n\nExample 2:\nInput: bloomDay = [1,10,3,10,2], m = 3, k = 2\nOutput: -1\nExplanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.\n\nExample 3:\nInput: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3\nOutput: 12\nExplanation: We need 2 bouquets each should have 3 flowers.\nHere is the garden after the 7 and 12 days:\nAfter day 7: [x, x, x, x, _, x, x]\nWe can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.\nAfter day 12: [x, x, x, x, x, x, x]\nIt is obvious that we can make two bouquets in different ways.\n\nConstraints:\n- bloomDay.length == n\n- 1 <= n <= 10^5\n- 1 <= bloomDay[i] <= 10^9\n- 1 <= m <= 10^6\n- 1 <= k <= n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogd), d is the max day of bloomDay\n# Space: O(1)\n\nclass Solution(object):\n def minDays(self, bloomDay, m, k):\n \"\"\"\n :type bloomDay: List[int]\n :type m: int\n :type k: int\n :rtype: int\n \"\"\"\n def check(bloomDay, m, k, x):\n result = count = 0\n for d in bloomDay:\n count = count+1 if d <= x else 0\n if count == k:\n count = 0\n result += 1\n if result == m:\n break\n return result >= m\n\n if m*k > len(bloomDay):\n return -1\n left, right = 1, max(bloomDay)\n while left <= right:\n mid = left + (right-left)//2\n if check(bloomDay, m, k, mid):\n right = mid-1\n else:\n left = mid+1\n return left\n"}} diff --git a/cp/cp-10890.jsonl b/cp/cp-10890.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7a1de9701b98e39940923e43068643ed2e4c90a1 --- /dev/null +++ b/cp/cp-10890.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10890", "name": "LeetCode 1483: Kth Ancestor Of A Tree Node"} +{"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 Ancestor of a Tree Node (Difficulty: Hard)\nTags: Binary Search, Dynamic Programming, Tree, Depth-First Search, Breadth-First Search, Design\n\nYou are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a given node.\nThe kth ancestor of a tree node is the kth node in the path from that node to the root node.\nImplement the TreeAncestor class:\n\nExample 1:\nInput\n[\"TreeAncestor\", \"getKthAncestor\", \"getKthAncestor\", \"getKthAncestor\"]\n[[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]]\nOutput\n[null, 1, 0, -1]\n\nExplanation\nTreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);\ntreeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3\ntreeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5\ntreeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor\n\nConstraints:\n- 1 <= k <= n <= 5 * 10^4\n- parent.length == n\n- parent[0] == -1\n- 0 <= parent[i] < n for all 0 < i < n\n- 0 <= node < n\n- There will be at most 5 * 10^4 queries."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(n * logh)\n# get: O(logh)\n# Space: O(n * logh)\n\n# binary jump solution (frequently used in competitive programming)\n# Template:\n# https://github.com/kamyu104/FacebookHackerCup-2019/blob/master/Final%20Round/little_boat_on_the_sea.py\nclass TreeAncestor(object):\n\n def __init__(self, n, parent):\n \"\"\"\n :type n: int\n :type parent: List[int]\n \"\"\"\n par = [[p] if p != -1 else [] for p in parent]\n q = [par[i] for i, p in enumerate(parent) if p != -1]\n i = 0\n while q:\n new_q = []\n for p in q:\n if not (i < len(par[p[i]])):\n continue\n p.append(par[p[i]][i])\n new_q.append(p)\n q = new_q\n i += 1\n self.__parent = par\n\n def getKthAncestor(self, node, k):\n \"\"\"\n :type node: int\n :type k: int\n :rtype: int\n \"\"\"\n par, i, pow_i_of_2 = self.__parent, 0, 1\n while pow_i_of_2 <= k:\n if k & pow_i_of_2:\n if not (i < len(par[node])):\n return -1\n node = par[node][i]\n i += 1\n pow_i_of_2 *= 2\n return node\n"}} diff --git a/cp/cp-10892.jsonl b/cp/cp-10892.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0b098a5d46ef8d9c046861422d0201e1eb72b438 --- /dev/null +++ b/cp/cp-10892.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10892", "name": "LeetCode 1486: Xor Operation In An 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: XOR Operation in an Array (Difficulty: Easy)\nTags: Math, Bit Manipulation\n\nYou are given an integer n and an integer start.\nDefine an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length.\nReturn the bitwise XOR of all elements of nums.\n\nExample 1:\nInput: n = 5, start = 0\nOutput: 8\nExplanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.\nWhere \"^\" corresponds to bitwise XOR operator.\n\nExample 2:\nInput: n = 4, start = 3\nOutput: 8\nExplanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.\n\nConstraints:\n- 1 <= n <= 1000\n- 0 <= start <= 1000\n- n == nums.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def xorOperation(self, n, start):\n \"\"\"\n :type n: int\n :type start: int\n :rtype: int\n \"\"\"\n def xorNums(n, start):\n def xorNumsBeginEven(n, start):\n assert(start%2 == 0)\n # 2*i ^ (2*i+1) = 1\n return ((n//2)%2)^((start+n-1) if n%2 else 0)\n\n return start^xorNumsBeginEven(n-1, start+1) if start%2 else xorNumsBeginEven(n, start)\n \n return int(n%2 and start%2) + 2*xorNums(n, start//2)\n\n\n# Time: O(n)\n# Space: O(1)\nimport operator\n\n\nclass Solution2(object):\n def xorOperation(self, n, start):\n \"\"\"\n :type n: int\n :type start: int\n :rtype: int\n \"\"\"\n return reduce(operator.xor, (i for i in range(start, start+2*n, 2)))\n"}} diff --git a/cp/cp-10893.jsonl b/cp/cp-10893.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..643085e167a73c99a4564e1cd45dfbc14501890c --- /dev/null +++ b/cp/cp-10893.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10893", "name": "LeetCode 1487: Making File Names Unique"} +{"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: Making File Names Unique (Difficulty: Medium)\nTags: Array, Hash Table, String\n\nGiven an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i].\nSince two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique.\nReturn an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it.\n\nExample 1:\nInput: names = [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\nOutput: [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\nExplanation: Let's see how the file system creates folder names:\n\"pes\" --> not assigned before, remains \"pes\"\n\"fifa\" --> not assigned before, remains \"fifa\"\n\"gta\" --> not assigned before, remains \"gta\"\n\"pes(2019)\" --> not assigned before, remains \"pes(2019)\"\n\nExample 2:\nInput: names = [\"gta\",\"gta(1)\",\"gta\",\"avalon\"]\nOutput: [\"gta\",\"gta(1)\",\"gta(2)\",\"avalon\"]\nExplanation: Let's see how the file system creates folder names:\n\"gta\" --> not assigned before, remains \"gta\"\n\"gta(1)\" --> not assigned before, remains \"gta(1)\"\n\"gta\" --> the name is reserved, system adds (k), since \"gta(1)\" is also reserved, systems put k = 2. it becomes \"gta(2)\"\n\"avalon\" --> not assigned before, remains \"avalon\"\n\nExample 3:\nInput: names = [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece\"]\nOutput: [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece(4)\"]\nExplanation: When the last folder is created, the smallest positive valid k is 4, and it becomes \"onepiece(4)\".\n\nConstraints:\n- 1 <= names.length <= 5 * 10^4\n- 1 <= names[i].length <= 20\n- names[i] consists of lowercase English letters, digits, and/or round brackets."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def getFolderNames(self, names):\n \"\"\"\n :type names: List[str]\n :rtype: List[str]\n \"\"\"\n count = collections.Counter()\n result, lookup = [], set()\n for name in names:\n while True:\n name_with_suffix = \"{}({})\".format(name, count[name]) if count[name] else name\n count[name] += 1\n if name_with_suffix not in lookup:\n break\n result.append(name_with_suffix)\n lookup.add(name_with_suffix)\n return result\n"}} diff --git a/cp/cp-10894.jsonl b/cp/cp-10894.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..681d8e316126fadad78853c07eabed8805fedbf7 --- /dev/null +++ b/cp/cp-10894.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10894", "name": "LeetCode 1488: Avoid Flood In The City"} +{"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: Avoid Flood in The City (Difficulty: Medium)\nTags: Array, Hash Table, Binary Search, Greedy, Heap (Priority Queue)\n\nYour country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any lake.\nGiven an integer array rains where:\nReturn an array ans where:\nIf there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.\nNotice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.\n\nExample 1:\nInput: rains = [1,2,3,4]\nOutput: [-1,-1,-1,-1]\nExplanation: After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day full lakes are [1,2,3]\nAfter the fourth day full lakes are [1,2,3,4]\nThere's no day to dry any lake and there is no flood in any lake.\n\nExample 2:\nInput: rains = [1,2,0,0,2,1]\nOutput: [-1,-1,2,1,-1,-1]\nExplanation: After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day, we dry lake 2. Full lakes are [1]\nAfter the fourth day, we dry lake 1. There is no full lakes.\nAfter the fifth day, full lakes are [2].\nAfter the sixth day, full lakes are [1,2].\nIt is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.\n\nExample 3:\nInput: rains = [1,2,0,1,2]\nOutput: []\nExplanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day.\nAfter that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.\n\nConstraints:\n- 1 <= rains.length <= 10^5\n- 0 <= rains[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport collections\nimport heapq\n\n\nclass Solution(object):\n def avoidFlood(self, rains):\n \"\"\"\n :type rains: List[int]\n :rtype: List[int]\n \"\"\"\n lookup = collections.defaultdict(list)\n i = len(rains)-1\n for lake in reversed(rains):\n lookup[lake].append(i)\n i -= 1\n result, min_heap = [], []\n for i, lake in enumerate(rains):\n if lake:\n if len(lookup[lake]) >= 2:\n lookup[lake].pop()\n heapq.heappush(min_heap, lookup[lake][-1])\n result.append(-1)\n elif min_heap:\n j = heapq.heappop(min_heap)\n if j < i:\n return []\n result.append(rains[j])\n else:\n result.append(1)\n return result if not min_heap else []\n"}} diff --git a/cp/cp-10895.jsonl b/cp/cp-10895.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0fa125904122c3e30eb5d0227db05a958fb9c14c --- /dev/null +++ b/cp/cp-10895.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10895", "name": "LeetCode 1489: Find Critical And Pseudo Critical Edges In Minimum Spanning 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: Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree (Difficulty: Hard)\nTags: Union Find, Graph, Sorting, Minimum Spanning Tree, Strongly Connected Component\n\nGiven a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes ai and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.\nFind all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.\nNote that you can return the indices of the edges in any order.\n\nExample 1:\nInput: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]\nOutput: [[0,1],[2,3,4,5]]\nExplanation: The figure above describes the graph.\nThe following figure shows all the possible MSTs:\n\nNotice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.\nThe edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.\n\nExample 2:\nInput: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]\nOutput: [[],[0,1,2,3]]\nExplanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.\n\nConstraints:\n- 2 <= n <= 100\n- 1 <= edges.length <= min(200, n * (n - 1) / 2)\n- edges[i].length == 3\n- 0 <= ai < bi < n\n- 1 <= weighti <= 1000\n- All pairs (ai, bi) are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n self.count = n\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[max(x_root, y_root)] = min(x_root, y_root)\n self.count -= 1\n return True\n\n\nclass Solution(object):\n def findCriticalAndPseudoCriticalEdges(self, n, edges):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n def MST(n, edges, unused=None, used=None):\n union_find = UnionFind(n)\n weight = 0\n if used is not None:\n u, v, w, _ = edges[used]\n if union_find.union_set(u, v):\n weight += w\n for i, (u, v, w, _) in enumerate(edges):\n if i == unused:\n continue\n if union_find.union_set(u, v):\n weight += w\n return weight if union_find.count == 1 else float(\"inf\")\n \n for i, edge in enumerate(edges):\n edge.append(i)\n edges.sort(key=lambda x: x[2])\n mst = MST(n, edges)\n result = [[], []]\n for i, edge in enumerate(edges):\n if mst < MST(n, edges, unused=i):\n result[0].append(edge[3])\n elif mst == MST(n, edges, used=i):\n result[1].append(edge[3])\n return result\n"}} diff --git a/cp/cp-10897.jsonl b/cp/cp-10897.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2b21cd25fa17586da11338f8c43a8e79cb25eefd --- /dev/null +++ b/cp/cp-10897.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10897", "name": "LeetCode 1491: Average Salary Excluding The Minimum And Maximum Salary"} +{"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 Salary Excluding the Minimum and Maximum Salary (Difficulty: Easy)\nTags: Array, Sorting\n\nYou are given an array of unique integers salary where salary[i] is the salary of the ith employee.\nReturn the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted.\n\nExample 1:\nInput: salary = [4000,3000,1000,2000]\nOutput: 2500.00000\nExplanation: Minimum salary and maximum salary are 1000 and 4000 respectively.\nAverage salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500\n\nExample 2:\nInput: salary = [1000,2000,3000]\nOutput: 2000.00000\nExplanation: Minimum salary and maximum salary are 1000 and 3000 respectively.\nAverage salary excluding minimum and maximum salary is (2000) / 1 = 2000\n\nConstraints:\n- 3 <= salary.length <= 100\n- 1000 <= salary[i] <= 10^6\n- All the integers of salary are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# one pass solution\nclass Solution(object):\n def average(self, salary):\n \"\"\"\n :type salary: List[int]\n :rtype: float\n \"\"\"\n total, mi, ma = 0, float(\"inf\"), float(\"-inf\")\n for s in salary:\n total += s\n mi, ma = min(mi, s), max(ma, s)\n return 1.0*(total-mi-ma)/(len(salary)-2)\n\n\n# Time: O(n)\n# Space: O(1)\n# one-liner solution\nclass Solution2(object):\n def average(self, salary):\n \"\"\"\n :type salary: List[int]\n :rtype: float\n \"\"\"\n return 1.0*(sum(salary)-min(salary)-max(salary))/(len(salary)-2)\n"}} diff --git a/cp/cp-10898.jsonl b/cp/cp-10898.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e4a102acbadfb05c1c4dea66ec1a9d0d6a927410 --- /dev/null +++ b/cp/cp-10898.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10898", "name": "LeetCode 1492: The Kth Factor Of N"} +{"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: The kth Factor of n (Difficulty: Medium)\nTags: Math, Number Theory\n\nYou are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0.\nConsider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.\nFollow up:\nCould you solve this problem in less than O(n) complexity?\n\nExample 1:\nInput: n = 12, k = 3\nOutput: 3\nExplanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.\n\nExample 2:\nInput: n = 7, k = 2\nOutput: 7\nExplanation: Factors list is [1, 7], the 2nd factor is 7.\n\nExample 3:\nInput: n = 4, k = 4\nOutput: -1\nExplanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.\n\nConstraints:\n- 1 <= k <= n <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(sqrt(n))\n# Space: O(1)\n\nclass Solution(object):\n def kthFactor(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n def kth_factor(n, k=0):\n mid = None\n i = 1\n while i*i <= n:\n if not n%i:\n mid = i\n k -= 1\n if not k:\n break\n i += 1\n return mid, -k\n \n mid, count = kth_factor(n)\n total = 2*count-(mid*mid == n)\n if k > total:\n return -1\n result = kth_factor(n, k if k <= count else total-(k-1))[0]\n return result if k <= count else n//result\n\n\n# Time: O(sqrt(n))\n# Space: O(sqrt(n))\nclass Solution2(object):\n def kthFactor(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n result = []\n i = 1\n while i*i <= n:\n if not n%i:\n if i*i != n:\n result.append(i)\n k -= 1\n if not k:\n return i\n i += 1\n return -1 if k > len(result) else n//result[-k]\n"}} diff --git a/cp/cp-10899.jsonl b/cp/cp-10899.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..60865b1a01f80afae107c5644919dbd7a6247ac9 --- /dev/null +++ b/cp/cp-10899.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10899", "name": "LeetCode 1493: Longest Subarray Of 1S After Deleting One Element"} +{"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 Subarray of 1's After Deleting One Element (Difficulty: Medium)\nTags: Array, Dynamic Programming, Sliding Window\n\nGiven a binary array nums, you should delete one element from it.\nReturn the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.\n\nExample 1:\nInput: nums = [1,1,0,1]\nOutput: 3\nExplanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.\n\nExample 2:\nInput: nums = [0,1,1,1,0,1,1,0,1]\nOutput: 5\nExplanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].\n\nExample 3:\nInput: nums = [1,1,1]\nOutput: 2\nExplanation: You must delete one element.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- nums[i] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def longestSubarray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n count, left = 0, 0\n for right in range(len(nums)):\n count += (nums[right] == 0)\n if count >= 2:\n count -= (nums[left] == 0)\n left += 1\n return (right-left+1)-1\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def longestSubarray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result, count, left = 0, 0, 0\n for right in range(len(nums)):\n count += (nums[right] == 0)\n while count >= 2:\n count -= (nums[left] == 0)\n left += 1\n result = max(result, right-left+1)\n return result-1\n"}} diff --git a/cp/cp-10900.jsonl b/cp/cp-10900.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..14d8337712915381cf79d8657f6b93ad38c07011 --- /dev/null +++ b/cp/cp-10900.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10900", "name": "LeetCode 1494: Parallel Courses 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: Parallel Courses II (Difficulty: Hard)\nTags: Dynamic Programming, Bit Manipulation, Graph, Bitmask\n\nYou are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei. Also, you are given the integer k.\nIn one semester, you can take at most k courses as long as you have taken all the prerequisites in the previous semesters for the courses you are taking.\nReturn the minimum number of semesters needed to take all courses. The testcases will be generated such that it is possible to take every course.\n\nExample 1:\nInput: n = 4, relations = [[2,1],[3,1],[1,4]], k = 2\nOutput: 3\nExplanation: The figure above represents the given graph.\nIn the first semester, you can take courses 2 and 3.\nIn the second semester, you can take course 1.\nIn the third semester, you can take course 4.\n\nExample 2:\nInput: n = 5, relations = [[2,1],[3,1],[4,1],[1,5]], k = 2\nOutput: 4\nExplanation: The figure above represents the given graph.\nIn the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester.\nIn the second semester, you can take course 4.\nIn the third semester, you can take course 1.\nIn the fourth semester, you can take course 5.\n\nConstraints:\n- 1 <= n <= 15\n- 1 <= k <= n\n- 0 <= relations.length <= n * (n-1) / 2\n- relations[i].length == 2\n- 1 <= prevCoursei, nextCoursei <= n\n- prevCoursei != nextCoursei\n- All the pairs [prevCoursei, nextCoursei] are unique.\n- The given graph is a directed acyclic graph."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((n * C(c, min(c, k))) * 2^n)\n# Space: O(2^n)\n\nimport itertools\n\n\nclass Solution(object):\n def minNumberOfSemesters(self, n, dependencies, k):\n \"\"\"\n :type n: int\n :type dependencies: List[List[int]]\n :type k: int\n :rtype: int\n \"\"\"\n reqs = [0]*n\n for u, v in dependencies:\n reqs[v-1] |= 1 << (u-1)\n dp = [n]*(1<= len(arr) or arr[i] == arr[j]:\n return False\n arr[i], arr[j] = arr[j], arr[i]\n return True\n"}} diff --git a/cp/cp-10907.jsonl b/cp/cp-10907.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8820a2528e2930573c561a9648684e81b9a3f38d --- /dev/null +++ b/cp/cp-10907.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10907", "name": "LeetCode 1504: Count Submatrices With All 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: Count Submatrices With All Ones (Difficulty: Medium)\nTags: Array, Dynamic Programming, Stack, Matrix, Monotonic Stack\n\nGiven an m x n binary matrix mat, return the number of submatrices that have all ones.\n\nExample 1:\nInput: mat = [[1,0,1],[1,1,0],[1,1,0]]\nOutput: 13\nExplanation: \nThere are 6 rectangles of side 1x1.\nThere are 2 rectangles of side 1x2.\nThere are 3 rectangles of side 2x1.\nThere is 1 rectangle of side 2x2. \nThere is 1 rectangle of side 3x1.\nTotal number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.\n\nExample 2:\nInput: mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]\nOutput: 24\nExplanation: \nThere are 8 rectangles of side 1x1.\nThere are 5 rectangles of side 1x2.\nThere are 2 rectangles of side 1x3. \nThere are 4 rectangles of side 2x1.\nThere are 2 rectangles of side 2x2. \nThere are 2 rectangles of side 3x1. \nThere is 1 rectangle of side 3x2. \nTotal number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.\n\nConstraints:\n- 1 <= m, n <= 150\n- mat[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(n)\n\n# mono stack\nclass Solution(object):\n def numSubmat(self, mat):\n \"\"\"\n :type mat: List[List[int]]\n :rtype: int\n \"\"\"\n def count(heights):\n result = curr = 0\n stk = []\n for i in range(len(heights)):\n while stk and heights[stk[-1]] >= heights[i]:\n j = stk.pop()\n curr -= (heights[j]-heights[i])*(j-(stk[-1] if stk else -1))\n stk.append(i)\n curr += heights[i]\n result += curr\n return result\n\n result = 0\n heights = [0]*len(mat[0])\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n heights[j] = heights[j]+1 if mat[i][j] == 1 else 0\n result += count(heights)\n return result\n\n\n# Time: O(m * n)\n# Space: O(n)\n# mono stack, dp\nclass Solution2(object):\n def numSubmat(self, mat):\n \"\"\"\n :type mat: List[List[int]]\n :rtype: int\n \"\"\"\n def count(heights):\n dp, stk = [0]*len(heights), []\n for i in range(len(heights)):\n while stk and heights[stk[-1]] >= heights[i]:\n stk.pop()\n dp[i] = dp[stk[-1]] + heights[i]*(i-stk[-1]) if stk else heights[i]*(i-(-1))\n stk.append(i)\n return sum(dp)\n\n result = 0\n heights = [0]*len(mat[0])\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n heights[j] = heights[j]+1 if mat[i][j] == 1 else 0\n result += count(heights)\n return result\n"}} diff --git a/cp/cp-10908.jsonl b/cp/cp-10908.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0ff5ddf0d514465b5f662a91dbad141ff451e47b --- /dev/null +++ b/cp/cp-10908.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10908", "name": "LeetCode 1505: Minimum Possible Integer After At Most K Adjacent Swaps On Digits"} +{"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: Minimum Possible Integer After at Most K Adjacent Swaps On Digits (Difficulty: Hard)\nTags: String, Greedy, Binary Indexed Tree, Segment Tree\n\nYou are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times.\nReturn the minimum integer you can obtain also as a string.\n\nExample 1:\nInput: num = \"4321\", k = 4\nOutput: \"1342\"\nExplanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.\n\nExample 2:\nInput: num = \"100\", k = 1\nOutput: \"010\"\nExplanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.\n\nExample 3:\nInput: num = \"36789\", k = 1000\nOutput: \"36789\"\nExplanation: We can keep the number without any swaps.\n\nConstraints:\n- 1 <= num.length <= 3 * 10^4\n- num consists of only digits and does not contain leading zeros.\n- 1 <= k <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport collections\n\n\nclass BIT(object): # Fenwick Tree, 1-indexed\n def __init__(self, n):\n self.__bit = [0] * n\n\n def add(self, i, val):\n while i < len(self.__bit):\n self.__bit[i] += val\n i += (i & -i)\n\n def sum(self, i):\n result = 0\n while i > 0:\n result += self.__bit[i]\n i -= (i & -i)\n return result\n\n\nclass Solution(object):\n def minInteger(self, num, k):\n \"\"\"\n :type num: str\n :type k: int\n :rtype: str\n \"\"\"\n lookup = collections.defaultdict(list)\n bit = BIT(len(num)+1)\n for i in reversed(range(len(num))):\n bit.add(i+1, 1)\n lookup[int(num[i])].append(i+1)\n result = []\n for _ in range(len(num)):\n for d in range(10):\n if lookup[d] and bit.sum(lookup[d][-1]-1) <= k:\n k -= bit.sum(lookup[d][-1]-1)\n bit.add(lookup[d].pop(), -1)\n result.append(d)\n break\n return \"\".join(map(str, result))\n"}} diff --git a/cp/cp-10910.jsonl b/cp/cp-10910.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..668205692cc78febda755a0cd55f3f05b1e61211 --- /dev/null +++ b/cp/cp-10910.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10910", "name": "LeetCode 1507: Reformat Date"} +{"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: Reformat Date (Difficulty: Easy)\nTags: String\n\nGiven a date string in the form Day Month Year, where:\nConvert the date string to the format YYYY-MM-DD, where:\n\nExample 1:\nInput: date = \"20th Oct 2052\"\nOutput: \"2052-10-20\"\n\nExample 2:\nInput: date = \"6th Jun 1933\"\nOutput: \"1933-06-06\"\n\nExample 3:\nInput: date = \"26th May 1960\"\nOutput: \"1960-05-26\"\n\nConstraints:\n- The given dates are guaranteed to be valid, so no error handling is necessary."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def reformatDate(self, date):\n \"\"\"\n :type date: str\n :rtype: str\n \"\"\"\n lookup = {\"Jan\":1, \"Feb\":2, \"Mar\":3, \"Apr\":4,\n \"May\":5, \"Jun\":6, \"Jul\":7, \"Aug\":8,\n \"Sep\":9, \"Oct\":10, \"Nov\":11, \"Dec\":12}\n return \"{:04d}-{:02d}-{:02d}\".format(int(date[-4:]), lookup[date[-8:-5]], int(date[:date.index(' ')-2]))\n"}} diff --git a/cp/cp-10911.jsonl b/cp/cp-10911.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3ec49217ad6dab7744ca51b2fe5183406e97caac --- /dev/null +++ b/cp/cp-10911.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10911", "name": "LeetCode 1508: Range Sum Of Sorted Subarray Sums"} +{"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: Range Sum of Sorted Subarray Sums (Difficulty: Medium)\nTags: Array, Two Pointers, Binary Search, Sorting, Prefix Sum\n\nYou are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.\nReturn the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7.\n\nExample 1:\nInput: nums = [1,2,3,4], n = 4, left = 1, right = 5\nOutput: 13 \nExplanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.\n\nExample 2:\nInput: nums = [1,2,3,4], n = 4, left = 3, right = 4\nOutput: 6\nExplanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.\n\nExample 3:\nInput: nums = [1,2,3,4], n = 4, left = 1, right = 10\nOutput: 50\n\nConstraints:\n- n == nums.length\n- 1 <= nums.length <= 1000\n- 1 <= nums[i] <= 100\n- 1 <= left <= right <= n * (n + 1) / 2"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlog(sum(nums)))\n# Space: O(n)\n\n# binary search + sliding window solution\nclass Solution(object):\n def rangeSum(self, nums, n, left, right):\n \"\"\"\n :type nums: List[int]\n :type n: int\n :type left: int\n :type right: int\n :rtype: int\n \"\"\"\n def countUntil(nums, target):\n result, curr, left = 0, 0, 0\n for right in range(len(nums)):\n curr += nums[right]\n while curr > target:\n curr -= nums[left]\n left += 1\n result += right-left+1\n return result\n \n def sumUntil(nums, prefix, target):\n result, curr, total, left = 0, 0, 0, 0\n for right in range(len(nums)):\n curr += nums[right]\n total += nums[right]*(right-left+1)\n while curr > target:\n curr -= nums[left]\n total -= prefix[right+1]-prefix[(left-1)+1]\n left += 1\n result += total\n return result\n \n def sumLessOrEqualTo(prefix, nums, left, right, count):\n while left <= right:\n mid = left + (right-left)//2\n if countUntil(nums, mid)-count >= 0:\n right = mid-1\n else:\n left = mid+1\n return sumUntil(nums, prefix, left)-left*(countUntil(nums, left)-count)\n \n MOD = 10**9+7\n prefix = [0]*(len(nums)+1)\n for i in range(len(nums)):\n prefix[i+1] = prefix[i]+nums[i]\n m, M = min(nums), sum(nums)\n return (sumLessOrEqualTo(prefix, nums, m, M, right) -\n sumLessOrEqualTo(prefix, nums, m, M, left-1))%MOD\n \n\n \n# Time: O(rlogr), worst: O(n^2 * logn)\n# Space: O(n)\nimport heapq\n\n\n# heap solution\nclass Solution2(object):\n def rangeSum(self, nums, n, left, right):\n \"\"\"\n :type nums: List[int]\n :type n: int\n :type left: int\n :type right: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n min_heap = []\n for i, num in enumerate(nums, 1):\n heapq.heappush(min_heap, (num, i))\n result = 0\n for i in range(1, right+1):\n total, j = heapq.heappop(min_heap)\n if i >= left:\n result = (result+total)%MOD\n if j+1 <= n:\n heapq.heappush(min_heap, (total+nums[j], j+1))\n return result\n"}} diff --git a/cp/cp-10912.jsonl b/cp/cp-10912.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..645dec240a4feea9297dcb3b7be37cc8b9ace7b2 --- /dev/null +++ b/cp/cp-10912.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10912", "name": "LeetCode 1509: Minimum Difference Between Largest And Smallest Value In Three Moves"} +{"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: Minimum Difference Between Largest and Smallest Value in Three Moves (Difficulty: Medium)\nTags: Array, Greedy, Sorting\n\nYou are given an integer array nums.\nIn one move, you can choose one element of nums and change it to any value.\nReturn the minimum difference between the largest and smallest value of nums after performing at most three moves.\n\nExample 1:\nInput: nums = [5,3,2,4]\nOutput: 0\nExplanation: We can make at most 3 moves.\nIn the first move, change 2 to 3. nums becomes [5,3,3,4].\nIn the second move, change 4 to 3. nums becomes [5,3,3,3].\nIn the third move, change 5 to 3. nums becomes [3,3,3,3].\nAfter performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.\n\nExample 2:\nInput: nums = [1,5,0,10,14]\nOutput: 1\nExplanation: We can make at most 3 moves.\nIn the first move, change 5 to 0. nums becomes [1,0,0,10,14].\nIn the second move, change 10 to 0. nums becomes [1,0,0,0,14].\nIn the third move, change 14 to 1. nums becomes [1,0,0,0,1].\nAfter performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1.\nIt can be shown that there is no way to make the difference 0 in 3 moves.\n\nExample 3:\nInput: nums = [3,100,20]\nOutput: 0\nExplanation: We can make at most 3 moves.\nIn the first move, change 100 to 7. nums becomes [3,7,20].\nIn the second move, change 20 to 7. nums becomes [3,7,7].\nIn the third move, change 3 to 7. nums becomes [7,7,7].\nAfter performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- -10^9 <= nums[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + klogk)\n# Space: O(k)\n\nimport random\n\n\nclass Solution(object):\n def minDifference(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def nth_element(nums, left, n, right, compare=lambda a, b: a < b):\n def partition_around_pivot(left, right, pivot_idx, nums, compare):\n new_pivot_idx = left\n nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]\n for i in range(left, right):\n if compare(nums[i], nums[right]):\n nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]\n new_pivot_idx += 1\n\n nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]\n return new_pivot_idx\n\n while left <= right:\n pivot_idx = random.randint(left, right)\n new_pivot_idx = partition_around_pivot(left, right, pivot_idx, nums, compare)\n if new_pivot_idx == n:\n return\n elif new_pivot_idx > n:\n right = new_pivot_idx - 1\n else: # new_pivot_idx < n\n left = new_pivot_idx + 1\n\n k = 4\n if len(nums) <= k:\n return 0\n nth_element(nums, 0, k, len(nums)-1)\n nums[:k] = sorted(nums[:k])\n nth_element(nums, k, max(k, len(nums)-k), len(nums)-1)\n nums[-k:] = sorted(nums[-k:])\n return min(nums[-k+i]-nums[i] for i in range(k))\n"}} diff --git a/cp/cp-10913.jsonl b/cp/cp-10913.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d330f91bf37edfc0c3d451faabb5fa0c57157069 --- /dev/null +++ b/cp/cp-10913.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10913", "name": "LeetCode 1510: Stone Game Iv"} +{"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: Stone Game IV (Difficulty: Hard)\nTags: Math, Dynamic Programming, Game Theory\n\nAlice and Bob take turns playing a game, with Alice starting first.\nInitially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.\nAlso, if a player cannot make a move, he/she loses the game.\nGiven a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.\n\nExample 1:\nInput: n = 1\nOutput: true\nExplanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.\n\nExample 2:\nInput: n = 2\nOutput: false\nExplanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).\n\nExample 3:\nInput: n = 4\nOutput: true\nExplanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).\n\nConstraints:\n- 1 <= n <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * sqrt(n))\n# Space: O(n)\n\nclass Solution(object):\n def winnerSquareGame(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n dp = [False]*(n+1)\n for i in range(1, n+1):\n j = 1\n while j*j <= i:\n if not dp[i-j*j]:\n dp[i] = True\n break\n j += 1\n return dp[-1]\n"}} diff --git a/cp/cp-10915.jsonl b/cp/cp-10915.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..696e53f60b55603b289ba5e46d9236b8f7c29d6a --- /dev/null +++ b/cp/cp-10915.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10915", "name": "LeetCode 1513: Number Of Substrings With Only 1S"} +{"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 Substrings With Only 1s (Difficulty: Medium)\nTags: Math, String\n\nGiven a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: s = \"0110111\"\nOutput: 9\nExplanation: There are 9 substring in total with only 1's characters.\n\"1\" -> 5 times.\n\"11\" -> 3 times.\n\"111\" -> 1 time.\n\nExample 2:\nInput: s = \"101\"\nOutput: 2\nExplanation: Substring \"1\" is shown 2 times in s.\n\nExample 3:\nInput: s = \"111111\"\nOutput: 21\nExplanation: Each substring contains only 1's characters.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s[i] is either '0' or '1'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def numSub(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n result, count = 0, 0\n for c in s:\n count = count+1 if c == '1' else 0\n result = (result+count)%MOD\n return result\n"}} diff --git a/cp/cp-10916.jsonl b/cp/cp-10916.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9f5eae471c386190c7805671d5cd96ee84623958 --- /dev/null +++ b/cp/cp-10916.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10916", "name": "LeetCode 1514: Path With Maximum Probability"} +{"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: Path with Maximum Probability (Difficulty: Medium)\nTags: Array, Graph, Heap (Priority Queue), Shortest Path\n\nYou are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].\nGiven two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.\nIf there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.\n\nExample 1:\nInput: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2\nOutput: 0.25000\nExplanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.\n\nExample 2:\nInput: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2\nOutput: 0.30000\n\nExample 3:\nInput: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2\nOutput: 0.00000\nExplanation: There is no path between 0 and 2.\n\nConstraints:\n- 2 <= n <= 10^4\n- 0 <= start, end < n\n- start != end\n- 0 <= a, b < n\n- a != b\n- 0 <= succProb.length == edges.length <= 2*10^4\n- 0 <= succProb[i] <= 1\n- There is at most one edge between every two nodes."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) by using binary heap,\n# if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|)\n# Space: O(|E| + |V|) = O(|E|)\n\nimport collections\nimport itertools\nimport heapq\n\n\nclass Solution(object):\n def maxProbability(self, n, edges, succProb, start, end):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type succProb: List[float]\n :type start: int\n :type end: int\n :rtype: float\n \"\"\"\n adj = collections.defaultdict(list)\n for (u, v), p in itertools.izip(edges, succProb):\n adj[u].append((v, p))\n adj[v].append((u, p))\n max_heap = [(-1.0, start)]\n result, lookup = collections.defaultdict(float), set()\n result[start] = 1.0\n while max_heap and len(lookup) != len(adj):\n curr, u = heapq.heappop(max_heap)\n if u in lookup:\n continue\n lookup.add(u)\n for v, w in adj[u]:\n if v in lookup:\n continue\n if v in result and result[v] >= -curr*w:\n continue\n result[v] = -curr*w\n heapq.heappush(max_heap, (-result[v], v))\n return result[end]\n"}} diff --git a/cp/cp-10917.jsonl b/cp/cp-10917.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9f9c5bfbd0a7f972c91fd5ceec88399508ce0133 --- /dev/null +++ b/cp/cp-10917.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10917", "name": "LeetCode 1515: Best Position For A Service Centre"} +{"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: Best Position for a Service Centre (Difficulty: Hard)\nTags: Array, Math, Geometry, Randomized\n\nA delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum.\nGiven an array positions where positions[i] = [xi, yi] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers.\nIn other words, you need to choose the position of the service center [xcentre, ycentre] such that the following formula is minimized:\nAnswers within 10-5 of the actual value will be accepted.\n\nExample 1:\nInput: positions = [[0,1],[1,0],[1,2],[2,1]]\nOutput: 4.00000\nExplanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.\n\nExample 2:\nInput: positions = [[1,1],[3,3]]\nOutput: 2.82843\nExplanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843\n\nConstraints:\n- 1 <= positions.length <= 50\n- positions[i].length == 2\n- 0 <= xi, yi <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * iter), iter is the number of iterations\n# Space: O(1)\n\n# see reference:\n# - https://en.wikipedia.org/wiki/Geometric_median\n# - https://wikimedia.org/api/rest_v1/media/math/render/svg/b3fb215363358f12687100710caff0e86cd9d26b\n# Weiszfeld's algorithm\nclass Solution(object):\n def getMinDistSum(self, positions):\n \"\"\"\n :type positions: List[List[int]]\n :rtype: float\n \"\"\"\n EPS = 1e-6\n def norm(p1, p2):\n return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5\n \n def geometry_median(positions, median):\n numerator, denominator = [0.0, 0.0], 0.0\n for p in positions:\n l = norm(median, p)\n if not l:\n continue \n numerator[0] += p[0]/l\n numerator[1] += p[1]/l\n denominator += 1/l\n if denominator == 0.0:\n return True, None\n return False, [numerator[0]/denominator, numerator[1]/denominator]\n\n median = [float(sum(p[0] for p in positions))/len(positions),\n float(sum(p[1] for p in positions))/len(positions)]\n prev_median = [float(\"-inf\"), float(\"-inf\")]\n while norm(median, prev_median)*len(positions) > EPS:\n stopped, new_median = geometry_median(positions, median)\n if stopped:\n break\n median, prev_median = new_median, median\n return sum(norm(median, p) for p in positions)\n\n\n# Time: O(n * iter), iter is the number of iterations\n# Space: O(1)\nclass Solution2(object):\n def getMinDistSum(self, positions):\n \"\"\"\n :type positions: List[List[int]]\n :rtype: float\n \"\"\"\n DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n EPS = 1e-6\n def dist(positions, p):\n return sum(((p[0]-x)**2 + (p[1]-y)**2)**0.5 for x, y in positions)\n \n median = [0.0, 0.0]\n median[0] = float(sum(x for x, _ in positions))/len(positions)\n median[1] = float(sum(y for _, y in positions))/len(positions)\n result = dist(positions, median)\n delta = float(max(max(positions, key=lambda x: x[0])[0],\n max(positions, key=lambda x: x[1])[1])) - \\\n float(min(min(positions, key=lambda x: x[0])[0],\n min(positions, key=lambda x: x[1])[1]))\n while delta > EPS:\n for dx, dy in DIRECTIONS:\n new_median = [median[0] + delta*dx, median[1] + delta*dy]\n nd = dist(positions, new_median)\n if nd < result: \n result = nd \n median = new_median\n break \n else:\n delta /= 2.0\n return result \n"}} diff --git a/cp/cp-10919.jsonl b/cp/cp-10919.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b615c0ed9a15b1639d48d5d60923c674c09491fb --- /dev/null +++ b/cp/cp-10919.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10919", "name": "LeetCode 1518: Water Bottles"} +{"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: Water Bottles (Difficulty: Easy)\nTags: Math, Simulation\n\nThere are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.\nThe operation of drinking a full water bottle turns it into an empty bottle.\nGiven the two integers numBottles and numExchange, return the maximum number of water bottles you can drink.\n\nExample 1:\nInput: numBottles = 9, numExchange = 3\nOutput: 13\nExplanation: You can exchange 3 empty bottles to get 1 full water bottle.\nNumber of water bottles you can drink: 9 + 3 + 1 = 13.\n\nExample 2:\nInput: numBottles = 15, numExchange = 4\nOutput: 19\nExplanation: You can exchange 4 empty bottles to get 1 full water bottle. \nNumber of water bottles you can drink: 15 + 3 + 1 = 19.\n\nConstraints:\n- 1 <= numBottles <= 100\n- 2 <= numExchange <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn/logm), n is numBottles, m is numExchange\n# Space: O(1)\n\nclass Solution(object):\n def numWaterBottles(self, numBottles, numExchange):\n \"\"\"\n :type numBottles: int\n :type numExchange: int\n :rtype: int\n \"\"\"\n result = numBottles\n while numBottles >= numExchange:\n numBottles, remainder = divmod(numBottles, numExchange)\n result += numBottles\n numBottles += remainder\n return result\n"}} diff --git a/cp/cp-10920.jsonl b/cp/cp-10920.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2d4b3a0755a1545ea89d7355aa23e3c0553a5f7f --- /dev/null +++ b/cp/cp-10920.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10920", "name": "LeetCode 1519: Number Of Nodes In The Sub Tree With The Same Label"} +{"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 Nodes in the Sub-Tree With the Same Label (Difficulty: Medium)\nTags: Hash Table, Tree, Depth-First Search, Breadth-First Search, Counting\n\nYou are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]).\nThe edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree.\nReturn an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i.\nA subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.\n\nExample 1:\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = \"abaedcd\"\nOutput: [2,1,1,1,1,1,1]\nExplanation: Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.\nNode 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).\n\nExample 2:\nInput: n = 4, edges = [[0,1],[1,2],[0,3]], labels = \"bbbb\"\nOutput: [4,2,1,1]\nExplanation: The sub-tree of node 2 contains only node 2, so the answer is 1.\nThe sub-tree of node 3 contains only node 3, so the answer is 1.\nThe sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.\nThe sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.\n\nExample 3:\nInput: n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = \"aabab\"\nOutput: [3,2,1,1,1]\n\nConstraints:\n- 1 <= n <= 10^5\n- edges.length == n - 1\n- edges[i].length == 2\n- 0 <= ai, bi < n\n- ai != bi\n- labels.length == n\n- labels is consisting of only of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nclass Solution(object):\n def countSubTrees(self, n, edges, labels):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type labels: str\n :rtype: List[int]\n \"\"\"\n def iter_dfs(labels, adj, node, parent, result):\n stk = [(1, (node, parent, [0]*26))]\n while stk:\n step, params = stk.pop()\n if step == 1:\n node, parent, ret = params\n stk.append((4, (node, ret)))\n stk.append((2, (node, parent, reversed(adj[node]), ret)))\n elif step == 2:\n node, parent, it, ret = params\n child = next(it, None)\n if not child or child == parent:\n continue\n ret2 = [0]*26\n stk.append((2, (node, parent, it, ret)))\n stk.append((3, (ret2, ret)))\n stk.append((1, (child, node, ret2)))\n elif step == 3:\n ret2, ret = params\n for k in range(len(ret2)):\n ret[k] += ret2[k]\n else:\n node, ret = params\n ret[ord(labels[node]) - ord('a')] += 1\n result[node] += ret[ord(labels[node]) - ord('a')]\n \n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n result = [0]*n\n iter_dfs(labels, adj, 0, -1, result)\n return result\n\n\n# Time: O(n)\n# Space: O(h)\nimport collections\n\n\nclass Solution2(object):\n def countSubTrees(self, n, edges, labels):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type labels: str\n :rtype: List[int]\n \"\"\"\n def dfs(labels, adj, node, parent, result):\n count = [0]*26\n for child in adj[node]:\n if child == parent:\n continue\n new_count = dfs(labels, adj, child, node, result)\n for k in range(len(new_count)):\n count[k] += new_count[k]\n count[ord(labels[node]) - ord('a')] += 1\n result[node] = count[ord(labels[node]) - ord('a')]\n return count\n \n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n result = [0]*n\n dfs(labels, adj, 0, -1, result)\n return result\n"}} diff --git a/cp/cp-10921.jsonl b/cp/cp-10921.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4080fc1e09eadf0a3962e307b8a71aaf243088f4 --- /dev/null +++ b/cp/cp-10921.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10921", "name": "LeetCode 1520: Maximum Number Of Non Overlapping 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: Maximum Number of Non-Overlapping Substrings (Difficulty: Hard)\nTags: String, Greedy\n\nGiven a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions:\nFind the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length.\nNotice that you can return the substrings in any order.\n\nExample 1:\nInput: s = \"adefaddaccc\"\nOutput: [\"e\",\"f\",\"ccc\"]\nExplanation: The following are all the possible substrings that meet the conditions:\n[\n  \"adefaddaccc\"\n  \"adefadda\",\n  \"ef\",\n  \"e\",\n \"f\",\n  \"ccc\",\n]\nIf we choose the first string, we cannot choose anything else and we'd get only 1. If we choose \"adefadda\", we are left with \"ccc\" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose \"ef\" since it can be split into two. Therefore, the optimal way is to choose [\"e\",\"f\",\"ccc\"] which gives us 3 substrings. No other solution of the same number of substrings exist.\n\nExample 2:\nInput: s = \"abbaccd\"\nOutput: [\"d\",\"bb\",\"cc\"]\nExplanation: Notice that while the set of substrings [\"d\",\"abba\",\"cc\"] also has length 3, it's considered incorrect since it has larger total length.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s contains only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# space: O(1)\n\nclass Solution(object):\n def maxNumOfSubstrings(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n def find_right_from_left(s, first, last, left):\n right, i = last[ord(s[left])-ord('a')], left\n while i <= right:\n if first[ord(s[i])-ord('a')] < left:\n return -1\n right = max(right, last[ord(s[i])-ord('a')])\n i += 1\n return right\n \n first, last = [float(\"inf\")]*26, [float(\"-inf\")]*26\n for i, c in enumerate(s):\n first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)\n last[ord(c)-ord('a')] = max(last[ord(c)-ord('a')], i)\n result = [\"\"]\n right = float(\"inf\")\n for left, c in enumerate(s):\n if left != first[ord(c)-ord('a')]:\n continue\n new_right = find_right_from_left(s, first, last, left)\n if new_right == -1:\n continue\n if left > right:\n result.append(\"\")\n right = new_right\n result[-1] = s[left:right+1]\n return result\n\n\n# Time: O(n)\n# space: O(1)\nclass Solution2(object):\n def maxNumOfSubstrings(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n def find_right_from_left(s, first, last, left):\n right, i = last[ord(s[left])-ord('a')], left\n while i <= right:\n if first[ord(s[i])-ord('a')] < left:\n return -1\n right = max(right, last[ord(s[i])-ord('a')])\n i += 1\n return right\n\n first, last = [float(\"inf\")]*26, [float(\"-inf\")]*26\n for i, c in enumerate(s):\n first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)\n last[ord(c)-ord('a')] = max(last[ord(c)-ord('a')], i)\n intervals = []\n for c in range(len(first)):\n if first[c] == float(\"inf\"):\n continue\n left, right = first[c], find_right_from_left(s, first, last, first[c])\n if right != -1:\n intervals.append((right, left))\n intervals.sort() # Time: O(26log26)\n result, prev = [], -1\n for right, left in intervals:\n if left <= prev:\n continue\n result.append(s[left:right+1])\n prev = right\n return result\n"}} diff --git a/cp/cp-10922.jsonl b/cp/cp-10922.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3b3ec19b7ba45c72496ca547e4b203c375605575 --- /dev/null +++ b/cp/cp-10922.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10922", "name": "LeetCode 1521: Find A Value Of A Mysterious Function Closest To Target"} +{"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 a Value of a Mysterious Function Closest to Target (Difficulty: Hard)\nTags: Array, Binary Search, Bit Manipulation, Segment Tree\n\nWinston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible.\nReturn the minimum possible value of |func(arr, l, r) - target|.\nNotice that func should be called with the values l and r where 0 <= l, r < arr.length.\n\nExample 1:\nInput: arr = [9,12,3,7,15], target = 5\nOutput: 2\nExplanation: Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.\n\nExample 2:\nInput: arr = [1000000,1000000,1000000], target = 1\nOutput: 999999\nExplanation: Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.\n\nExample 3:\nInput: arr = [1,2,4,8,16], target = 0\nOutput: 0\n\nConstraints:\n- 1 <= arr.length <= 10^5\n- 1 <= arr[i] <= 10^6\n- 0 <= target <= 10^7"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogm), m is the max value of arr\n# Space: O(logm)\n\nclass BitCount(object):\n def __init__(self, n):\n self.__l = 0\n self.__n = n\n self.__count = [0]*n\n \n def __iadd__(self, num):\n self.__l += 1\n base = 1\n for i in range(self.__n):\n if num&base:\n self.__count[i] += 1\n base <<= 1\n return self\n\n def __isub__(self, num):\n self.__l -= 1\n base = 1\n for i in range(self.__n):\n if num&base:\n self.__count[i] -= 1\n base <<= 1\n return self\n \n def bit_and(self):\n num, base = 0, 1\n for i in range(self.__n):\n if self.__count[i] == self.__l:\n num |= base\n base <<= 1\n return num\n\n\nclass Solution(object):\n def closestToTarget(self, arr, target):\n \"\"\"\n :type arr: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n count = BitCount(max(arr).bit_length())\n result, left = float(\"inf\"), 0\n for right in range(len(arr)):\n count += arr[right]\n while left <= right:\n f = count.bit_and()\n result = min(result, abs(f-target))\n if f >= target:\n break\n count -= arr[left]\n left += 1\n return result\n \n \n# Time: O(nlogm), m is the max value of arr\n# Space: O(logm)\nclass Solution2(object):\n def closestToTarget(self, arr, target):\n \"\"\"\n :type arr: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n result, dp = float(\"inf\"), set() # at most O(logm) dp states\n for x in arr:\n dp = {x}|{f&x for f in dp}\n for f in dp:\n result = min(result, abs(f-target))\n return result\n"}} diff --git a/cp/cp-10925.jsonl b/cp/cp-10925.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7040e02ada53191bdb2868513f868986fa731ce7 --- /dev/null +++ b/cp/cp-10925.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10925", "name": "LeetCode 1524: Number Of Sub Arrays With Odd Sum"} +{"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 Sub-arrays With Odd Sum (Difficulty: Medium)\nTags: Array, Math, Dynamic Programming, Prefix Sum\n\nGiven an array of integers arr, return the number of subarrays with an odd sum.\nSince the answer can be very large, return it modulo 109 + 7.\n\nExample 1:\nInput: arr = [1,3,5]\nOutput: 4\nExplanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]\nAll sub-arrays sum are [1,4,9,3,8,5].\nOdd sums are [1,9,3,5] so the answer is 4.\n\nExample 2:\nInput: arr = [2,4,6]\nOutput: 0\nExplanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]\nAll sub-arrays sum are [2,6,12,4,10,6].\nAll sub-arrays have even sum and the answer is 0.\n\nExample 3:\nInput: arr = [1,2,3,4,5,6,7]\nOutput: 16\n\nConstraints:\n- 1 <= arr.length <= 10^5\n- 1 <= arr[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def numOfSubarrays(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n result, accu = 0, 0\n dp = [1, 0]\n for x in arr:\n accu ^= x&1\n dp[accu] += 1\n result = (result + dp[accu^1]) % MOD\n return result\n"}} diff --git a/cp/cp-10926.jsonl b/cp/cp-10926.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8c5096250db7e4fc7d6cf2370144c787354e8dda --- /dev/null +++ b/cp/cp-10926.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10926", "name": "LeetCode 1525: Number Of Good Ways To Split A 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: Number of Good Ways to Split a String (Difficulty: Medium)\nTags: Hash Table, String, Dynamic Programming, Bit Manipulation\n\nYou are given a string s.\nA split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same.\nReturn the number of good splits you can make in s.\n\nExample 1:\nInput: s = \"aacaba\"\nOutput: 2\nExplanation: There are 5 ways to split \"aacaba\" and 2 of them are good. \n(\"a\", \"acaba\") Left string and right string contains 1 and 3 different letters respectively.\n(\"aa\", \"caba\") Left string and right string contains 1 and 3 different letters respectively.\n(\"aac\", \"aba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n(\"aaca\", \"ba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n(\"aacab\", \"a\") Left string and right string contains 3 and 1 different letters respectively.\n\nExample 2:\nInput: s = \"abcd\"\nOutput: 1\nExplanation: Split the string as follows (\"ab\", \"cd\").\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s consists of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def numSplits(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n left_count, right_count = collections.Counter(), collections.Counter(s)\n result = 0\n for c in s:\n left_count[c] += 1\n right_count[c] -= 1\n if not right_count[c]:\n del right_count[c]\n if len(left_count) == len(right_count):\n result += 1\n return result\n"}} diff --git a/cp/cp-10927.jsonl b/cp/cp-10927.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..baf83fc8ead4fd78b1ec502d5e657f5172099db8 --- /dev/null +++ b/cp/cp-10927.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10927", "name": "LeetCode 1526: Minimum Number Of Increments On Subarrays To Form A Target 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: Minimum Number of Increments on Subarrays to Form a Target Array (Difficulty: Hard)\nTags: Array, Dynamic Programming, Stack, Greedy, Monotonic Stack\n\nYou are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.\nIn one operation you can choose any subarray from initial and increment each value by one.\nReturn the minimum number of operations to form a target array from initial.\nThe test cases are generated so that the answer fits in a 32-bit integer.\n\nExample 1:\nInput: target = [1,2,3,2,1]\nOutput: 3\nExplanation: We need at least 3 operations to form the target array from the initial array.\n[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).\n[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).\n[1,2,2,2,1] increment 1 at index 2.\n[1,2,3,2,1] target array is formed.\n\nExample 2:\nInput: target = [3,1,1,2]\nOutput: 4\nExplanation: [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]\n\nExample 3:\nInput: target = [3,1,5,4,2]\nOutput: 7\nExplanation: [0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].\n\nConstraints:\n- 1 <= target.length <= 10^5\n- 1 <= target[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minNumberOperations(self, target):\n \"\"\"\n :type target: List[int]\n :rtype: int\n \"\"\"\n return sum(max((target[i] if i < len(target) else 0)-(target[i-1] if i-1 >= 0 else 0), 0) for i in range(len(target)+1))\n"}} diff --git a/cp/cp-10928.jsonl b/cp/cp-10928.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9fc2eb8fc196ce572d2ff144e4b8de7e4d78d4de --- /dev/null +++ b/cp/cp-10928.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10928", "name": "LeetCode 1528: Shuffle 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: Shuffle String (Difficulty: Easy)\nTags: Array, String\n\nYou are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.\nReturn the shuffled string.\n\nExample 1:\nInput: s = \"codeleet\", indices = [4,5,6,7,0,2,1,3]\nOutput: \"leetcode\"\nExplanation: As shown, \"codeleet\" becomes \"leetcode\" after shuffling.\n\nExample 2:\nInput: s = \"abc\", indices = [0,1,2]\nOutput: \"abc\"\nExplanation: After shuffling, each character remains in its position.\n\nConstraints:\n- s.length == indices.length == n\n- 1 <= n <= 100\n- s consists of only lowercase English letters.\n- 0 <= indices[i] < n\n- All values of indices are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# in-place solution\nclass Solution(object):\n def restoreString(self, s, indices):\n \"\"\"\n :type s: str\n :type indices: List[int]\n :rtype: str\n \"\"\"\n result = list(s)\n for i, c in enumerate(result):\n if indices[i] == i:\n continue\n move, j = c, indices[i]\n while j != i:\n result[j], move = move, result[j]\n indices[j], j = j, indices[j]\n result[i] = move\n return \"\".join(result)\n\n\n# Time: O(n)\n# Space: O(1)\nimport itertools\n\n\nclass Solution2(object):\n def restoreString(self, s, indices):\n \"\"\"\n :type s: str\n :type indices: List[int]\n :rtype: str\n \"\"\"\n result = ['']*len(s)\n for i, c in itertools.izip(indices, s):\n result[i] = c\n return \"\".join(result)\n"}} diff --git a/cp/cp-10930.jsonl b/cp/cp-10930.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..01f235241539ea46ef4388e4e193e3478cfd7ee6 --- /dev/null +++ b/cp/cp-10930.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10930", "name": "LeetCode 1530: Number Of Good Leaf Nodes 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: Number of Good Leaf Nodes Pairs (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Tree\n\nYou are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.\nReturn the number of good leaf node pairs in the tree.\n\nExample 1:\nInput: root = [1,2,3,null,4], distance = 3\nOutput: 1\nExplanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.\n\nExample 2:\nInput: root = [1,2,3,4,5,6,7], distance = 3\nOutput: 2\nExplanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.\n\nExample 3:\nInput: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3\nOutput: 1\nExplanation: The only good pair is [2,5].\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 210].\n- 1 <= Node.val <= 100\n- 1 <= distance <= 10"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nimport collections\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution(object):\n def countPairs(self, root, distance):\n \"\"\"\n :type root: TreeNode\n :type distance: int\n :rtype: int\n \"\"\"\n def iter_dfs(distance, root):\n result = 0\n stk = [(1, (root, [collections.Counter()]))]\n while stk:\n step, params = stk.pop()\n if step == 1:\n node, ret = params\n if not node:\n continue\n if not node.left and not node.right:\n ret[0][0] = 1\n continue\n left, right = [collections.Counter()], [collections.Counter()]\n stk.append((2, (left, right, ret)))\n stk.append((1, (node.right, right)))\n stk.append((1, (node.left, left)))\n else:\n left, right, ret = params\n for left_d, left_c in left[0].iteritems():\n for right_d,right_c in right[0].iteritems():\n if left_d+right_d+2 <= distance:\n result += left_c*right_c\n ret[0] = collections.Counter({k+1:v for k,v in (left[0]+right[0]).iteritems()})\n return result\n \n return iter_dfs(distance, root)\n\n\n# Time: O(n)\n# Space: O(h)\nimport collections\n\n\nclass Solution2(object):\n def countPairs(self, root, distance):\n \"\"\"\n :type root: TreeNode\n :type distance: int\n :rtype: int\n \"\"\"\n def dfs(distance, node):\n if not node:\n return 0, collections.Counter()\n if not node.left and not node.right:\n return 0, collections.Counter([0])\n left, right = dfs(distance, node.left), dfs(distance, node.right)\n result = left[0]+right[0]\n for left_d, left_c in left[1].iteritems():\n for right_d,right_c in right[1].iteritems():\n if left_d+right_d+2 <= distance:\n result += left_c*right_c\n return result, collections.Counter({k+1:v for k,v in (left[1]+right[1]).iteritems()})\n \n return dfs(distance, root)[0]\n"}} diff --git a/cp/cp-10931.jsonl b/cp/cp-10931.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..08ea2af0aebcc03c532901e675d2d67b051a09ce --- /dev/null +++ b/cp/cp-10931.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10931", "name": "LeetCode 1531: String Compression 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: String Compression II (Difficulty: Hard)\nTags: String, Dynamic Programming\n\nRun-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string \"aabccc\" we replace \"aa\" by \"a2\" and replace \"ccc\" by \"c3\". Thus the compressed string becomes \"a2bc3\".\nNotice that in this problem, we are not adding '1' after single characters.\nGiven a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.\nFind the minimum length of the run-length encoded version of s after deleting at most k characters.\n\nExample 1:\nInput: s = \"aaabcccd\", k = 2\nOutput: 4\nExplanation: Compressing s without deleting anything will give us \"a3bc3d\" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = \"abcccd\" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be \"a3c3\" of length 4.\n\nExample 2:\nInput: s = \"aabbaa\", k = 2\nOutput: 2\nExplanation: If we delete both 'b' characters, the resulting compressed string would be \"a4\" of length 2.\n\nExample 3:\nInput: s = \"aaaaaaaaaaa\", k = 0\nOutput: 3\nExplanation: Since k is zero, we cannot delete anything. The compressed string is \"a11\" of length 3.\n\nConstraints:\n- 1 <= s.length <= 100\n- 0 <= k <= s.length\n- s contains only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2 * k)\n# Space: O(n * k)\n\nclass Solution(object):\n def getLengthOfOptimalCompression(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: int\n \"\"\"\n def length(cnt):\n l = 2 if cnt >= 2 else 1\n while cnt >= 10:\n l += 1\n cnt //= 10\n return l\n\n dp = [[len(s)]*(k+1) for _ in range(len(s)+1)]\n dp[0][0] = 0\n for i in range(1, len(s)+1):\n for j in range(k+1):\n if i-1 >= 0 and j-1 >= 0:\n dp[i][j] = min(dp[i][j], dp[i-1][j-1])\n keep = delete = 0\n for m in range(i, len(s)+1):\n if s[i-1] == s[m-1]:\n keep += 1\n else:\n delete += 1\n if j+delete <= k:\n dp[m][j+delete] = min(dp[m][j+delete], dp[i-1][j]+length(keep))\n return dp[len(s)][k]\n"}} diff --git a/cp/cp-10933.jsonl b/cp/cp-10933.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..478d1f616d43f3551211d188e8f233e000fa40fc --- /dev/null +++ b/cp/cp-10933.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10933", "name": "LeetCode 1534: Count Good Triplets"} +{"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: Count Good Triplets (Difficulty: Easy)\nTags: Array, Enumeration\n\nGiven an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.\nA triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:\nWhere |x| denotes the absolute value of x.\nReturn the number of good triplets.\n\nExample 1:\nInput: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3\r\nOutput: 4\r\nExplanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].\n\nExample 2:\nInput: arr = [1,1,2,2,3], a = 0, b = 0, c = 1\r\nOutput: 0\r\nExplanation: No triplet satisfies all conditions.\n\nConstraints:\n- 3 <= arr.length <= 100\n- 0 <= arr[i] <= 1000\n- 0 <= a, b, c <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(1)\n\nclass Solution(object):\n def countGoodTriplets(self, arr, a, b, c):\n \"\"\"\n :type arr: List[int]\n :type a: int\n :type b: int\n :type c: int\n :rtype: int\n \"\"\"\n return sum(abs(arr[i]-arr[j]) <= a and\n abs(arr[j]-arr[k]) <= b and\n abs(arr[k]-arr[i]) <= c \n for i in range(len(arr)-2)\n for j in range(i+1, len(arr)-1)\n for k in range(j+1, len(arr)))\n \n"}} diff --git a/cp/cp-10934.jsonl b/cp/cp-10934.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b59fd5ad4d58748e6b67b4f48715145da52184f1 --- /dev/null +++ b/cp/cp-10934.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10934", "name": "LeetCode 1535: Find The Winner Of An Array Game"} +{"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 the Winner of an Array Game (Difficulty: Medium)\nTags: Array, Simulation\n\nGiven an integer array arr of distinct integers and an integer k.\nA game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0, and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds.\nReturn the integer which will win the game.\nIt is guaranteed that there will be a winner of the game.\n\nExample 1:\nInput: arr = [2,1,3,5,4,6,7], k = 2\nOutput: 5\nExplanation: Let's see the rounds of the game:\nRound | arr | winner | win_count\n 1 | [2,1,3,5,4,6,7] | 2 | 1\n 2 | [2,3,5,4,6,7,1] | 3 | 1\n 3 | [3,5,4,6,7,1,2] | 5 | 1\n 4 | [5,4,6,7,1,2,3] | 5 | 2\nSo we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.\n\nExample 2:\nInput: arr = [3,2,1], k = 10\nOutput: 3\nExplanation: 3 will win the first 10 rounds consecutively.\n\nConstraints:\n- 2 <= arr.length <= 10^5\n- 1 <= arr[i] <= 10^6\n- arr contains distinct integers.\n- 1 <= k <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def getWinner(self, arr, k):\n \"\"\"\n :type arr: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n result = arr[0]\n count = 0\n for i in range(1, len(arr)):\n if arr[i] > result:\n result = arr[i]\n count = 0\n count += 1\n if (count == k):\n break\n return result\n"}} diff --git a/cp/cp-10935.jsonl b/cp/cp-10935.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f00c5175355509ef71561bf788640999b0290e0d --- /dev/null +++ b/cp/cp-10935.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10935", "name": "LeetCode 1536: Minimum Swaps To Arrange A Binary Grid"} +{"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: Minimum Swaps to Arrange a Binary Grid (Difficulty: Medium)\nTags: Array, Greedy, Matrix\n\nGiven an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.\nA grid is said to be valid if all the cells above the main diagonal are zeros.\nReturn the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.\nThe main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).\n\nExample 1:\nInput: grid = [[0,0,1],[1,1,0],[1,0,0]]\nOutput: 3\n\nExample 2:\nInput: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]\nOutput: -1\nExplanation: All rows are similar, swaps have no effect on the grid.\n\nExample 3:\nInput: grid = [[1,0,0],[1,1,0],[1,1,1]]\nOutput: 0\n\nConstraints:\n- n == grid.length == grid[i].length\n- 1 <= n <= 200\n- grid[i][j] is either 0 or 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def minSwaps(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n result = 0\n for target in reversed(range(1, len(grid))):\n row_idx = len(grid)-1-target\n while row_idx < len(grid):\n row = grid[row_idx]\n if not sum(itertools.islice(row, len(row)-target, len(row))):\n break\n row_idx += 1\n else:\n return -1\n while row_idx != len(grid)-1-target:\n grid[row_idx], grid[row_idx-1] = grid[row_idx-1], grid[row_idx]\n result += 1\n row_idx -= 1\n return result\n"}} diff --git a/cp/cp-10936.jsonl b/cp/cp-10936.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bc2d0be892881f1da26aaaea587df093f49be6ea --- /dev/null +++ b/cp/cp-10936.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10936", "name": "LeetCode 1537: Get The Maximum Score"} +{"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: Get the Maximum Score (Difficulty: Hard)\nTags: Array, Two Pointers, Dynamic Programming, Greedy\n\nYou are given two sorted arrays of distinct integers nums1 and nums2.\nA valid path is defined as follows:\nThe score is defined as the sum of unique values in a valid path.\nReturn the maximum score you can obtain of all possible valid paths. Since the answer may be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]\nOutput: 30\nExplanation: Valid paths:\n[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)\n[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)\nThe maximum is obtained with the path in green [2,4,6,8,10].\n\nExample 2:\nInput: nums1 = [1,3,5,7,9], nums2 = [3,5,100]\nOutput: 109\nExplanation: Maximum sum is obtained with the path [1,3,5,100].\n\nExample 3:\nInput: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]\nOutput: 40\nExplanation: There are no common elements between nums1 and nums2.\nMaximum sum is obtained with the path [6,7,8,9,10].\n\nConstraints:\n- 1 <= nums1.length, nums2.length <= 10^5\n- 1 <= nums1[i], nums2[i] <= 10^7\n- nums1 and nums2 are strictly increasing."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n)\n# Space: O(1)\n\nclass Solution(object):\n def maxSum(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n i, j = 0, 0\n result, sum1, sum2 = 0, 0, 0,\n while i != len(nums1) or j != len(nums2):\n if i != len(nums1) and (j == len(nums2) or nums1[i] < nums2[j]):\n sum1 += nums1[i]\n i += 1\n elif j != len(nums2) and (i == len(nums1) or nums1[i] > nums2[j]):\n sum2 += nums2[j]\n j += 1\n else:\n result = (result + (max(sum1, sum2) + nums1[i])) % MOD\n sum1, sum2 = 0, 0\n i += 1\n j += 1\n return (result + max(sum1, sum2)) % MOD\n"}} diff --git a/cp/cp-10938.jsonl b/cp/cp-10938.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4a0f319b8daa012b55319b7755ed7fa0c77484f0 --- /dev/null +++ b/cp/cp-10938.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10938", "name": "LeetCode 1539: Kth Missing Positive 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: Kth Missing Positive Number (Difficulty: Easy)\nTags: Array, Binary Search\n\nGiven an array arr of positive integers sorted in a strictly increasing order, and an integer k.\nReturn the kth positive integer that is missing from this array.\nFollow up:\nCould you solve this problem in less than O(n) complexity?\n\nExample 1:\nInput: arr = [2,3,4,7,11], k = 5\nOutput: 9\nExplanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.\n\nExample 2:\nInput: arr = [1,2,3,4], k = 2\nOutput: 6\nExplanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.\n\nConstraints:\n- 1 <= arr.length <= 1000\n- 1 <= arr[i] <= 1000\n- 1 <= k <= 1000\n- arr[i] < arr[j] for 1 <= i < j <= arr.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nclass Solution(object):\n def findKthPositive(self, arr, k):\n \"\"\"\n :type arr: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n def check(arr, k, x):\n return arr[x]-(x+1) < k\n\n left, right = 0, len(arr)-1\n while left <= right:\n mid = left + (right-left)//2\n if not check(arr, k, mid):\n right = mid-1\n else:\n left = mid+1\n return right+1+k # arr[right] + (k-(arr[right]-(right+1))) if right >= 0 else k\n"}} diff --git a/cp/cp-10939.jsonl b/cp/cp-10939.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..699642d3593d520a68dc7d25e3067c721517b0b5 --- /dev/null +++ b/cp/cp-10939.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10939", "name": "LeetCode 1540: Can Convert String In K Moves"} +{"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 Convert String in K Moves (Difficulty: Medium)\nTags: Hash Table, String\n\nGiven two strings s and t, your goal is to convert s into t in k moves or less.\nDuring the ith (1 <= i <= k) move you can:\nShifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Shifting a character by i means applying the shift operations i times.\nRemember that any index j can be picked at most once.\nReturn true if it's possible to convert s into t in no more than k moves, otherwise return false.\n\nExample 1:\nInput: s = \"input\", t = \"ouput\", k = 9\nOutput: true\nExplanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.\n\nExample 2:\nInput: s = \"abc\", t = \"bcd\", k = 10\nOutput: false\nExplanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.\n\nExample 3:\nInput: s = \"aab\", t = \"bbb\", k = 27\nOutput: true\nExplanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.\n\nConstraints:\n- 1 <= s.length, t.length <= 10^5\n- 0 <= k <= 10^9\n- s, t contain only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def canConvertString(self, s, t, k):\n \"\"\"\n :type s: str\n :type t: str\n :type k: int\n :rtype: bool\n \"\"\"\n if len(s) != len(t):\n return False\n cnt = [0]*26\n for a, b in itertools.izip(s, t):\n diff = (ord(b)-ord(a)) % len(cnt)\n if diff != 0 and cnt[diff]*len(cnt) + diff > k:\n return False\n cnt[diff] += 1\n return True\n"}} diff --git a/cp/cp-10940.jsonl b/cp/cp-10940.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8eb419c508b989c4aa451542228549b851093edd --- /dev/null +++ b/cp/cp-10940.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10940", "name": "LeetCode 1541: Minimum Insertions To Balance A Parentheses 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: Minimum Insertions to Balance a Parentheses String (Difficulty: Medium)\nTags: String, Stack, Greedy\n\nGiven a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:\nIn other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis.\nYou can insert the characters '(' and ')' at any position of the string to balance it if needed.\nReturn the minimum number of insertions needed to make s balanced.\n\nExample 1:\nInput: s = \"(()))\"\nOutput: 1\nExplanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be \"(())))\" which is balanced.\n\nExample 2:\nInput: s = \"())\"\nOutput: 0\nExplanation: The string is already balanced.\n\nExample 3:\nInput: s = \"))())(\"\nOutput: 3\nExplanation: Add '(' to match the first '))', Add '))' to match the last '('.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s consists of '(' and ')' only."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minInsertions(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n add, bal = 0, 0\n for c in s:\n if c == '(':\n if bal > 0 and bal%2:\n add += 1\n bal -= 1\n bal += 2\n else:\n bal -= 1\n if bal < 0:\n add += 1\n bal += 2\n return add + bal\n"}} diff --git a/cp/cp-10941.jsonl b/cp/cp-10941.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1fe62291235b7498d2f3faf3eaecd9440c60bd48 --- /dev/null +++ b/cp/cp-10941.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10941", "name": "LeetCode 1542: Find Longest Awesome Substring"} +{"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 Longest Awesome Substring (Difficulty: Hard)\nTags: Hash Table, String, Bit Manipulation\n\nYou are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome.\nReturn the length of the maximum length awesome substring of s.\n\nExample 1:\nInput: s = \"3242415\"\nOutput: 5\nExplanation: \"24241\" is the longest awesome substring, we can form the palindrome \"24142\" with some swaps.\n\nExample 2:\nInput: s = \"12345678\"\nOutput: 1\n\nExample 3:\nInput: s = \"213123\"\nOutput: 6\nExplanation: \"213123\" is the longest awesome substring, we can form the palindrome \"231132\" with some swaps.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s consists only of digits."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(10 * n)\n# Space: O(1024)\n\nclass Solution(object):\n def longestAwesome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n ALPHABET_SIZE = 10\n result, mask, lookup = 0, 0, [len(s)]*(2**ALPHABET_SIZE)\n lookup[0] = -1\n for i, ch in enumerate(s):\n mask ^= 2**(ord(ch)-ord('0'))\n if lookup[mask] == len(s):\n lookup[mask] = i\n result = max(result, i - lookup[mask])\n for d in range(ALPHABET_SIZE):\n result = max(result, i - lookup[mask^(2**d)])\n return result\n"}} diff --git a/cp/cp-10942.jsonl b/cp/cp-10942.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b6dba6dd46039b127382b33aa2acc960900bb372 --- /dev/null +++ b/cp/cp-10942.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10942", "name": "LeetCode 1544: Make The String Great"} +{"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: Make The String Great (Difficulty: Easy)\nTags: String, Stack\n\nGiven a string s of lower and upper case English letters.\nA good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:\nTo make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.\nReturn the string after making it good. The answer is guaranteed to be unique under the given constraints.\nNotice that an empty string is also good.\n\nExample 1:\nInput: s = \"leEeetcode\"\nOutput: \"leetcode\"\nExplanation: In the first step, either you choose i = 1 or i = 2, both will result \"leEeetcode\" to be reduced to \"leetcode\".\n\nExample 2:\nInput: s = \"abBAcC\"\nOutput: \"\"\nExplanation: We have many possible scenarios, and all lead to the same answer. For example:\n\"abBAcC\" --> \"aAcC\" --> \"cC\" --> \"\"\n\"abBAcC\" --> \"abBA\" --> \"aA\" --> \"\"\n\nExample 3:\nInput: s = \"s\"\nOutput: \"s\"\n\nConstraints:\n- 1 <= s.length <= 100\n- s contains only lower and upper case English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def makeGood(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n stk = []\n for ch in s:\n counter_ch = ch.upper() if ch.islower() else ch.lower()\n if stk and stk[-1] == counter_ch:\n stk.pop()\n else:\n stk.append(ch)\n return \"\".join(stk)\n"}} diff --git a/cp/cp-10943.jsonl b/cp/cp-10943.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..02dad07740c642979d575d09f069cfa9b085449d --- /dev/null +++ b/cp/cp-10943.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10943", "name": "LeetCode 1545: Find Kth Bit In Nth Binary 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: Find Kth Bit in Nth Binary String (Difficulty: Medium)\nTags: String, Recursion, Simulation\n\nGiven two positive integers n and k, the binary string Sn is formed as follows:\nWhere + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).\nFor example, the first four strings in the above sequence are:\nReturn the kth bit in Sn. It is guaranteed that k is valid for the given n.\n\nExample 1:\nInput: n = 3, k = 1\nOutput: \"0\"\nExplanation: S3 is \"0111001\".\nThe 1st bit is \"0\".\n\nExample 2:\nInput: n = 4, k = 11\nOutput: \"1\"\nExplanation: S4 is \"011100110110001\".\nThe 11th bit is \"1\".\n\nConstraints:\n- 1 <= n <= 20\n- 1 <= k <= 2n - 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def findKthBit(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n flip, l = 0, 2**n-1\n while k > 1:\n if k == l//2+1:\n flip ^= 1\n break\n if k > l//2:\n k = l+1-k\n flip ^= 1\n l //= 2\n return str(flip)\n"}} diff --git a/cp/cp-10944.jsonl b/cp/cp-10944.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4d2084216553f3dade828eed26f0dd339724d3ad --- /dev/null +++ b/cp/cp-10944.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10944", "name": "LeetCode 1546: Maximum Number Of Non Overlapping Subarrays With Sum Equals Target"} +{"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 Number of Non-Overlapping Subarrays With Sum Equals Target (Difficulty: Medium)\nTags: Array, Hash Table, Greedy, Prefix Sum\n\nGiven an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.\n\nExample 1:\nInput: nums = [1,1,1,1,1], target = 2\nOutput: 2\nExplanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).\n\nExample 2:\nInput: nums = [-1,3,5,1,4,2,-9], target = 6\nOutput: 2\nExplanation: There are 3 subarrays with sum equal to 6.\n([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- -10^4 <= nums[i] <= 10^4\n- 0 <= target <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def maxNonOverlapping(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n lookup = {0:-1}\n result, accu, right = 0, 0, -1\n for i, num in enumerate(nums):\n accu += num\n if accu-target in lookup and lookup[accu-target] >= right:\n right = i\n result += 1 # greedy\n lookup[accu] = i\n return result\n"}} diff --git a/cp/cp-10945.jsonl b/cp/cp-10945.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2f847fa17f6cbf5204b714bcfc4ecad56e57499a --- /dev/null +++ b/cp/cp-10945.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10945", "name": "LeetCode 1547: Minimum Cost To Cut A Stick"} +{"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: Minimum Cost to Cut a Stick (Difficulty: Hard)\nTags: Array, Dynamic Programming, Sorting\n\nGiven a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows:\nGiven an integer array cuts where cuts[i] denotes a position you should perform a cut at.\nYou should perform the cuts in order, you can change the order of the cuts as you wish.\nThe cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.\nReturn the minimum total cost of the cuts.\n\nExample 1:\nInput: n = 7, cuts = [1,3,4,5]\nOutput: 16\nExplanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:\n\nThe first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.\nRearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).\n\nExample 2:\nInput: n = 9, cuts = [5,6,1,4,2]\nOutput: 22\nExplanation: If you try the given cuts ordering the cost will be 25.\nThere are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.\n\nConstraints:\n- 2 <= n <= 10^6\n- 1 <= cuts.length <= min(n - 1, 100)\n- 1 <= cuts[i] <= n - 1\n- All the integers in cuts array are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(n^2)\n\nclass Solution(object):\n def minCost(self, n, cuts):\n \"\"\"\n :type n: int\n :type cuts: List[int]\n :rtype: int\n \"\"\"\n sorted_cuts = sorted(cuts + [0, n])\n dp = [[0]*len(sorted_cuts) for _ in range(len(sorted_cuts))]\n for l in range(2, len(sorted_cuts)):\n for i in range(len(sorted_cuts)-l):\n dp[i][i+l] = min(dp[i][j]+dp[j][i+l] for j in range(i+1, i+l)) + \\\n sorted_cuts[i+l]-sorted_cuts[i]\n return dp[0][len(sorted_cuts)-1]\n"}} diff --git a/cp/cp-10947.jsonl b/cp/cp-10947.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..19da2159ff572777cb39e27f27e41cb21a1f5e4b --- /dev/null +++ b/cp/cp-10947.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10947", "name": "LeetCode 1550: Three Consecutive Odds"} +{"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: Three Consecutive Odds (Difficulty: Easy)\nTags: Array\n\nExample 1:\nInput: arr = [2,6,4,1]\nOutput: false\nExplanation: There are no three consecutive odds.\n\nExample 2:\nInput: arr = [1,2,34,3,4,5,7,23,12]\nOutput: true\nExplanation: [5,7,23] are three consecutive odds.\n\nConstraints:\n- 1 <= arr.length <= 1000\n- 1 <= arr[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def threeConsecutiveOdds(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: bool\n \"\"\"\n count = 0\n for x in arr:\n count = count+1 if x%2 else 0\n if count == 3:\n return True\n return False\n"}} diff --git a/cp/cp-10948.jsonl b/cp/cp-10948.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..683a0b5e6e0cd881305f39bceb26060981542385 --- /dev/null +++ b/cp/cp-10948.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10948", "name": "LeetCode 1551: Minimum Operations To Make Array Equal"} +{"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: Minimum Operations to Make Array Equal (Difficulty: Medium)\nTags: Math\n\nYou have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n).\nIn one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.\nGiven an integer n, the length of the array, return the minimum number of operations needed to make all the elements of arr equal.\n\nExample 1:\nInput: n = 3\nOutput: 2\nExplanation: arr = [1, 3, 5]\nFirst operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]\nIn the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].\n\nExample 2:\nInput: n = 6\nOutput: 9\n\nConstraints:\n- 1 <= n <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def minOperations(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n # total = sum(2i+1 for i in range(n)) = n^2\n # left_half_total = sum(2i+1 for i in range(n//2)) = (n//2)^2\n # result = (n//2) * (total//n) - left_half_total = (n//2)*(n-n//2) = (n//2)*((n+1)//2)\n return (n//2)*((n+1)//2)\n"}} diff --git a/cp/cp-10949.jsonl b/cp/cp-10949.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a83714af01adbfaf28fec0a1b9441f66d578d6a5 --- /dev/null +++ b/cp/cp-10949.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10949", "name": "LeetCode 1552: Magnetic Force Between Two Balls"} +{"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: Magnetic Force Between Two Balls (Difficulty: Medium)\nTags: Array, Binary Search, Sorting\n\nIn the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.\nRick stated that magnetic force between two different balls at positions x and y is |x - y|.\nGiven the integer array position and the integer m. Return the required force.\n\nExample 1:\nInput: position = [1,2,3,4,7], m = 3\nOutput: 3\nExplanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.\n\nExample 2:\nInput: position = [5,4,3,2,1,1000000000], m = 2\nOutput: 999999999\nExplanation: We can use baskets 1 and 1000000000.\n\nConstraints:\n- n == position.length\n- 2 <= n <= 10^5\n- 1 <= position[i] <= 10^9\n- All integers in position are distinct.\n- 2 <= m <= position.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn + nlogr), r is the range of positions\n# Space: O(1)\n\nclass Solution(object):\n def maxDistance(self, position, m):\n \"\"\"\n :type position: List[int]\n :type m: int\n :rtype: int\n \"\"\"\n def check(position, m, x):\n count, prev = 1, position[0]\n for i in range(1, len(position)):\n if position[i]-prev >= x:\n count += 1\n prev = position[i]\n return count >= m\n \n position.sort()\n left, right = 1, position[-1]-position[0]\n while left <= right:\n mid = left + (right-left)//2\n if not check(position, m, mid):\n right = mid-1\n else:\n left = mid+1\n return right\n"}} diff --git a/cp/cp-10950.jsonl b/cp/cp-10950.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f79bab6a3c59250ce2a2708bbae0d36c81fd13da --- /dev/null +++ b/cp/cp-10950.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10950", "name": "LeetCode 1553: Minimum Number Of Days To Eat N Oranges"} +{"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: Minimum Number of Days to Eat N Oranges (Difficulty: Hard)\nTags: Dynamic Programming, Memoization\n\nThere are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:\nYou can only choose one of the actions per day.\nGiven the integer n, return the minimum number of days to eat n oranges.\n\nExample 1:\nInput: n = 10\nOutput: 4\nExplanation: You have 10 oranges.\nDay 1: Eat 1 orange, 10 - 1 = 9. \nDay 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)\nDay 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. \nDay 4: Eat the last orange 1 - 1 = 0.\nYou need at least 4 days to eat the 10 oranges.\n\nExample 2:\nInput: n = 6\nOutput: 3\nExplanation: You have 6 oranges.\nDay 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).\nDay 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)\nDay 3: Eat the last orange 1 - 1 = 0.\nYou need at least 3 days to eat the 6 oranges.\n\nConstraints:\n- 1 <= n <= 2 * 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((logn)^2)\n# Space: O((logn)^2)\n\n# complexity analysis: see https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/discuss/794847/Polylogarithmic-solution\nclass Solution(object):\n def minDays(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n def memoization(lookup, i):\n if i <= 1:\n return i\n if i not in lookup:\n lookup[i] = 1+min(i%2+memoization(lookup, i//2),\n i%3+memoization(lookup, i//3))\n return lookup[i]\n\n lookup = {}\n return memoization(lookup, n)\n\n\n# Time: O((logn)^2)\n# Space: O((logn)^2)\nclass Solution2(object):\n def minDays(self, n):\n result = 0\n q, lookup = [n], set([n])\n while q:\n new_q = []\n for i in q: \n if not i:\n return result\n if i-1 not in lookup:\n lookup.add(i-1)\n new_q.append(i-1)\n if i%2 == 0 and i//2 not in lookup:\n lookup.add(i//2)\n new_q.append(i//2)\n if i%3 == 0 and i//3 not in lookup:\n lookup.add(i//3)\n new_q.append(i//3)\n result += 1\n q = new_q\n return result\n"}} diff --git a/cp/cp-10952.jsonl b/cp/cp-10952.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b9576314e3d6414d46af5c28f4fb2bb38957e1ac --- /dev/null +++ b/cp/cp-10952.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10952", "name": "LeetCode 1556: Thousand Separator"} +{"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: Thousand Separator (Difficulty: Easy)\nTags: String\n\nGiven an integer n, add a dot (\".\") as the thousands separator and return it in string format.\n\nExample 1:\nInput: n = 987\nOutput: \"987\"\n\nExample 2:\nInput: n = 1234\nOutput: \"1.234\"\n\nConstraints:\n- 0 <= n <= 2^31 - 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def thousandSeparator(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n result = []\n s = str(n)\n for i, c in enumerate(str(n)):\n if i and (len(s)-i)%3 == 0:\n result.append(\".\")\n result.append(c)\n return \"\".join(result)\n"}} diff --git a/cp/cp-10953.jsonl b/cp/cp-10953.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..61ac5f0df80fd42297dc26fd7bd548d34436c84d --- /dev/null +++ b/cp/cp-10953.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10953", "name": "LeetCode 1557: Minimum Number Of Vertices To Reach All Nodes"} +{"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: Minimum Number of Vertices to Reach All Nodes (Difficulty: Medium)\nTags: Graph\n\nGiven a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi.\nFind the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.\nNotice that you can return the vertices in any order.\n\nExample 1:\nInput: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]\nOutput: [0,3]\nExplanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].\n\nExample 2:\nInput: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]\nOutput: [0,2,3]\nExplanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.\n\nConstraints:\n- 2 <= n <= 10^5\n- 1 <= edges.length <= min(10^5, n * (n - 1) / 2)\n- edges[i].length == 2\n- 0 <= fromi, toi < n\n- All pairs (fromi, toi) are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(e)\n# Space: O(n)\n\nclass Solution(object):\n def findSmallestSetOfVertices(self, n, edges):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :rtype: List[int]\n \"\"\"\n result = []\n lookup = set()\n for u, v in edges:\n lookup.add(v)\n for i in range(n):\n if i not in lookup:\n result.append(i)\n return result\n"}} diff --git a/cp/cp-10954.jsonl b/cp/cp-10954.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0b2db066e5a04206b4147b64324b485ac8fc3b4a --- /dev/null +++ b/cp/cp-10954.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10954", "name": "LeetCode 1558: Minimum Numbers Of Function Calls To Make Target 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: Minimum Numbers of Function Calls to Make Target Array (Difficulty: Medium)\nTags: Array, Greedy, Bit Manipulation\n\nYou are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function:\nYou want to use the modify function to convert arr to nums using the minimum number of calls.\nReturn the minimum number of function calls to make nums from arr.\nThe test cases are generated so that the answer fits in a 32-bit signed integer.\n\nExample 1:\nInput: nums = [1,5]\nOutput: 5\nExplanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).\nDouble all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).\nIncrement by 1 (both elements) [0, 4] -> [1, 4] -> [1, 5] (2 operations).\nTotal of operations: 1 + 2 + 2 = 5.\n\nExample 2:\nInput: nums = [2,2]\nOutput: 3\nExplanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).\nDouble all the elements: [1, 1] -> [2, 2] (1 operation).\nTotal of operations: 2 + 1 = 3.\n\nExample 3:\nInput: nums = [4,2,5]\nOutput: 6\nExplanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 0 <= nums[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def minOperations(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def popcount(n):\n result = 0\n while n:\n n &= n-1\n result += 1\n return result\n\n result, max_len = 0, 1\n for num in nums:\n result += popcount(num)\n max_len = max(max_len, num.bit_length())\n return result + (max_len-1)\n"}} diff --git a/cp/cp-10955.jsonl b/cp/cp-10955.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4ee449878ad6a80356650b6eb8568a1e159908bd --- /dev/null +++ b/cp/cp-10955.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10955", "name": "LeetCode 1559: Detect Cycles In 2D Grid"} +{"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: Detect Cycles in 2D Grid (Difficulty: Medium)\nTags: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix\n\nGiven a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid.\nA cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.\nAlso, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell.\nReturn true if any cycle of the same value exists in grid, otherwise, return false.\n\nExample 1:\nInput: grid = [[\"a\",\"a\",\"a\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"a\",\"a\",\"a\"]]\nOutput: true\nExplanation: There are two valid cycles shown in different colors in the image below:\n\nExample 2:\nInput: grid = [[\"c\",\"c\",\"c\",\"a\"],[\"c\",\"d\",\"c\",\"c\"],[\"c\",\"c\",\"e\",\"c\"],[\"f\",\"c\",\"c\",\"c\"]]\nOutput: true\nExplanation: There is only one valid cycle highlighted in the image below:\n\nExample 3:\nInput: grid = [[\"a\",\"b\",\"b\"],[\"b\",\"z\",\"b\"],[\"b\",\"b\",\"a\"]]\nOutput: false\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 500\n- grid consists only of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n * α(n)) ~= O(m * n)\n# Space: O(m * n)\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n self.count = n\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root != y_root:\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n self.count -= 1\n\n\nclass Solution(object):\n def containsCycle(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: bool\n \"\"\"\n def index(n, i, j):\n return i*n + j\n \n union_find = UnionFind(len(grid)*len(grid[0]))\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if i and j and grid[i][j] == grid[i-1][j] == grid[i][j-1] and \\\n union_find.find_set(index(len(grid[0]), i-1, j)) == \\\n union_find.find_set(index(len(grid[0]), i, j-1)):\n return True\n if i and grid[i][j] == grid[i-1][j]:\n union_find.union_set(index(len(grid[0]), i-1, j),\n index(len(grid[0]),i, j))\n if j and grid[i][j] == grid[i][j-1]:\n union_find.union_set(index(len(grid[0]), i, j-1),\n index(len(grid[0]), i, j))\n return False\n\n\n# Time: O(m * n)\n# Space: O(m * n)\nclass Solution2(object):\n def containsCycle(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: bool\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if not grid[i][j]:\n continue\n val = grid[i][j]\n q = [(i, j)]\n while q:\n new_q = []\n for r, c in q:\n if not grid[r][c]:\n return True\n grid[r][c] = 0\n for dr, dc in directions:\n nr, nc = r+dr, c+dc\n if not (0 <= nr < len(grid) and\n 0 <= nc < len(grid[0]) and\n grid[nr][nc] == val):\n continue\n new_q.append((nr, nc))\n q = new_q\n return False\n"}} diff --git a/cp/cp-10956.jsonl b/cp/cp-10956.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1d81cce77c509ab4a780429fef3d1ea415c01106 --- /dev/null +++ b/cp/cp-10956.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10956", "name": "LeetCode 1560: Most Visited Sector In A Circular Track"} +{"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: Most Visited Sector in a Circular Track (Difficulty: Easy)\nTags: Array, Simulation\n\nGiven an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1]\nReturn an array of the most visited sectors sorted in ascending order.\nNotice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).\n\nExample 1:\nInput: n = 4, rounds = [1,3,1,2]\nOutput: [1,2]\nExplanation: The marathon starts at sector 1. The order of the visited sectors is as follows:\n1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)\nWe can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.\n\nExample 2:\nInput: n = 2, rounds = [2,1,2,1,2,1,2,1,2]\nOutput: [2]\n\nExample 3:\nInput: n = 7, rounds = [1,3,5,7]\nOutput: [1,2,3,4,5,6,7]\n\nConstraints:\n- 2 <= n <= 100\n- 1 <= m <= 100\n- rounds.length == m + 1\n- 1 <= rounds[i] <= n\n- rounds[i] != rounds[i + 1] for 0 <= i < m"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def mostVisited(self, n, rounds):\n \"\"\"\n :type n: int\n :type rounds: List[int]\n :rtype: List[int]\n \"\"\"\n return range(rounds[0], rounds[-1]+1) or \\\n range(1, rounds[-1]+1) + range(rounds[0], n+1)\n"}} diff --git a/cp/cp-10958.jsonl b/cp/cp-10958.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..270a22b972ac4358b22d3abb4f4bcf82dde4ce06 --- /dev/null +++ b/cp/cp-10958.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10958", "name": "LeetCode 1562: Find Latest Group Of Size M"} +{"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 Latest Group of Size M (Difficulty: Medium)\nTags: Array, Hash Table, Binary Search, Simulation\n\nGiven an array arr that represents a permutation of numbers from 1 to n.\nYou have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1.\nYou are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction.\nReturn the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1.\n\nExample 1:\nInput: arr = [3,5,1,2,4], m = 1\nOutput: 4\nExplanation: \nStep 1: \"00100\", groups: [\"1\"]\nStep 2: \"00101\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"11101\", groups: [\"111\", \"1\"]\nStep 5: \"11111\", groups: [\"11111\"]\nThe latest step at which there exists a group of size 1 is step 4.\n\nExample 2:\nInput: arr = [3,1,5,4,2], m = 2\nOutput: -1\nExplanation: \nStep 1: \"00100\", groups: [\"1\"]\nStep 2: \"10100\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"10111\", groups: [\"1\", \"111\"]\nStep 5: \"11111\", groups: [\"11111\"]\nNo group of size 2 exists during any step.\n\nConstraints:\n- n == arr.length\n- 1 <= m <= n <= 10^5\n- 1 <= arr[i] <= n\n- All integers in arr are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def findLatestStep(self, arr, m):\n \"\"\"\n :type arr: List[int]\n :type m: int\n :rtype: int\n \"\"\"\n if m == len(arr):\n return m\n length = [0]*(len(arr)+2)\n result = -1\n for i, x in enumerate(arr):\n left, right = length[x-1], length[x+1]\n if left == m or right == m:\n result = i\n length[x-left] = length[x+right] = left+right+1\n return result\n"}} diff --git a/cp/cp-10959.jsonl b/cp/cp-10959.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..80114fe75b41fe1261ed7b7aba280f6ee500a262 --- /dev/null +++ b/cp/cp-10959.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10959", "name": "LeetCode 1563: Stone Game V"} +{"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: Stone Game V (Difficulty: Hard)\nTags: Array, Math, Dynamic Programming, Game Theory\n\nThere are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.\nIn each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.\nThe game ends when there is only one stone remaining. Alice's score is initially zero.\nReturn the maximum score that Alice can obtain.\n\nExample 1:\nInput: stoneValue = [6,2,3,4,5,5]\nOutput: 18\nExplanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.\nIn the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).\nThe last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.\n\nExample 2:\nInput: stoneValue = [7,7,7,7,7,7,7]\nOutput: 28\n\nExample 3:\nInput: stoneValue = [4]\nOutput: 0\n\nConstraints:\n- 1 <= stoneValue.length <= 500\n- 1 <= stoneValue[i] <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2)\n\nclass Solution(object):\n def stoneGameV(self, stoneValue):\n \"\"\"\n :type stoneValue: List[int]\n :rtype: int\n \"\"\"\n n = len(stoneValue)\n prefix = [0]\n for v in stoneValue:\n prefix.append(prefix[-1] + v)\n\n mid = range(n)\n\n dp = [[0]*n for _ in range(n)]\n for i in range(n):\n dp[i][i] = stoneValue[i]\n\n max_score = 0\n for l in range(2, n+1):\n for i in range(n-l+1):\n j = i+l-1\n while prefix[mid[i]]-prefix[i] < prefix[j+1]-prefix[mid[i]]:\n mid[i] += 1 # Time: O(n^2) in total\n p = mid[i]\n max_score = 0\n if prefix[p]-prefix[i] == prefix[j+1]-prefix[p]:\n max_score = max(dp[i][p-1], dp[j][p])\n else:\n if i <= p-2:\n max_score = max(max_score, dp[i][p-2])\n if p <= j:\n max_score = max(max_score, dp[j][p])\n dp[i][j] = max(dp[i][j-1], (prefix[j+1]-prefix[i]) + max_score)\n dp[j][i] = max(dp[j][i+1], (prefix[j+1]-prefix[i]) + max_score)\n return max_score\n\n\n# Time: O(n^2)\n# Space: O(n^2)\nclass Solution2(object):\n def stoneGameV(self, stoneValue):\n \"\"\"\n :type stoneValue: List[int]\n :rtype: int\n \"\"\"\n n = len(stoneValue)\n prefix = [0]\n for v in stoneValue:\n prefix.append(prefix[-1] + v)\n\n mid = [[0]*n for _ in range(n)]\n for l in range(1, n+1):\n for i in range(n-l+1):\n j = i+l-1\n p = i if l == 1 else mid[i][j-1]\n while prefix[p]-prefix[i] < prefix[j+1]-prefix[p]:\n p += 1 # Time: O(n^2) in total\n mid[i][j] = p\n \n rmq = [[0]*n for _ in range(n)]\n for i in range(n):\n rmq[i][i] = stoneValue[i]\n\n dp = [[0]*n for _ in range(n)]\n for l in range(2, n+1):\n for i in range(n-l+1):\n j = i+l-1\n p = mid[i][j]\n max_score = 0\n if prefix[p]-prefix[i] == prefix[j+1]-prefix[p]:\n max_score = max(rmq[i][p-1], rmq[j][p])\n else:\n if i <= p-2:\n max_score = max(max_score, rmq[i][p-2])\n if p <= j:\n max_score = max(max_score, rmq[j][p])\n dp[i][j] = max_score\n rmq[i][j] = max(rmq[i][j-1], (prefix[j+1]-prefix[i]) + max_score)\n rmq[j][i] = max(rmq[j][i+1], (prefix[j+1]-prefix[i]) + max_score)\n return dp[0][n-1]\n"}} diff --git a/cp/cp-10961.jsonl b/cp/cp-10961.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0d95b2c31f4fd10b5a00a37fd62aceaa5a833276 --- /dev/null +++ b/cp/cp-10961.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10961", "name": "LeetCode 1567: Maximum Length Of Subarray With Positive Product"} +{"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 Subarray With Positive Product (Difficulty: Medium)\nTags: Array, Dynamic Programming, Greedy\n\nGiven an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.\nA subarray of an array is a consecutive sequence of zero or more values taken out of that array.\nReturn the maximum length of a subarray with positive product.\n\nExample 1:\nInput: nums = [1,-2,-3,4]\nOutput: 4\nExplanation: The array nums already has a positive product of 24.\n\nExample 2:\nInput: nums = [0,1,-2,-3,-4]\nOutput: 3\nExplanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.\nNotice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.\n\nExample 3:\nInput: nums = [-1,-2,-3,0,1]\nOutput: 2\nExplanation: The longest subarray with positive product is [-1,-2] or [-2,-3].\n\nConstraints:\n- 1 <= nums.length <= 10^5\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 getMaxLen(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result, neg_cnt, last_zero_pos, first_valid_neg_pos = 0, 0, -1, -1\n for i in range(len(nums)):\n if nums[i] == 0:\n neg_cnt = 0\n last_zero_pos = i\n first_valid_neg_pos = -1\n continue\n if nums[i] < 0:\n if first_valid_neg_pos == -1:\n first_valid_neg_pos = i\n neg_cnt += 1\n result = max(result, i-(last_zero_pos if neg_cnt%2 == 0 else first_valid_neg_pos))\n return result\n"}} diff --git a/cp/cp-10962.jsonl b/cp/cp-10962.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e1fadb80de1931d2b639afb826f7f2fba3ab54e3 --- /dev/null +++ b/cp/cp-10962.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10962", "name": "LeetCode 1568: Minimum Number Of Days To Disconnect Island"} +{"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: Minimum Number of Days to Disconnect Island (Difficulty: Hard)\nTags: Array, Depth-First Search, Breadth-First Search, Matrix, Strongly Connected Component\n\nYou are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's.\nThe grid is said to be connected if we have exactly one island, otherwise is said disconnected.\nIn one day, we are allowed to change any single land cell (1) into a water cell (0).\nReturn the minimum number of days to disconnect the grid.\n\nExample 1:\nInput: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]\n\nOutput: 2\nExplanation: We need at least 2 days to get a disconnected grid.\nChange land grid[1][1] and grid[0][2] to water and get 2 disconnected island.\n\nExample 2:\nInput: grid = [[1,1]]\nOutput: 2\nExplanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 30\n- grid[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m * n)\n\n# template: https://github.com/kamyu104/GoogleCodeJam-Farewell-Rounds/blob/main/Round%20B/railroad_maintenance.py3\n# Reference: https://en.wikipedia.org/wiki/Biconnected_component#Algorithms\ndef iter_get_articulation_points(graph, v): # modified\n def iter_dfs(v, p):\n stk = [(1, (v, p))]\n while stk:\n step, args = stk.pop()\n if step == 1:\n v, p = args\n index[v] = index_counter[0]\n lowlinks[v] = index_counter[0]\n index_counter[0] += 1\n children_count = [0]\n is_cut = [False]\n stk.append((4, (v, p, children_count, is_cut)))\n for w in reversed(graph[v]):\n if w == p:\n continue\n stk.append((2, (w, v, children_count, is_cut)))\n elif step == 2:\n w, v, children_count, is_cut = args\n if index[w] == -1:\n children_count[0] += 1\n stk.append((3, (w, v, is_cut)))\n stk.append((1, (w, v)))\n else:\n lowlinks[v] = min(lowlinks[v], index[w])\n elif step == 3:\n w, v, is_cut = args\n if lowlinks[w] >= index[v]:\n is_cut[0] = True\n lowlinks[v] = min(lowlinks[v], lowlinks[w])\n elif step == 4:\n v, p, children_count, is_cut = args\n if (p != -1 and is_cut[0]) or (p == -1 and children_count[0] >= 2):\n cutpoints.append(v)\n index_counter, index, lowlinks = [0], [-1]*len(graph), [0]*len(graph)\n cutpoints = []\n iter_dfs(v, -1) # modified\n return cutpoints\n\n\n# flood fill, tarjan's algorithm, articulation points\nclass Solution(object):\n def minDays(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n \n def floodfill(grid, i, j, lookup):\n stk = [(i, j)]\n lookup[i][j] = 1\n while stk:\n i, j = stk.pop()\n for di, dj in DIRECTIONS:\n ni, nj = i+di, j+dj\n if not (0 <= ni < R and 0 <= nj < C and grid[ni][nj] and not lookup[ni][nj]):\n continue\n lookup[ni][nj] = 1\n stk.append((ni, nj))\n \n def count_islands(grid):\n lookup = [[0]*C for _ in range(R)]\n island_cnt = 0\n for i in range(R):\n for j in range(C):\n if grid[i][j] == 0 or lookup[i][j]:\n continue\n island_cnt += 1\n floodfill(grid, i, j, lookup)\n return island_cnt\n\n R, C = len(grid), len(grid[0])\n if count_islands(grid) != 1:\n return 0\n adj = [[] for _ in range(R*C)]\n cnt, idx = 0, -1\n for i in range(R):\n for j in range(C):\n if grid[i][j] == 0:\n continue\n cnt += 1\n if idx == -1:\n idx = i*C+j\n for di, dj in DIRECTIONS:\n ni, nj = i+di, j+dj\n if 0 <= ni < R and 0 <= nj < C and grid[ni][nj] == grid[i][j]:\n adj[i*C+j].append(ni*C+nj)\n return 1 if cnt == 1 or iter_get_articulation_points(adj, idx) else 2\n\n\n# Time: O((m * n) * log(m * n))\n# Space: O((m * n) * log(m * n))\n# Template: https://github.com/kamyu104/MetaHackerCup-2022/blob/main/Final%20Round/tile_transposing.py3\nclass PersistentUnionFind(object): # Time: O(n * alpha(n)), Space: O(n)\n def __init__(self, n):\n self.set = range(n)\n self.size = [1]*n\n self.snapshots = [] # added\n self.undos = [] # added\n\n def find_set(self, x):\n stk = []\n while self.set[x] != x: # path compression\n stk.append(x)\n x = self.set[x]\n while stk:\n y = stk.pop()\n self.undos.append((~y, self.set[y])) # added\n self.set[y] = x\n return x\n\n def union_set(self, x, y):\n x, y = self.find_set(x), self.find_set(y)\n if x == y:\n return False\n if self.size[x] > self.size[y]: # union by size\n x, y = y, x\n self.undos.append((x, y)) # added\n self.set[x] = self.set[y]\n self.size[y] += self.size[x]\n return True\n\n def total(self, x):\n return self.size[self.find_set(x)]\n\n def snapshot(self): # added\n self.snapshots.append(len(self.undos))\n\n def rollback(self): # added\n for _ in range(len(self.undos)-self.snapshots.pop()):\n x, y = self.undos.pop()\n if x >= 0:\n self.size[y] -= self.size[x]\n self.set[x] = x\n else:\n self.set[~x] = y\n\n\n# flood fill, persistent union find\nclass Solution2(object):\n def minDays(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n \n def floodfill(grid, i, j, lookup):\n stk = [(i, j)]\n lookup[i][j] = 1\n while stk:\n i, j = stk.pop()\n for di, dj in DIRECTIONS:\n ni, nj = i+di, j+dj\n if not (0 <= ni < R and 0 <= nj < C and grid[ni][nj] and not lookup[ni][nj]):\n continue\n lookup[ni][nj] = 1\n stk.append((ni, nj))\n \n def count_islands(grid):\n lookup = [[0]*C for _ in range(R)]\n island_cnt = 0\n for i in range(R):\n for j in range(C):\n if grid[i][j] == 0 or lookup[i][j]:\n continue\n island_cnt += 1\n floodfill(grid, i, j, lookup)\n return island_cnt\n \n def merge(i):\n r, c = divmod(i, C)\n for dr, dc in DIRECTIONS:\n nr, nc = r+dr, c+dc\n ni = nr*C+nc\n if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == grid[r][c] and lookup[ni]:\n uf.union_set(i, ni)\n\n def check(i):\n r, c = divmod(i, C)\n if grid[r][c] == 0:\n return False\n lookup = set()\n for dr, dc in DIRECTIONS:\n nr, nc = r+dr, c+dc\n if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == grid[r][c]:\n lookup.add(uf.find_set(nr*C+nc))\n return len(lookup) != 1\n\n def dfs(left, right):\n if left == right:\n return check(left)\n mid = left + (right-left)//2\n l1, r1, l2, r2 = left, mid, mid+1, right\n for _ in range(2):\n uf.snapshot()\n for i in range(l1, r1+1):\n lookup[i] = True\n merge(i)\n if dfs(l2, r2):\n return True\n for i in range(l1, r1+1):\n lookup[i] = False\n uf.rollback()\n l1, r1, l2, r2 = l2, r2, l1, r1\n return False\n\n R, C = len(grid), len(grid[0])\n if count_islands(grid) != 1:\n return 0\n uf = PersistentUnionFind(R*C)\n lookup = [False]*(R*C)\n return 1 if dfs(0, R*C-1) else 2\n\n\n# Time: O(m^2 * n^2)\n# Space: O(m * n)\n# flood fill\nclass Solution3(object):\n def minDays(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n \n def floodfill(grid, i, j, lookup):\n stk = [(i, j)]\n lookup[i][j] = 1\n while stk:\n i, j = stk.pop()\n for di, dj in DIRECTIONS:\n ni, nj = i+di, j+dj\n if not (0 <= ni < R and 0 <= nj < C and grid[ni][nj] and not lookup[ni][nj]):\n continue\n lookup[ni][nj] = 1\n stk.append((ni, nj))\n \n def count_islands(grid):\n lookup = [[0]*C for _ in range(R)]\n island_cnt = 0\n for i in range(R):\n for j in range(C):\n if grid[i][j] == 0 or lookup[i][j]:\n continue\n island_cnt += 1\n floodfill(grid, i, j, lookup)\n return island_cnt\n\n R, C = len(grid), len(grid[0])\n if count_islands(grid) != 1:\n return 0\n for i in range(R):\n for j in range(C):\n if grid[i][j] == 0:\n continue\n grid[i][j] = 0\n island_cnt = count_islands(grid)\n grid[i][j] = 1\n if island_cnt != 1:\n return 1\n return 2\n"}} diff --git a/cp/cp-10966.jsonl b/cp/cp-10966.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..59889f812bdaf6adf2632b21f85c929a0d4b98fb --- /dev/null +++ b/cp/cp-10966.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10966", "name": "LeetCode 1573: Number Of Ways To Split A 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: Number of Ways to Split a String (Difficulty: Medium)\nTags: Math, String\n\nGiven a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s.\nReturn the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: s = \"10101\"\nOutput: 4\nExplanation: There are four ways to split s in 3 parts where each part contain the same number of letters '1'.\n\"1|010|1\"\n\"1|01|01\"\n\"10|10|1\"\n\"10|1|01\"\n\nExample 2:\nInput: s = \"1001\"\nOutput: 0\n\nExample 3:\nInput: s = \"0000\"\nOutput: 3\nExplanation: There are three ways to split s in 3 parts.\n\"0|0|00\"\n\"0|00|0\"\n\"00|0|0\"\n\nConstraints:\n- 3 <= s.length <= 10^5\n- s[i] is either '0' or '1'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def numWays(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n\n ones = s.count('1')\n if ones % 3:\n return 0\n ones //= 3\n if ones == 0:\n return (len(s)-1)*(len(s)-2)//2 % MOD\n count = left = right = 0\n for c in s:\n if c == '1':\n count += 1\n if count == ones:\n left += 1\n elif count == 2*ones:\n right += 1\n return left*right % MOD\n"}} diff --git a/cp/cp-10967.jsonl b/cp/cp-10967.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ef2c4a837382664732475a74e54fb289adda17ba --- /dev/null +++ b/cp/cp-10967.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10967", "name": "LeetCode 1574: Shortest Subarray To Be Removed To Make Array Sorted"} +{"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: Shortest Subarray to be Removed to Make Array Sorted (Difficulty: Medium)\nTags: Array, Two Pointers, Binary Search, Stack, Monotonic Stack\n\nGiven an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.\nReturn the length of the shortest subarray to remove.\nA subarray is a contiguous subsequence of the array.\n\nExample 1:\nInput: arr = [1,2,3,10,4,2,3,5]\nOutput: 3\nExplanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.\nAnother correct solution is to remove the subarray [3,10,4].\n\nExample 2:\nInput: arr = [5,4,3,2,1]\nOutput: 4\nExplanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].\n\nExample 3:\nInput: arr = [1,2,3]\nOutput: 0\nExplanation: The array is already non-decreasing. We do not need to remove any elements.\n\nConstraints:\n- 1 <= arr.length <= 10^5\n- 0 <= arr[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def findLengthOfShortestSubarray(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n j = -1\n for j in reversed(range(1, len(arr))):\n if arr[j-1] > arr[j]:\n break\n else:\n return 0\n result = j\n for i in range(j):\n if i and arr[i] < arr[i-1]:\n break\n while j < len(arr) and arr[i] > arr[j]:\n j += 1\n result = min(result, (j-i+1)-2)\n return result\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def findLengthOfShortestSubarray(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n result = 0\n for i in range(1, len(arr)):\n if arr[i-1] <= arr[i]:\n continue\n j = len(arr)-1\n while j > i and (j == len(arr)-1 or arr[j] <= arr[j+1]) and arr[i-1] <= arr[j]:\n j -= 1\n result = j-i+1\n break\n for j in reversed(range(len(arr)-1)):\n if arr[j] <= arr[j+1]:\n continue\n i = 0\n while i < j and (i == 0 or arr[i-1] <= arr[i]) and arr[i] <= arr[j+1]:\n i += 1\n result = min(result, j-i+1)\n break\n return result\n"}} diff --git a/cp/cp-10968.jsonl b/cp/cp-10968.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3d7d04a11027ed27bfd8531f96c5b8f64d2764ef --- /dev/null +++ b/cp/cp-10968.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10968", "name": "LeetCode 1575: Count All Possible Routes"} +{"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: Count All Possible Routes (Difficulty: Hard)\nTags: Array, Dynamic Programming, Memoization\n\nYou are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively.\nAt each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x.\nNotice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish).\nReturn the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5\nOutput: 4\nExplanation: The following are all possible routes, each uses 5 units of fuel:\n1 -> 3\n1 -> 2 -> 3\n1 -> 4 -> 3\n1 -> 4 -> 2 -> 3\n\nExample 2:\nInput: locations = [4,3,1], start = 1, finish = 0, fuel = 6\nOutput: 5\nExplanation: The following are all possible routes:\n1 -> 0, used fuel = 1\n1 -> 2 -> 0, used fuel = 5\n1 -> 2 -> 1 -> 0, used fuel = 5\n1 -> 0 -> 1 -> 0, used fuel = 3\n1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5\n\nExample 3:\nInput: locations = [5,2,1], start = 0, finish = 2, fuel = 3\nOutput: 0\nExplanation: It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.\n\nConstraints:\n- 2 <= locations.length <= 100\n- 1 <= locations[i] <= 10^9\n- All integers in locations are distinct.\n- 0 <= start, finish < locations.length\n- 1 <= fuel <= 200"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn + n * f)\n# Space: O(n * f)\n\nimport bisect\n\n\nclass Solution(object):\n def countRoutes(self, locations, start, finish, fuel):\n \"\"\"\n :type locations: List[int]\n :type start: int\n :type finish: int\n :type fuel: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n\n s, f = locations[start], locations[finish]\n locations.sort()\n start, finish = bisect.bisect_left(locations, s), bisect.bisect_left(locations, f)\n\n left = [[0]*(fuel+1) for _ in range(len(locations))] # left[i][f], last move is toward left to location i by f fuel\n right = [[0]*(fuel+1) for _ in range(len(locations))] # right[i][f], last move is toward right to location i by f fuel\n for f in range(1, fuel+1):\n for j in range(len(locations)-1):\n d = locations[j+1]-locations[j]\n if f > d:\n # left[j][f] = right[j+1][f-d(j, j+1)] + 2*right[j+2][f-d(j, j+2)] + ... + 2^(k-1)*right[j+k][f-d(j, j+k)]\n # => left[j+1][f] = (ight[j+2][f-d(j+1, j+2)] + 2*right[j+3][f-d(j+1, j+3)] + ... + 2^(k-2)*right[j+1+k-1][f-d(j+1, j+1+k-1)]\n # => left[j+1][f-d(j, j+1)] = right[j+2][f-d(j, j+2)] + 2*right[j+3][f-d(j, j+3)] + ... + 2^(k-2)*right[j+k][f-d(j, j+k)]\n # => left[j][f] = right[j+1][f-d(j, j+1)] + 2*left[j+1][f-d(j, j+1)]\n left[j][f] = (right[j+1][f-d] + 2*left[j+1][f-d] % MOD) % MOD\n elif f == d:\n left[j][f] = int(j+1 == start)\n for j in range(1, len(locations)):\n d = locations[j]-locations[j-1]\n if f > d:\n # right[j][f] = left[j-1][f-d(j, j-1)] + 2*left[j-2][f-d(j, j-2)] + ... + 2^(k-1)*left[j-k][f-d(j, j-k)]\n # => right[j-1][f] = left[j-2][f-d(j-1, j-2)] + 2*left[j-3][f-d(j-1, j-3)] + ... + 2^(k-2)*left[j-1-k+1][f-d(j-1, j-1-k+1)]\n # => right[j-1][f-d(j, j-1)] = left[j-2][f-d(j, j-2)] + 2*left[j-3][f-d(j, j-3)] + ... + 2^(k-2)*left[j-k][f-d(j, j-k)]\n # => right[j][f] = left[j-1][f-d(j, j-1)] + 2*right[j-1][f-d(j, j-1)]\n right[j][f] = (left[j-1][f-d] + 2*right[j-1][f-d] % MOD) % MOD\n elif f == d:\n right[j][f] = int(j-1 == start)\n result = int(start == finish)\n for f in range(1, fuel+1):\n result = ((result + left[finish][f]) % MOD + right[finish][f]) % MOD\n return result\n\n\n# Time: O(n^2 * f)\n# Space: O(n * f)\nclass Solution2(object):\n def countRoutes(self, locations, start, finish, fuel):\n \"\"\"\n :type locations: List[int]\n :type start: int\n :type finish: int\n :type fuel: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n dp = [[0]*(fuel+1) for _ in range(len(locations))]\n dp[start][0] = 1\n for f in range(fuel+1):\n for i in range(len(locations)):\n for j in range(len(locations)):\n if i == j:\n continue\n d = abs(locations[i]-locations[j])\n if f-d < 0:\n continue\n dp[i][f] = (dp[i][f]+dp[j][f-d])%MOD\n return reduce(lambda x, y: (x+y)%MOD, dp[finish])\n"}} diff --git a/cp/cp-10969.jsonl b/cp/cp-10969.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5a7680d93b0215f9c6db73a1cc2ea2628ede7b6b --- /dev/null +++ b/cp/cp-10969.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10969", "name": "LeetCode 1576: Replace All S To Avoid Consecutive Repeating Characters"} +{"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 All ?'s to Avoid Consecutive Repeating Characters (Difficulty: Easy)\nTags: String\n\nGiven a string s containing only lowercase English letters and the '?' character, convert all the '?' characters into lowercase letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters.\nIt is guaranteed that there are no consecutive repeating characters in the given string except for '?'.\nReturn the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints.\n\nExample 1:\nInput: s = \"?zs\"\nOutput: \"azs\"\nExplanation: There are 25 solutions for this problem. From \"azs\" to \"yzs\", all are valid. Only \"z\" is an invalid modification as the string will consist of consecutive repeating characters in \"zzs\".\n\nExample 2:\nInput: s = \"ubv?w\"\nOutput: \"ubvaw\"\nExplanation: There are 24 solutions for this problem. Only \"v\" and \"w\" are invalid modifications as the strings will consist of consecutive repeating characters in \"ubvvw\" and \"ubvww\".\n\nConstraints:\n- 1 <= s.length <= 100\n- s consist of lowercase English letters and '?'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def modifyString(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n s = list(s)\n for i in range(len(s)):\n if s[i] != '?':\n continue\n for c in ('a', 'b', 'c'):\n if (i == 0 or s[i-1] != c) and (i == len(s)-1 or c != s[i+1]):\n break\n s[i] = c\n return \"\".join(s)\n"}} diff --git a/cp/cp-10970.jsonl b/cp/cp-10970.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3f03d4a6810f9ed1c28f099981e49178f8e9a154 --- /dev/null +++ b/cp/cp-10970.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10970", "name": "LeetCode 1577: Number Of Ways Where Square Of Number Is Equal To Product Of Two 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: Number of Ways Where Square of Number Is Equal to Product of Two Numbers (Difficulty: Medium)\nTags: Array, Hash Table, Math, Two Pointers\n\nGiven two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:\n\nExample 1:\nInput: nums1 = [7,4], nums2 = [5,2,8,9]\nOutput: 1\nExplanation: Type 1: (1, 1, 2), nums1[1]2 = nums2[1] * nums2[2]. (42 = 2 * 8).\n\nExample 2:\nInput: nums1 = [1,1], nums2 = [1,1,1]\nOutput: 9\nExplanation: All Triplets are valid, because 12 = 1 * 1.\nType 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]2 = nums2[j] * nums2[k].\nType 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2 = nums1[j] * nums1[k].\n\nExample 3:\nInput: nums1 = [7,7,8,3], nums2 = [1,2,9,7]\nOutput: 2\nExplanation: There are 2 valid triplets.\nType 1: (3,0,2). nums1[3]2 = nums2[0] * nums2[2].\nType 2: (3,0,1). nums2[3]2 = nums1[0] * nums1[1].\n\nConstraints:\n- 1 <= nums1.length, nums2.length <= 1000\n- 1 <= nums1[i], nums2[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m + n)\n\nimport collections\n\n\nclass Solution(object):\n def numTriplets(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: int\n \"\"\"\n def two_product(nums, i):\n count = 0\n lookup = collections.defaultdict(int)\n for num in nums:\n if i%num:\n continue\n count += lookup[i//num]\n lookup[num] += 1\n return count\n \n result = 0\n for num in nums1:\n result += two_product(nums2, num**2)\n for num in nums2:\n result += two_product(nums1, num**2)\n return result\n"}} diff --git a/cp/cp-10972.jsonl b/cp/cp-10972.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b93eeaa7e54311ae48b24fa6e27239069fd364ca --- /dev/null +++ b/cp/cp-10972.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10972", "name": "LeetCode 1579: Remove Max Number Of Edges To Keep Graph Fully Traversable"} +{"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: Remove Max Number of Edges to Keep Graph Fully Traversable (Difficulty: Hard)\nTags: Union Find, Graph\n\nAlice and Bob have an undirected graph of n nodes and three types of edges:\nGiven an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.\nReturn the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph.\n\nExample 1:\nInput: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]\nOutput: 2\nExplanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.\n\nExample 2:\nInput: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]\nOutput: 0\nExplanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.\n\nExample 3:\nInput: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]\nOutput: -1\nExplanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.\n\nConstraints:\n- 1 <= n <= 10^5\n- 1 <= edges.length <= min(105, 3 * n * (n - 1) / 2)\n- edges[i].length == 3\n- 1 <= typei <= 3\n- 1 <= ui < vi <= n\n- All tuples (typei, ui, vi) are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + m * α(n)) ~= O(n + m)\n# Space: O(n)\n\nclass UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n self.count = n\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n self.set[max(x_root, y_root)] = min(x_root, y_root)\n self.count -= 1\n return True\n\n\nclass Solution(object):\n def maxNumEdgesToRemove(self, n, edges):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :rtype: int\n \"\"\"\n result = 0\n union_find_a, union_find_b = UnionFind(n), UnionFind(n)\n for t, i, j in edges:\n if t != 3:\n continue\n a = union_find_a.union_set(i-1, j-1)\n b = union_find_b.union_set(i-1, j-1)\n if not a and not b:\n result += 1\n for t, i, j in edges:\n if t == 1:\n if not union_find_a.union_set(i-1, j-1):\n result += 1\n elif t == 2:\n if not union_find_b.union_set(i-1, j-1):\n result += 1\n return result if union_find_a.count == union_find_b.count == 1 else -1\n"}} diff --git a/cp/cp-10974.jsonl b/cp/cp-10974.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5b78b8e97c5ac721368b70f5c87ca77126432f47 --- /dev/null +++ b/cp/cp-10974.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10974", "name": "LeetCode 1582: Special Positions In A Binary Matrix"} +{"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: Special Positions in a Binary Matrix (Difficulty: Easy)\nTags: Array, Matrix\n\nGiven an m x n binary matrix mat, return the number of special positions in mat.\nA position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).\n\nExample 1:\nInput: mat = [[1,0,0],[0,0,1],[1,0,0]]\nOutput: 1\nExplanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.\n\nExample 2:\nInput: mat = [[1,0,0],[0,1,0],[0,0,1]]\nOutput: 3\nExplanation: (0, 0), (1, 1) and (2, 2) are special positions.\n\nConstraints:\n- m == mat.length\n- n == mat[i].length\n- 1 <= m, n <= 100\n- mat[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def numSpecial(self, mat):\n \"\"\"\n :type mat: List[List[int]]\n :rtype: int\n \"\"\"\n rows, cols = [0]*len(mat), [0]*len(mat[0])\n for i in range(len(rows)):\n for j in range(len(cols)):\n if mat[i][j]:\n rows[i] += 1\n cols[j] += 1\n result = 0\n for i in range(len(rows)):\n for j in range(len(cols)):\n if mat[i][j] == rows[i] == cols[j] == 1:\n result += 1\n return result\n"}} diff --git a/cp/cp-10975.jsonl b/cp/cp-10975.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4effd33fca88ffcdc91db6f95488762de2f13730 --- /dev/null +++ b/cp/cp-10975.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10975", "name": "LeetCode 1583: Count Unhappy Friends"} +{"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: Count Unhappy Friends (Difficulty: Medium)\nTags: Array, Simulation\n\nYou are given a list of preferences for n friends, where n is always even.\nFor each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.\nAll the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.\nHowever, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:\nReturn the number of unhappy friends.\n\nExample 1:\nInput: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]\nOutput: 2\nExplanation:\nFriend 1 is unhappy because:\n- 1 is paired with 0 but prefers 3 over 0, and\n- 3 prefers 1 over 2.\nFriend 3 is unhappy because:\n- 3 is paired with 2 but prefers 1 over 2, and\n- 1 prefers 3 over 0.\nFriends 0 and 2 are happy.\n\nExample 2:\nInput: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]\nOutput: 0\nExplanation: Both friends 0 and 1 are happy.\n\nExample 3:\nInput: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]\nOutput: 4\n\nConstraints:\n- 2 <= n <= 500\n- n is even.\n- preferences.length == n\n- preferences[i].length == n - 1\n- 0 <= preferences[i][j] <= n - 1\n- preferences[i] does not contain i.\n- All values in preferences[i] are unique.\n- pairs.length == n/2\n- pairs[i].length == 2\n- xi != yi\n- 0 <= xi, yi <= n - 1\n- Each person is contained in exactly one pair."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2)\n\nclass Solution(object):\n def unhappyFriends(self, n, preferences, pairs):\n \"\"\"\n :type n: int\n :type preferences: List[List[int]]\n :type pairs: List[List[int]]\n :rtype: int\n \"\"\"\n friends = [[0]*n for _ in range(n)]\n for i in range(len(preferences)):\n for j in range(len(preferences[i])):\n friends[i][preferences[i][j]] = j\n pairing = [0]*n\n for i, j in pairs:\n pairing[i], pairing[j] = j, i\n return sum(any(friends[i][j] < friends[i][pairing[i]] and friends[j][i] < friends[j][pairing[j]]\n for j in range(len(friends[i])) if j != i and j != pairing[i])\n for i in range(len(friends)))\n"}} diff --git a/cp/cp-10976.jsonl b/cp/cp-10976.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c11467de262cdd3e81600a9b5ed26bb87396fe98 --- /dev/null +++ b/cp/cp-10976.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10976", "name": "LeetCode 1584: Min Cost To Connect All Points"} +{"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: Min Cost to Connect All Points (Difficulty: Medium)\nTags: Array, Union Find, Graph, Minimum Spanning Tree\n\nYou are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].\nThe cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.\nReturn the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.\n\nExample 1:\nInput: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]\nOutput: 20\nExplanation: \n\nWe can connect the points as shown above to get the minimum cost of 20.\nNotice that there is a unique path between every pair of points.\n\nExample 2:\nInput: points = [[3,12],[-2,5],[-4,1]]\nOutput: 18\n\nConstraints:\n- 1 <= points.length <= 1000\n- -10^6 <= xi, yi <= 10^6\n- All pairs (xi, yi) are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def minCostConnectPoints(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n result, u = 0, 0 # we can start from any node as u\n dist = [float(\"inf\")]*len(points)\n lookup = set()\n for _ in range(len(points)-1):\n x0, y0 = points[u]\n lookup.add(u)\n for v, (x, y) in enumerate(points):\n if v in lookup:\n continue\n dist[v] = min(dist[v], abs(x-x0) + abs(y-y0))\n val, u = min((val, v) for v, val in enumerate(dist)) \n dist[u] = float(\"inf\") # used\n result += val\n return result\n\n\n\n# Time: O(eloge) = O(n^2 * logn)\n# Space: O(e) = O(n^2)\n# kruskal's algorithm\nclass UnionFind(object): # Time: O(n * α(n)), Space: O(n)\n def __init__(self, n):\n self.set = range(n)\n self.rank = [0]*n\n\n def find_set(self, x):\n stk = []\n while self.set[x] != x: # path compression\n stk.append(x)\n x = self.set[x]\n while stk:\n self.set[stk.pop()] = x\n return x\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n if self.rank[x_root] < self.rank[y_root]: # union by rank\n self.set[x_root] = y_root\n elif self.rank[x_root] > self.rank[y_root]:\n self.set[y_root] = x_root\n else:\n self.set[y_root] = x_root\n self.rank[x_root] += 1\n return True\n\n\nclass Solution2(object):\n def minCostConnectPoints(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n edges = []\n for u in range(len(points)):\n for v in range(u+1, len(points)):\n edges.append((u, v, abs(points[v][0]-points[u][0]) + abs(points[v][1]-points[u][1])))\n edges.sort(key=lambda x: x[2])\n result = 0\n union_find = UnionFind(len(points))\n for u, v, val in edges:\n if union_find.union_set(u, v):\n result += val\n return result\n\n"}} diff --git a/cp/cp-10977.jsonl b/cp/cp-10977.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..50fb22025b39b35af6aca3473f6916edf020157c --- /dev/null +++ b/cp/cp-10977.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10977", "name": "LeetCode 1585: Check If String Is Transformable With Substring Sort Operations"} +{"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: Check If String Is Transformable With Substring Sort Operations (Difficulty: Hard)\nTags: String, Greedy, Sorting\n\nGiven two strings s and t, transform string s into string t using the following operation any number of times:\nReturn true if it is possible to transform s into t. Otherwise, return false.\nA substring is a contiguous sequence of characters within a string.\n\nExample 1:\nInput: s = \"84532\", t = \"34852\"\nOutput: true\nExplanation: You can transform s into t using the following sort operations:\n\"84532\" (from index 2 to 3) -> \"84352\"\n\"84352\" (from index 0 to 2) -> \"34852\"\n\nExample 2:\nInput: s = \"34521\", t = \"23415\"\nOutput: true\nExplanation: You can transform s into t using the following sort operations:\n\"34521\" -> \"23451\"\n\"23451\" -> \"23415\"\n\nExample 3:\nInput: s = \"12345\", t = \"12435\"\nOutput: false\n\nConstraints:\n- s.length == t.length\n- 1 <= s.length <= 10^5\n- s and t consist of only digits."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def isTransformable(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n idxs = [[] for _ in range(10)]\n for i in reversed(range(len(s))):\n idxs[int(s[i])].append(i)\n for c in t:\n d = int(c)\n if not idxs[d]:\n return False\n for k in range(d): # a char can be moved left to the current position if it meets no smaller one\n if idxs[k] and idxs[k][-1] < idxs[d][-1]:\n return False\n idxs[d].pop()\n return True\n"}} diff --git a/cp/cp-10979.jsonl b/cp/cp-10979.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a0677b68756e39b65b1000ad54ad083ef7c40497 --- /dev/null +++ b/cp/cp-10979.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10979", "name": "LeetCode 1588: Sum Of All Odd Length Subarrays"} +{"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 All Odd Length Subarrays (Difficulty: Easy)\nTags: Array, Math, Prefix Sum\n\nGiven an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.\nA subarray is a contiguous subsequence of the array.\nFollow up:\nCould you solve this problem in O(n) time complexity?\n\nExample 1:\nInput: arr = [1,4,2,5,3]\nOutput: 58\nExplanation: The odd-length subarrays of arr and their sums are:\n[1] = 1\n[4] = 4\n[2] = 2\n[5] = 5\n[3] = 3\n[1,4,2] = 7\n[4,2,5] = 11\n[2,5,3] = 10\n[1,4,2,5,3] = 15\nIf we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58\n\nExample 2:\nInput: arr = [1,2]\nOutput: 3\nExplanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.\n\nExample 3:\nInput: arr = [10,11,12]\nOutput: 66\n\nConstraints:\n- 1 <= arr.length <= 100\n- 1 <= arr[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def sumOddLengthSubarrays(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n def ceil_divide(a, b):\n return (a+(b-1))//b\n \n # begin\\pos |0 i (n-1)\n # ----------------------------\n # 0 --101.... ↑\n # 1 -010.... i-0+1\n # i 101.... ↓\n # ← (n-1-i+1) →\n #\n # for each number x with its position i, we want to know how many odd length subarrays is with x,\n # as the graph depicted above,\n # (begin, pos) pair represents a subarray arr[begin:pos+1] containing x, marked 1 if odd length else 0,\n # so the total number of 0 and 1 are exactly the total number of subarrays with x, which is (i-0+1)*((len(arr)-1)-i+1),\n # because the number of 1 is always equal to or one more than the number of 0, (always begins with 1010... and alternatively flips)\n # so there are ceil((i-0+1)*((len(arr)-1)-i+1)/2) odd length subarrays with x\n # \n return sum(x * ceil_divide((i-0+1)*((len(arr)-1)-i+1), 2) for i, x in enumerate(arr))\n"}} diff --git a/cp/cp-10980.jsonl b/cp/cp-10980.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d05bb3c78cf6cc57608e31de8209ac13c1852606 --- /dev/null +++ b/cp/cp-10980.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10980", "name": "LeetCode 1589: Maximum Sum Obtained Of Any Permutation"} +{"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 Sum Obtained of Any Permutation (Difficulty: Medium)\nTags: Array, Greedy, Sorting, Prefix Sum\n\nWe have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed.\nReturn the maximum total sum of all requests among all permutations of nums.\nSince the answer may be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: nums = [1,2,3,4,5], requests = [[1,3],[0,1]]\nOutput: 19\nExplanation: One permutation of nums is [2,1,3,4,5] with the following result: \nrequests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8\nrequests[1] -> nums[0] + nums[1] = 2 + 1 = 3\nTotal sum: 8 + 3 = 11.\nA permutation with a higher total sum is [3,5,4,2,1] with the following result:\nrequests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11\nrequests[1] -> nums[0] + nums[1] = 3 + 5 = 8\nTotal sum: 11 + 8 = 19, which is the best that you can do.\n\nExample 2:\nInput: nums = [1,2,3,4,5,6], requests = [[0,1]]\nOutput: 11\nExplanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].\n\nExample 3:\nInput: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]\nOutput: 47\nExplanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].\n\nConstraints:\n- n == nums.length\n- 1 <= n <= 10^5\n- 0 <= nums[i] <= 10^5\n- 1 <= requests.length <= 10^5\n- requests[i].length == 2\n- 0 <= starti <= endi < n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport itertools\n\n\nclass Solution(object):\n def maxSumRangeQuery(self, nums, requests):\n \"\"\"\n :type nums: List[int]\n :type requests: List[List[int]]\n :rtype: int\n \"\"\"\n def addmod(a, b, mod): # avoid overflow in other languages\n a %= mod\n b %= mod\n if mod-a <= b:\n b -= mod\n return a+b\n \n def mulmod(a, b, mod): # avoid overflow in other languages\n a %= mod\n b %= mod\n if a < b:\n a, b = b, a\n result = 0\n while b > 0:\n if b%2 == 1:\n result = addmod(result, a, mod)\n a = addmod(a, a, mod)\n b //= 2\n return result\n\n MOD = 10**9+7\n\n count = [0]*len(nums)\n for start, end in requests:\n count[start] += 1\n if end+1 < len(count):\n count[end+1] -= 1\n for i in range(1, len(count)):\n count[i] += count[i-1]\n nums.sort()\n count.sort()\n result = 0\n for i, (num, c) in enumerate(itertools.izip(nums, count)):\n # result = addmod(result, mulmod(num, c, MOD), MOD)\n result = (result+num*c)%MOD\n return result\n"}} diff --git a/cp/cp-10981.jsonl b/cp/cp-10981.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cf84b99c4f1fe666d222da71a43c86568acd5399 --- /dev/null +++ b/cp/cp-10981.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10981", "name": "LeetCode 1590: Make Sum Divisible By P"} +{"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: Make Sum Divisible by P (Difficulty: Medium)\nTags: Array, Hash Table, Prefix Sum\n\nGiven an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.\nReturn the length of the smallest subarray that you need to remove, or -1 if it's impossible.\nA subarray is defined as a contiguous block of elements in the array.\n\nExample 1:\nInput: nums = [3,1,4,2], p = 6\nOutput: 1\nExplanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.\n\nExample 2:\nInput: nums = [6,3,5,2], p = 9\nOutput: 2\nExplanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.\n\nExample 3:\nInput: nums = [1,2,3], p = 3\nOutput: 0\nExplanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i] <= 10^9\n- 1 <= p <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(p)\n\nclass Solution(object):\n def minSubarray(self, nums, p):\n \"\"\"\n :type nums: List[int]\n :type p: int\n :rtype: int\n \"\"\"\n residue = sum(nums) % p\n if not residue:\n return 0\n result = len(nums)\n curr, lookup = 0, {0: -1}\n for i, num in enumerate(nums):\n curr = (curr+num) % p\n lookup[curr] = i\n if (curr-residue) % p in lookup:\n result = min(result, i-lookup[(curr-residue)%p])\n return result if result < len(nums) else -1\n"}} diff --git a/cp/cp-10982.jsonl b/cp/cp-10982.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..706ce04756abf587eb1cb78ac61736da910ffd5e --- /dev/null +++ b/cp/cp-10982.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10982", "name": "LeetCode 1591: Strange Printer 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: Strange Printer II (Difficulty: Hard)\nTags: Array, Graph, Topological Sort, Matrix\n\nThere is a strange printer with the following two special requirements:\nYou are given a m x n matrix targetGrid, where targetGrid[row][col] is the color in the position (row, col) of the grid.\nReturn true if it is possible to print the matrix targetGrid, otherwise, return false.\n\nExample 1:\nInput: targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]\nOutput: true\n\nExample 2:\nInput: targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]\nOutput: true\n\nExample 3:\nInput: targetGrid = [[1,2,1],[2,1,2],[1,2,1]]\nOutput: false\nExplanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns.\n\nConstraints:\n- m == targetGrid.length\n- n == targetGrid[i].length\n- 1 <= m, n <= 60\n- 1 <= targetGrid[row][col] <= 60"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(c * m * n + e), c is the number of colors\n# , e is the number of edges in adj, at most O(c^2)\n# Space: O(e)\n\nimport collections\n\n\nclass Solution(object):\n def isPrintable(self, targetGrid):\n \"\"\"\n :type targetGrid: List[List[int]]\n :rtype: bool\n \"\"\"\n VISITING, VISITED = range(2)\n def has_cycle(adj, color, lookup):\n stk = [(1, color)]\n while stk:\n step, color = stk.pop()\n if step == 1:\n lookup[color] = VISITING\n stk.append((2, color))\n for new_color in adj[color]:\n if new_color in lookup:\n if lookup[new_color] == VISITED:\n continue\n return True # VISITING\n stk.append((1, new_color))\n elif step == 2:\n lookup[color] = VISITED\n return False\n\n boxes = collections.defaultdict(lambda:[len(targetGrid), len(targetGrid[0]), -1, -1])\n for r, row in enumerate(targetGrid):\n for c, color in enumerate(row):\n boxes[color][0] = min(boxes[color][0], r)\n boxes[color][1] = min(boxes[color][1], c)\n boxes[color][2] = max(boxes[color][2], r)\n boxes[color][3] = max(boxes[color][3], c)\n adj = collections.defaultdict(set)\n for color, (min_r, min_c, max_r, max_c) in boxes.iteritems():\n for r in range(min_r, max_r+1):\n for c in range(min_c, max_c+1):\n if targetGrid[r][c] != color:\n adj[color].add(targetGrid[r][c])\n\n lookup = {}\n return all(color in lookup or not has_cycle(adj, color, lookup) for color in boxes.iterkeys())\n \n\n# Time: O(c * m * n + e), c is the number of colors\n# , e is the number of edges in adj, at most O(c^2)\n# Space: O(e)\nclass Solution2(object):\n def isPrintable(self, targetGrid):\n \"\"\"\n :type targetGrid: List[List[int]]\n :rtype: bool\n \"\"\"\n VISITING, VISITED = range(2)\n def has_cycle(adj, color, lookup):\n lookup[color] = VISITING\n for new_color in adj[color]:\n if (new_color not in lookup and has_cycle(adj, new_color, lookup)) or \\\n lookup[new_color] == VISITING:\n return True\n lookup[color] = VISITED\n return False \n\n MAX_COLOR = 60\n adj = collections.defaultdict(set)\n for color in range(1, MAX_COLOR+1):\n min_r = len(targetGrid)\n min_c = len(targetGrid[0])\n max_r = -1\n max_c = -1\n for r in range(len(targetGrid)):\n for c in range(len(targetGrid[r])):\n if targetGrid[r][c] == color:\n min_r = min(min_r, r)\n min_c = min(min_c, c)\n max_r = max(max_r, r)\n max_c = max(max_c, c)\n for r in range(min_r, max_r+1):\n for c in range(min_c, max_c+1):\n if targetGrid[r][c] != color:\n adj[color].add(targetGrid[r][c])\n\n lookup = {}\n return all(color in lookup or not has_cycle(adj, color, lookup) for color in range(1, MAX_COLOR+1))\n"}} diff --git a/cp/cp-10983.jsonl b/cp/cp-10983.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dc2b79421558c1e7c8a0bc73fe38f8c1e079f624 --- /dev/null +++ b/cp/cp-10983.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10983", "name": "LeetCode 1592: Rearrange Spaces Between 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: Rearrange Spaces Between Words (Difficulty: Easy)\nTags: String\n\nYou are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.\nRearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.\nReturn the string after rearranging the spaces.\n\nExample 1:\nInput: text = \" this is a sentence \"\nOutput: \"this is a sentence\"\nExplanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.\n\nExample 2:\nInput: text = \" practice makes perfect\"\nOutput: \"practice makes perfect \"\nExplanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.\n\nConstraints:\n- 1 <= text.length <= 100\n- text consists of lowercase English letters and ' '.\n- text contains at least one word."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# inplace solution\nclass Solution(object):\n def reorderSpaces(self, text):\n \"\"\"\n :type text: str\n :rtype: str\n \"\"\"\n text = list(text)\n # count the spaces and words\n space_count, word_count = 0, 0\n for i, c in enumerate(text):\n if c == ' ':\n space_count += 1\n elif i == 0 or text[i-1] == ' ':\n word_count += 1\n\n # rearrange all the spaces to the right\n left, i = 0, 0\n while i < len(text):\n has_word = False\n while i < len(text) and text[i] != ' ':\n text[left], text[i] = text[i], text[left]\n left += 1\n i += 1\n has_word = True\n if has_word:\n left += 1 # keep one space\n i += 1\n\n # rearrange all the spaces to the left\n equal_count = space_count//(word_count-1) if word_count-1 > 0 else 0\n extra_count = space_count%(word_count-1) if word_count-1 > 0 else space_count\n right, i = len(text)-1-extra_count, len(text)-1\n while i >= 0:\n has_word = False\n while i >= 0 and text[i] != ' ':\n text[right], text[i] = text[i], text[right]\n right -= 1\n i -= 1\n has_word = True\n if has_word:\n right -= equal_count # keep equal_count spaces\n i -= 1\n return \"\".join(text)\n"}} diff --git a/cp/cp-10984.jsonl b/cp/cp-10984.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d0249ab916b8cb3a718712c99e1047545caa01fb --- /dev/null +++ b/cp/cp-10984.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10984", "name": "LeetCode 1593: Split A String Into The Max Number Of Unique 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: Split a String Into the Max Number of Unique Substrings (Difficulty: Medium)\nTags: Hash Table, String, Backtracking\n\nGiven a string s, return the maximum number of unique substrings that the given string can be split into.\nYou can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.\nA substring is a contiguous sequence of characters within a string.\n\nExample 1:\nInput: s = \"ababccc\"\nOutput: 5\nExplanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.\n\nExample 2:\nInput: s = \"aba\"\nOutput: 2\nExplanation: One way to split maximally is ['a', 'ba'].\n\nExample 3:\nInput: s = \"aa\"\nOutput: 1\nExplanation: It is impossible to split the string any further.\n\nConstraints:\n- 1 <= s.length <= 16\n- s contains only lower case English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * 2^(n - 1))\n# Space: O(n)\n\nclass Solution(object):\n def maxUniqueSplit(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n def popcount(n):\n count = 0\n while n:\n n &= n-1\n count += 1\n return count\n \n result = 1\n total = 2**(len(s)-1)\n mask = 0\n while mask < total:\n if popcount(mask) < result:\n mask += 1\n continue\n lookup, curr, base = set(), [], total//2\n for i in range(len(s)):\n curr.append(s[i])\n if (mask&base) or base == 0:\n if \"\".join(curr) in lookup:\n mask = (mask | (base-1)) + 1 if base else mask+1 # pruning, try next mask without base\n break\n lookup.add(\"\".join(curr))\n curr = []\n base >>= 1\n else:\n result = max(result, len(lookup))\n mask += 1\n return result\n"}} diff --git a/cp/cp-10985.jsonl b/cp/cp-10985.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6460c6802bb57b24d1e5e7fa9d707d6486e28614 --- /dev/null +++ b/cp/cp-10985.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10985", "name": "LeetCode 1594: Maximum Non Negative Product In A Matrix"} +{"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 Non Negative Product in a Matrix (Difficulty: Medium)\nTags: Array, Dynamic Programming, Matrix\n\nYou are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix.\nAmong all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path.\nReturn the maximum non-negative product modulo 109 + 7. If the maximum product is negative, return -1.\nNotice that the modulo is performed after getting the maximum product.\n\nExample 1:\nInput: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]\nOutput: -1\nExplanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.\n\nExample 2:\nInput: grid = [[1,-2,1],[1,-2,1],[3,-4,1]]\nOutput: 8\nExplanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).\n\nExample 3:\nInput: grid = [[1,3],[0,-4]]\nOutput: 0\nExplanation: Maximum non-negative product is shown (1 * 0 * -4 = 0).\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 15\n- -4 <= grid[i][j] <= 4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(n)\n\n# dp with rolling window\nclass Solution(object):\n def maxProductPath(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n max_dp = [[0]*len(grid[0]) for _ in range(2)]\n min_dp = [[0]*len(grid[0]) for _ in range(2)]\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if i == 0 and j == 0:\n max_dp[i%2][j] = min_dp[i%2][j] = grid[i][j]\n continue\n curr_max = max(max_dp[(i-1)%2][j] if i > 0 else max_dp[i%2][j-1],\n max_dp[i%2][j-1] if j > 0 else max_dp[(i-1)%2][j])\n curr_min = min(min_dp[(i-1)%2][j] if i > 0 else min_dp[i%2][j-1],\n min_dp[i%2][j-1] if j > 0 else min_dp[(i-1)%2][j])\n if grid[i][j] < 0:\n curr_max, curr_min = curr_min, curr_max\n max_dp[i%2][j] = curr_max*grid[i][j]\n min_dp[i%2][j] = curr_min*grid[i][j]\n return max_dp[(len(grid)-1)%2][-1]%MOD if max_dp[(len(grid)-1)%2][-1] >= 0 else -1\n"}} diff --git a/cp/cp-10986.jsonl b/cp/cp-10986.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b4187d894b003f009683f1cda66082169c1f022c --- /dev/null +++ b/cp/cp-10986.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10986", "name": "LeetCode 1595: Minimum Cost To Connect Two Groups Of Points"} +{"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: Minimum Cost to Connect Two Groups of Points (Difficulty: Hard)\nTags: Array, Dynamic Programming, Bit Manipulation, Matrix, Bitmask\n\nYou are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2.\nThe cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.\nReturn the minimum cost it takes to connect the two groups.\n\nExample 1:\nInput: cost = [[15, 96], [36, 2]]\nOutput: 17\nExplanation: The optimal way of connecting the groups is:\n1--A\n2--B\nThis results in a total cost of 17.\n\nExample 2:\nInput: cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]\nOutput: 4\nExplanation: The optimal way of connecting the groups is:\n1--A\n2--B\n2--C\n3--A\nThis results in a total cost of 4.\nNote that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.\n\nExample 3:\nInput: cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]\nOutput: 10\n\nConstraints:\n- size1 == cost.length\n- size2 == cost[i].length\n- 1 <= size1, size2 <= 12\n- size1 >= size2\n- 0 <= cost[i][j] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n * 2^n)\n# Space: O(2^n)\n\n# dp with rolling window\nclass Solution(object):\n def connectTwoGroups(self, cost):\n \"\"\"\n :type cost: List[List[int]]\n :rtype: int\n \"\"\"\n total = 2**len(cost[0])\n dp = [[float(\"inf\")]*total for _ in range(2)]\n dp[0][0] = 0\n for i in range(len(cost)):\n dp[(i+1)%2] = [float(\"inf\")]*total\n for mask in range(total):\n base = 1\n for j in range(len(cost[0])):\n dp[i%2][mask|base] = min(dp[i%2][mask|base], cost[i][j]+dp[i%2][mask])\n dp[(i+1)%2][mask|base] = min(dp[(i+1)%2][mask|base], cost[i][j]+dp[i%2][mask])\n base <<= 1\n return dp[len(cost)%2][-1]\n"}} diff --git a/cp/cp-10988.jsonl b/cp/cp-10988.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a450103e15701104b5fd73fb39c42464220ad259 --- /dev/null +++ b/cp/cp-10988.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10988", "name": "LeetCode 1598: Crawler Log Folder"} +{"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: Crawler Log Folder (Difficulty: Easy)\nTags: Array, String, Stack\n\nThe Leetcode file system keeps a log each time some user performs a change folder operation.\nThe operations are described below:\nYou are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.\nThe file system starts in the main folder, then the operations in logs are performed.\nReturn the minimum number of operations needed to go back to the main folder after the change folder operations.\n\nExample 1:\nInput: logs = [\"d1/\",\"d2/\",\"../\",\"d21/\",\"./\"]\nOutput: 2\nExplanation: Use this change folder operation \"../\" 2 times and go back to the main folder.\n\nExample 2:\nInput: logs = [\"d1/\",\"d2/\",\"./\",\"d3/\",\"../\",\"d31/\"]\nOutput: 3\n\nExample 3:\nInput: logs = [\"d1/\",\"../\",\"../\",\"../\"]\nOutput: 0\n\nConstraints:\n- 1 <= logs.length <= 103\n- 2 <= logs[i].length <= 10\n- logs[i] contains lowercase English letters, digits, '.', and '/'.\n- logs[i] follows the format described in the statement.\n- Folder names consist of lowercase English letters and digits."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minOperations(self, logs):\n \"\"\"\n :type logs: List[str]\n :rtype: int\n \"\"\"\n result = 0\n for log in logs:\n if log == \"../\":\n if result > 0:\n result -= 1\n elif log != \"./\":\n result += 1\n return result\n"}} diff --git a/cp/cp-10989.jsonl b/cp/cp-10989.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b30aaa05aecfa6d81248a0d195e91181d0682e79 --- /dev/null +++ b/cp/cp-10989.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10989", "name": "LeetCode 1599: Maximum Profit Of Operating A Centennial Wheel"} +{"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 Profit of Operating a Centennial Wheel (Difficulty: Medium)\nTags: Array, Simulation\n\nYou are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you runningCost dollars.\nYou are given an array customers of length n where customers[i] is the number of new customers arriving just before the ith rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive. You cannot make customers wait if there is room in the gondola. Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again.\nYou can stop the wheel at any time, including before serving all customers. If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation.\nReturn the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1.\n\nExample 1:\nInput: customers = [8,3], boardingCost = 5, runningCost = 6\nOutput: 3\nExplanation: The numbers written on the gondolas are the number of people currently there.\n1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.\n2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.\n3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.\nThe highest profit was $37 after rotating the wheel 3 times.\n\nExample 2:\nInput: customers = [10,9,6], boardingCost = 6, runningCost = 4\nOutput: 7\nExplanation:\n1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.\n2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40.\n3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.\n4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.\n5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.\n6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.\n7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.\nThe highest profit was $122 after rotating the wheel 7 times.\n\nExample 3:\nInput: customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92\nOutput: -1\nExplanation:\n1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.\n2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.\n3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.\n4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.\n5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.\nThe profit was never positive, so return -1.\n\nConstraints:\n- n == customers.length\n- 1 <= n <= 10^5\n- 0 <= customers[i] <= 50\n- 1 <= boardingCost, runningCost <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minOperationsMaxProfit(self, customers, boardingCost, runningCost):\n \"\"\"\n :type customers: List[int]\n :type boardingCost: int\n :type runningCost: int\n :rtype: int\n \"\"\"\n max_run = -1\n i = max_prof = prof = waiting = 0\n run = 1\n while i < len(customers) or waiting > 0:\n if i < len(customers):\n waiting += customers[i] # each run i increases people by customers[i]\n i += 1\n boarding = min(waiting, 4) # greedy\n waiting -= boarding\n prof += boarding * boardingCost - runningCost \n if prof > max_prof:\n max_prof = prof\n max_run = run\n run += 1\n return max_run\n"}} diff --git a/cp/cp-10990.jsonl b/cp/cp-10990.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5c01f5906523309b418640c7be9e819a449f8442 --- /dev/null +++ b/cp/cp-10990.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10990", "name": "LeetCode 1600: Throne Inheritance"} +{"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: Throne Inheritance (Difficulty: Medium)\nTags: Hash Table, Tree, Depth-First Search, Design\n\nA kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.\nThe kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance.\nFor example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.\nUsing the above function, we can always obtain a unique order of inheritance.\nImplement the ThroneInheritance class:\n\nExample 1:\nSuccessor(x, curOrder):\n if x has no children or all of x's children are in curOrder:\n if x is the king return null\n else return Successor(x's parent, curOrder)\n else return x's oldest child who's not in curOrder\n\nExample 2:\nInput\n[\"ThroneInheritance\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"getInheritanceOrder\", \"death\", \"getInheritanceOrder\"]\n[[\"king\"], [\"king\", \"andy\"], [\"king\", \"bob\"], [\"king\", \"catherine\"], [\"andy\", \"matthew\"], [\"bob\", \"alex\"], [\"bob\", \"asha\"], [null], [\"bob\"], [null]]\nOutput\n[null, null, null, null, null, null, null, [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"], null, [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]]\n\nExplanation\nThroneInheritance t= new ThroneInheritance(\"king\"); // order: king\nt.birth(\"king\", \"andy\"); // order: king > andy\nt.birth(\"king\", \"bob\"); // order: king > andy > bob\nt.birth(\"king\", \"catherine\"); // order: king > andy > bob > catherine\nt.birth(\"andy\", \"matthew\"); // order: king > andy > matthew > bob > catherine\nt.birth(\"bob\", \"alex\"); // order: king > andy > matthew > bob > alex > catherine\nt.birth(\"bob\", \"asha\"); // order: king > andy > matthew > bob > alex > asha > catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"]\nt.death(\"bob\"); // order: king > andy > matthew > bob > alex > asha > catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]\n\nConstraints:\n- 1 <= kingName.length, parentName.length, childName.length, name.length <= 15\n- kingName, parentName, childName, and name consist of lowercase English letters only.\n- All arguments childName and kingName are distinct.\n- All name arguments of death will be passed to either the constructor or as childName to birth first.\n- For each call to birth(parentName, childName), it is guaranteed that parentName is alive.\n- At most 105 calls will be made to birth and death.\n- At most 10 calls will be made to getInheritanceOrder."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(1)\n# birth: O(1)\n# death: O(1)\n# inherit: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass ThroneInheritance(object):\n\n def __init__(self, kingName):\n \"\"\"\n :type kingName: str\n \"\"\"\n self.__king = kingName\n self.__family_tree = collections.defaultdict(list)\n self.__dead = set()\n \n\n def birth(self, parentName, childName):\n \"\"\"\n :type parentName: str\n :type childName: str\n :rtype: None\n \"\"\"\n self.__family_tree[parentName].append(childName)\n\n\n def death(self, name):\n \"\"\"\n :type name: str\n :rtype: None\n \"\"\"\n self.__dead.add(name)\n \n \n def getInheritanceOrder(self):\n \"\"\"\n :rtype: List[str]\n \"\"\"\n result = []\n stk = [self.__king]\n while stk: # preorder traversal\n node = stk.pop()\n if node not in self.__dead:\n result.append(node)\n if node not in self.__family_tree:\n continue\n for child in reversed(self.__family_tree[node]):\n stk.append(child)\n return result\n\n"}} diff --git a/cp/cp-10991.jsonl b/cp/cp-10991.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5ff52ed47e582a4c9a079192e343d3f22ae8c955 --- /dev/null +++ b/cp/cp-10991.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10991", "name": "LeetCode 1601: Maximum Number Of Achievable Transfer Requests"} +{"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 Number of Achievable Transfer Requests (Difficulty: Hard)\nTags: Array, Backtracking, Bit Manipulation, Enumeration\n\nWe have n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.\nYou are given an array requests where requests[i] = [fromi, toi] represents an employee's request to transfer from building fromi to building toi.\nAll buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2.\nReturn the maximum number of achievable requests.\n\nExample 1:\nInput: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]\nOutput: 5\nExplantion: Let's see the requests:\nFrom building 0 we have employees x and y and both want to move to building 1.\nFrom building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.\nFrom building 2 we have employee z and they want to move to building 0.\nFrom building 3 we have employee c and they want to move to building 4.\nFrom building 4 we don't have any requests.\nWe can achieve the requests of users x and b by swapping their places.\nWe can achieve the requests of users y, a and z by swapping the places in the 3 buildings.\n\nExample 2:\nInput: n = 3, requests = [[0,0],[1,2],[2,1]]\nOutput: 3\nExplantion: Let's see the requests:\nFrom building 0 we have employee x and they want to stay in the same building 0.\nFrom building 1 we have employee y and they want to move to building 2.\nFrom building 2 we have employee z and they want to move to building 1.\nWe can achieve all the requests.\n\nExample 3:\nInput: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]\nOutput: 4\n\nConstraints:\n- 1 <= n <= 20\n- 1 <= requests.length <= 16\n- requests[i].length == 2\n- 0 <= fromi, toi < n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((n + r) * 2^r)\n# Space: O(n + r)\n\nimport itertools\n\n\n# early return solution\nclass Solution(object):\n def maximumRequests(self, n, requests):\n \"\"\"\n :type n: int\n :type requests: List[List[int]]\n :rtype: int\n \"\"\"\n for k in reversed(range(1, len(requests)+1)):\n for c in itertools.combinations(range(len(requests)), k):\n change = [0]*n\n for i in c:\n change[requests[i][0]] -= 1\n change[requests[i][1]] += 1\n if all(c == 0 for c in change):\n return k # early return\n return 0\n \n\n# Time: O((n + r) * 2^r)\n# Space: O(n + r)\n# full search solution (much slower)\nclass Solution2(object):\n def maximumRequests(self, n, requests):\n \"\"\"\n :type n: int\n :type requests: List[List[int]]\n :rtype: int\n \"\"\"\n def evaluate(n, requests, mask):\n change = [0]*n\n base, count = 1, 0\n for i in range(len(requests)):\n if base & mask:\n change[requests[i][0]] -= 1\n change[requests[i][1]] += 1\n count += 1\n base <<= 1\n return count if all(c == 0 for c in change) else 0\n\n return max(evaluate(n, requests, i) for i in range(1 << len(requests)))\n"}} diff --git a/cp/cp-10993.jsonl b/cp/cp-10993.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..29566d9670f3168fccffba18529e16f98d245a7a --- /dev/null +++ b/cp/cp-10993.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10993", "name": "LeetCode 1603: Design Parking 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: Design Parking System (Difficulty: Easy)\nTags: Design, Simulation, Counting\n\nDesign a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.\nImplement the ParkingSystem class:\n\nExample 1:\nInput\n[\"ParkingSystem\", \"addCar\", \"addCar\", \"addCar\", \"addCar\"]\n[[1, 1, 0], [1], [2], [3], [1]]\nOutput\n[null, true, true, false, false]\n\nExplanation\nParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);\nparkingSystem.addCar(1); // return true because there is 1 available slot for a big car\nparkingSystem.addCar(2); // return true because there is 1 available slot for a medium car\nparkingSystem.addCar(3); // return false because there is no available slot for a small car\nparkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.\n\nConstraints:\n- 0 <= big, medium, small <= 1000\n- carType is 1, 2, or 3\n- At most 1000 calls will be made to addCar"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass ParkingSystem(object):\n\n def __init__(self, big, medium, small):\n \"\"\"\n :type big: int\n :type medium: int\n :type small: int\n \"\"\"\n self.__space = [0, big, medium, small]\n\n def addCar(self, carType):\n \"\"\"\n :type carType: int\n :rtype: bool\n \"\"\"\n if self.__space[carType] > 0:\n self.__space[carType] -= 1\n return True\n return False\n"}} diff --git a/cp/cp-10994.jsonl b/cp/cp-10994.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..11d958e4c3b4eec780afe2e65f2504f1f2d23f6e --- /dev/null +++ b/cp/cp-10994.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10994", "name": "LeetCode 1604: Alert Using Same Key Card Three Or More Times In A One Hour Period"} +{"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: Alert Using Same Key-Card Three or More Times in a One Hour Period (Difficulty: Medium)\nTags: Array, Hash Table, String, Sorting\n\nLeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period.\nYou are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's name and the time when their key-card was used in a single day.\nAccess times are given in the 24-hour time format \"HH:MM\", such as \"23:51\" and \"09:49\".\nReturn a list of unique worker names who received an alert for frequent keycard use. Sort the names in ascending order alphabetically.\nNotice that \"10:00\" - \"11:00\" is considered to be within a one-hour period, while \"22:51\" - \"23:52\" is not considered to be within a one-hour period.\n\nExample 1:\nInput: keyName = [\"daniel\",\"daniel\",\"daniel\",\"luis\",\"luis\",\"luis\",\"luis\"], keyTime = [\"10:00\",\"10:40\",\"11:00\",\"09:00\",\"11:00\",\"13:00\",\"15:00\"]\nOutput: [\"daniel\"]\nExplanation: \"daniel\" used the keycard 3 times in a one-hour period (\"10:00\",\"10:40\", \"11:00\").\n\nExample 2:\nInput: keyName = [\"alice\",\"alice\",\"alice\",\"bob\",\"bob\",\"bob\",\"bob\"], keyTime = [\"12:01\",\"12:00\",\"18:00\",\"21:00\",\"21:20\",\"21:30\",\"23:00\"]\nOutput: [\"bob\"]\nExplanation: \"bob\" used the keycard 3 times in a one-hour period (\"21:00\",\"21:20\", \"21:30\").\n\nConstraints:\n- 1 <= keyName.length, keyTime.length <= 10^5\n- keyName.length == keyTime.length\n- keyTime[i] is in the format \"HH:MM\".\n- [keyName[i], keyTime[i]] is unique.\n- 1 <= keyName[i].length <= 10\n- keyName[i] contains only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport collections\nimport itertools\n\n\nclass Solution(object):\n def alertNames(self, keyName, keyTime):\n \"\"\"\n :type keyName: List[str]\n :type keyTime: List[str]\n :rtype: List[str]\n \"\"\"\n THRESHOLD = 3\n name_to_times = collections.defaultdict(list)\n for name, hour_minute in itertools.izip(keyName, keyTime):\n hour, minute = map(int, hour_minute.split(':'))\n name_to_times[name].append(hour*60 + minute)\n names = [] \n for name, times in name_to_times.iteritems():\n times.sort()\n left = 0\n for right, time in enumerate(times):\n while time-times[left] > 60:\n left += 1\n if right-left+1 >= THRESHOLD:\n names.append(name)\n break\n names.sort()\n return names\n"}} diff --git a/cp/cp-10995.jsonl b/cp/cp-10995.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c04b11bde8bf69063eedbdaa81774c976ad113c7 --- /dev/null +++ b/cp/cp-10995.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10995", "name": "LeetCode 1605: Find Valid Matrix Given Row And Column Sums"} +{"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 Valid Matrix Given Row and Column Sums (Difficulty: Medium)\nTags: Array, Greedy, Matrix\n\nYou are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.\nFind any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements.\nReturn a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists.\n\nExample 1:\nInput: rowSum = [3,8], colSum = [4,7]\nOutput: [[3,0],\n [1,7]]\nExplanation: \n0th row: 3 + 0 = 3 == rowSum[0]\n1st row: 1 + 7 = 8 == rowSum[1]\n0th column: 3 + 1 = 4 == colSum[0]\n1st column: 0 + 7 = 7 == colSum[1]\nThe row and column sums match, and all matrix elements are non-negative.\nAnother possible matrix is: [[1,2],\n [3,5]]\n\nExample 2:\nInput: rowSum = [5,7,10], colSum = [8,6,8]\nOutput: [[0,5,0],\n [6,1,0],\n [2,0,8]]\n\nConstraints:\n- 1 <= rowSum.length, colSum.length <= 500\n- 0 <= rowSum[i], colSum[i] <= 10^8\n- sum(rowSum) == sum(colSum)"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n), excluding ctor of result\n# Space: O(1)\n\n# optimized from Solution2 since we can find next i, j pair without nested loops\nclass Solution(object):\n def restoreMatrix(self, rowSum, colSum):\n \"\"\"\n :type rowSum: List[int]\n :type colSum: List[int]\n :rtype: List[List[int]]\n \"\"\"\n matrix = [[0]*len(colSum) for _ in range(len(rowSum))]\n i = j = 0\n while i < len(matrix) and j < len(matrix[0]):\n matrix[i][j] = min(rowSum[i], colSum[j]) # greedily used\n rowSum[i] -= matrix[i][j]\n colSum[j] -= matrix[i][j]\n if not rowSum[i]: # won't be used in row i, ++i\n i += 1\n if not colSum[j]: # won't be used in col j, ++j\n j += 1\n return matrix\n\n\n# Time: O(m * n)\n# Space: O(1)\nclass Solution2(object):\n def restoreMatrix(self, rowSum, colSum):\n \"\"\"\n :type rowSum: List[int]\n :type colSum: List[int]\n :rtype: List[List[int]]\n \"\"\"\n matrix = [[0]*len(colSum) for _ in range(len(rowSum))]\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n matrix[i][j] = min(rowSum[i], colSum[j]) # greedily used\n rowSum[i] -= matrix[i][j]\n colSum[j] -= matrix[i][j]\n return matrix\n"}} diff --git a/cp/cp-10996.jsonl b/cp/cp-10996.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..706c2df425cdea8dd693531fc59f9f1526bab2f4 --- /dev/null +++ b/cp/cp-10996.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10996", "name": "LeetCode 1606: Find Servers That Handled Most Number Of Requests"} +{"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 Servers That Handled Most Number of Requests (Difficulty: Hard)\nTags: Array, Greedy, Heap (Priority Queue), Ordered Set\n\nYou have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm:\nYou are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the ith request, and another array load, where load[i] represents the load of the ith request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers.\nReturn a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order.\n\nExample 1:\nInput: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] \nOutput: [1] \nExplanation: \nAll of the servers start out available.\nThe first 3 requests are handled by the first 3 servers in order.\nRequest 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.\nRequest 4 comes in. It cannot be handled since all servers are busy, so it is dropped.\nServers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.\n\nExample 2:\nInput: k = 3, arrival = [1,2,3,4], load = [1,2,1,2]\nOutput: [0]\nExplanation: \nThe first 3 requests are handled by first 3 servers.\nRequest 3 comes in. It is handled by server 0 since the server is available.\nServer 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.\n\nExample 3:\nInput: k = 3, arrival = [1,2,3], load = [10,12,11]\nOutput: [0,1,2]\nExplanation: Each server handles a single request, so they are all considered the busiest.\n\nConstraints:\n- 1 <= k <= 10^5\n- 1 <= arrival.length, load.length <= 10^5\n- arrival.length == load.length\n- 1 <= arrival[i], load[i] <= 10^9\n- arrival is strictly increasing."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogk)\n# Space: O(k)\n\nimport itertools\nimport heapq\n\n\nclass Solution(object):\n def busiestServers(self, k, arrival, load):\n \"\"\"\n :type k: int\n :type arrival: List[int]\n :type load: List[int]\n :rtype: List[int]\n \"\"\"\n count = [0]*k\n min_heap_of_endtimes = []\n min_heap_of_nodes_after_curr = []\n min_heap_of_nodes_before_curr = range(k)\n for i, (t, l) in enumerate(itertools.izip(arrival, load)):\n if i % k == 0:\n min_heap_of_nodes_before_curr, min_heap_of_nodes_after_curr = [], min_heap_of_nodes_before_curr\n while min_heap_of_endtimes and min_heap_of_endtimes[0][0] <= t:\n _, free = heapq.heappop(min_heap_of_endtimes)\n if free < i % k:\n heapq.heappush(min_heap_of_nodes_before_curr, free)\n else:\n heapq.heappush(min_heap_of_nodes_after_curr, free)\n min_heap_of_candidates = min_heap_of_nodes_after_curr if min_heap_of_nodes_after_curr else min_heap_of_nodes_before_curr\n if not min_heap_of_candidates:\n continue\n node = heapq.heappop(min_heap_of_candidates)\n count[node] += 1\n heapq.heappush(min_heap_of_endtimes, (t+l, node))\n max_count = max(count)\n return [i for i in range(k) if count[i] == max_count]\n\n\n# Time: O(nlogk)\n# Space: O(k)\nimport sortedcontainers # required to do pip install\nimport itertools\nimport heapq\n\n\n# reference: http://www.grantjenks.com/docs/sortedcontainers/sortedlist.html\nclass Solution2(object):\n def busiestServers(self, k, arrival, load):\n \"\"\"\n :type k: int\n :type arrival: List[int]\n :type load: List[int]\n :rtype: List[int]\n \"\"\"\n count = [0]*k \n min_heap_of_endtimes = []\n availables = sortedcontainers.SortedList(range(k)) # O(klogk)\n for i, (t, l) in enumerate(itertools.izip(arrival, load)):\n while min_heap_of_endtimes and min_heap_of_endtimes[0][0] <= t:\n _, free = heapq.heappop(min_heap_of_endtimes) # O(logk)\n availables.add(free) # O(logk)\n if not availables: \n continue\n idx = availables.bisect_left(i % k) % len(availables) # O(logk)\n node = availables.pop(idx) # O(logk)\n count[node] += 1\n heapq.heappush(min_heap_of_endtimes, (t+l, node)) # O(logk)\n max_count = max(count)\n return [i for i in range(k) if count[i] == max_count]\n"}} diff --git a/cp/cp-10997.jsonl b/cp/cp-10997.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..caa9434f5f80fb78c73ef5d6d3b490b32845ac61 --- /dev/null +++ b/cp/cp-10997.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10997", "name": "LeetCode 1608: Special Array With X Elements Greater Than Or Equal X"} +{"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: Special Array With X Elements Greater Than or Equal X (Difficulty: Easy)\nTags: Array, Binary Search, Sorting\n\nYou are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.\nNotice that x does not have to be an element in nums.\nReturn x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.\n\nExample 1:\nInput: nums = [3,5]\nOutput: 2\nExplanation: There are 2 values (3 and 5) that are greater than or equal to 2.\n\nExample 2:\nInput: nums = [0,0]\nOutput: -1\nExplanation: No numbers fit the criteria for x.\nIf x = 0, there should be 0 numbers >= x, but there are 2.\nIf x = 1, there should be 1 number >= x, but there are 0.\nIf x = 2, there should be 2 numbers >= x, but there are 0.\nx cannot be greater since there are only 2 numbers in nums.\n\nExample 3:\nInput: nums = [0,4,3,0,4]\nOutput: 3\nExplanation: There are 3 values that are greater than or equal to 3.\n\nConstraints:\n- 1 <= nums.length <= 100\n- 0 <= nums[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# counting sort solution\nclass Solution(object):\n def specialArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n MAX_NUM = 1000\n count = [0]*(MAX_NUM+1)\n for num in nums:\n count[num] += 1\n n = len(nums)\n for i in range(len(count)):\n if i == n:\n return i\n n -= count[i]\n return -1\n\n\n# Time: O(n)\n# Space: O(1)\n# counting sort + binary search solution\nclass Solution2(object):\n def specialArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n MAX_NUM = 1000\n def inplace_counting_sort(nums, reverse=False): # Time: O(n)\n count = [0]*(MAX_NUM+1)\n for num in nums:\n count[num] += 1\n for i in range(1, len(count)):\n count[i] += count[i-1]\n for i in reversed(range(len(nums))): # inplace but unstable sort\n while nums[i] >= 0:\n count[nums[i]] -= 1\n j = count[nums[i]]\n nums[i], nums[j] = nums[j], ~nums[i]\n for i in range(len(nums)):\n nums[i] = ~nums[i] # restore values\n if reverse: # unstable sort\n nums.reverse()\n \n inplace_counting_sort(nums, reverse=True)\n left, right = 0, len(nums)-1\n while left <= right: # Time: O(logn)\n mid = left + (right-left)//2\n if nums[mid] <= mid:\n right = mid-1\n else:\n left = mid+1\n return -1 if left < len(nums) and nums[left] == left else left\n\n\n# Time: O(n)\n# Space: O(n)\n# counting sort + binary search solution\nclass Solution3(object):\n def specialArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n MAX_NUM = 1000\n def counting_sort(nums, reverse=False): # Time: O(n), Space: O(n)\n count = [0]*(MAX_NUM+1)\n for num in nums:\n count[num] += 1\n for i in range(1, len(count)):\n count[i] += count[i-1]\n result = [0]*len(nums)\n if not reverse:\n for num in reversed(nums): # stable sort\n count[num] -= 1\n result[count[num]] = num\n else:\n for num in nums: # stable sort\n count[num] -= 1\n result[count[num]] = num\n result.reverse()\n return result\n \n nums = counting_sort(nums, reverse=True) # extra O(n) space for stable sort\n left, right = 0, len(nums)-1\n while left <= right: # Time: O(logn)\n mid = left + (right-left)//2\n if nums[mid] <= mid:\n right = mid-1\n else:\n left = mid+1\n return -1 if left < len(nums) and nums[left] == left else left\n\n\n# Time: O(nlogn)\n# Space: O(1)\n# sort solution\nclass Solution4(object):\n def specialArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums.sort(reverse=True) # Time: O(nlogn)\n for i in range(len(nums)): # Time: O(n)\n if nums[i] <= i:\n break\n else:\n i += 1\n return -1 if i < len(nums) and nums[i] == i else i\n"}} diff --git a/cp/cp-10998.jsonl b/cp/cp-10998.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..526c917ee0d00d58b63c6ccfc98ef2fb7102b64a --- /dev/null +++ b/cp/cp-10998.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10998", "name": "LeetCode 1609: Even Odd 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: Even Odd Tree (Difficulty: Medium)\nTags: Tree, Breadth-First Search, Binary Tree\n\nA binary tree is named Even-Odd if it meets the following conditions:\nGiven the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.\n\nExample 1:\nInput: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]\nOutput: true\nExplanation: The node values on each level are:\nLevel 0: [1]\nLevel 1: [10,4]\nLevel 2: [3,7,9]\nLevel 3: [12,8,6,2]\nSince levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.\n\nExample 2:\nInput: root = [5,4,2,3,3,7]\nOutput: false\nExplanation: The node values on each level are:\nLevel 0: [5]\nLevel 1: [4,2]\nLevel 2: [3,3,7]\nNode values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.\n\nExample 3:\nInput: root = [5,9,1,3,5,7]\nOutput: false\nExplanation: Node values in the level 1 should be even integers.\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 105].\n- 1 <= Node.val <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(w)\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution(object):\n def isEvenOddTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n q = [root]\n is_odd = False\n while q:\n new_q = []\n prev = None\n for node in q:\n if is_odd:\n if node.val%2 or (prev and prev.val <= node.val):\n return False\n else:\n if not node.val%2 or (prev and prev.val >= node.val):\n return False\n if node.left:\n new_q.append(node.left)\n if node.right:\n new_q.append(node.right)\n prev = node\n q = new_q\n is_odd = not is_odd\n return True\n"}} diff --git a/cp/cp-10999.jsonl b/cp/cp-10999.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..72f9d70c12c7b0d7819aa08e9e7948a2e1b2ddd9 --- /dev/null +++ b/cp/cp-10999.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-10999", "name": "LeetCode 1610: Maximum Number Of Visible Points"} +{"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 Number of Visible Points (Difficulty: Hard)\nTags: Array, Math, Geometry, Sliding Window, Sorting\n\nYou are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane.\nInitially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2].\nYour browser does not support the video tag or this video format.\nYou can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view.\nThere can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.\nReturn the maximum number of points you can see.\n\nExample 1:\nInput: points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]\nOutput: 3\nExplanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.\n\nExample 2:\nInput: points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]\nOutput: 4\nExplanation: All points can be made visible in your field of view, including the one at your location.\n\nExample 3:\nInput: points = [[1,0],[2,1]], angle = 13, location = [1,1]\nOutput: 1\nExplanation: You can only see one of the two points, as shown above.\n\nConstraints:\n- 1 <= points.length <= 10^5\n- points[i].length == 2\n- location.length == 2\n- 0 <= angle < 360\n- 0 <= posx, posy, xi, yi <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport math\n\n\nclass Solution(object):\n def visiblePoints(self, points, angle, location):\n \"\"\"\n :type points: List[List[int]]\n :type angle: int\n :type location: List[int]\n :rtype: int\n \"\"\"\n arr, extra = [], 0\n for p in points:\n if p == location:\n extra += 1\n continue\n arr.append(math.atan2(p[1]-location[1], p[0]-location[0]))\n arr.sort()\n arr.extend([x + 2.0*math.pi for x in arr]) # make it circular\n d = 2.0*math.pi * (angle/360.0)\n left = result = 0\n for right in range(len(arr)):\n while arr[right]-arr[left] > d:\n left += 1\n result = max(result, right-left+1)\n return result + extra\n"}} diff --git a/cp/cp-11000.jsonl b/cp/cp-11000.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9e9c9f8f0617a14f79d90a5da4825bcd1db9cf52 --- /dev/null +++ b/cp/cp-11000.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11000", "name": "LeetCode 1611: Minimum One Bit Operations To Make Integers Zero"} +{"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: Minimum One Bit Operations to Make Integers Zero (Difficulty: Hard)\nTags: Dynamic Programming, Bit Manipulation, Memoization\n\nGiven an integer n, you must transform it into 0 using the following operations any number of times:\nReturn the minimum number of operations to transform n into 0.\n\nExample 1:\nInput: n = 3\nOutput: 2\nExplanation: The binary representation of 3 is \"11\".\n\"11\" -> \"01\" with the 2nd operation since the 0th bit is 1.\n\"01\" -> \"00\" with the 1st operation.\n\nExample 2:\nInput: n = 6\nOutput: 4\nExplanation: The binary representation of 6 is \"110\".\n\"110\" -> \"010\" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.\n\"010\" -> \"011\" with the 1st operation.\n\"011\" -> \"001\" with the 2nd operation since the 0th bit is 1.\n\"001\" -> \"000\" with the 1st operation.\n\nConstraints:\n- 0 <= n <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\n# reference: https://en.wikipedia.org/wiki/Gray_code\nclass Solution(object):\n def minimumOneBitOperations(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n def gray_to_binary(n):\n result = 0\n while n:\n result ^= n\n n >>= 1\n return result\n \n # [observation]\n # n f(n)\n # 000 0\n # 001 1\n # 011 2\n # 010 3\n # 110 4\n # 111 5\n # 101 6\n # 100 7\n\t# f(0XX...X) + f(1XX...X) = f(100...0) implies n is a gray code\n # => f(n) is actually the inverse of gray code\n return gray_to_binary(n)\n\n\n# Time: O(logn)\n# Space: O(1)\nclass Solution2(object):\n def minimumOneBitOperations(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n # [observation1]:\n # f(1) = 1\n # f(10) = 2 * f(1) + 1 = 3\n # f(100) = 2 * f(10) + 1 = 7\n # by mathematical induction\n # => f(2^k) = 2^(k+1)-1\n #\n # [observation2]\n # n f(n)\n # 000 0\n # 001 1\n # 011 2\n # 010 3\n # 110 4\n # 111 5\n # 101 6\n # 100 7\n # let pos be an array of positions where the bit is 1 in ascending order:\n\t# f(0XX...X) + f(1XX...X) = f(100...0)\n # f(1XX...X) = f(100...0) - f(0XX...X)\n # = (2^(pos[k-1]+1)-1) - f(0XX...X)\n # by mathematical induction\n # => f(n) = (2^(pos[k-1]+1)-1) - (2^(pos[k-2])+1) + ... + (-1)^(k-1) * (2^(pos[0]+1)-1)\n result = 0\n while n:\n result = -result - (n^(n-1)) # 2^(pos[i]+1)-1\n n &= n-1\n return abs(result)\n"}} diff --git a/cp/cp-11002.jsonl b/cp/cp-11002.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4153065ece438aaa821667a0e3e7f033d436a6bd --- /dev/null +++ b/cp/cp-11002.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11002", "name": "LeetCode 1614: Maximum Nesting Depth Of The Parentheses"} +{"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 Nesting Depth of the Parentheses (Difficulty: Easy)\nTags: String, Stack\n\nGiven a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses.\n\nExample 1:\nInput: s = \"(1+(2*3)+((8)/4))+1\"\nOutput: 3\nExplanation:\nDigit 8 is inside of 3 nested parentheses in the string.\n\nExample 2:\nInput: s = \"(1)+((2))+(((3)))\"\nOutput: 3\nExplanation:\nDigit 3 is inside of 3 nested parentheses in the string.\n\nExample 3:\nInput: s = \"()(())((()()))\"\nOutput: 3\n\nConstraints:\n- 1 <= s.length <= 100\n- s consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'.\n- It is guaranteed that parentheses expression s is a VPS."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxDepth(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result = curr = 0\n for c in s:\n if c == '(':\n curr += 1\n result = max(result, curr)\n elif c == ')':\n curr -= 1\n return result\n"}} diff --git a/cp/cp-11003.jsonl b/cp/cp-11003.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e1eb89c8738960596f740210b940aa931a4e67de --- /dev/null +++ b/cp/cp-11003.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11003", "name": "LeetCode 1615: Maximal Network Rank"} +{"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: Maximal Network Rank (Difficulty: Medium)\nTags: Graph\n\nThere is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.\nThe network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.\nThe maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.\nGiven the integer n and the array roads, return the maximal network rank of the entire infrastructure.\n\nExample 1:\nInput: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]\nOutput: 4\nExplanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.\n\nExample 2:\nInput: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]\nOutput: 5\nExplanation: There are 5 roads that are connected to cities 1 or 2.\n\nExample 3:\nInput: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]\nOutput: 5\nExplanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.\n\nConstraints:\n- 2 <= n <= 100\n- 0 <= roads.length <= n * (n - 1) / 2\n- roads[i].length == 2\n- 0 <= ai, bi <= n-1\n- ai != bi\n- Each pair of cities has at most one road connecting them."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n + k^2), k is the number of values greater or equal to top2\n# Space: O(m + n)\n\n# optimized from Solution2 with counting sort\nclass Solution(object):\n def maximalNetworkRank(self, n, roads):\n \"\"\"\n :type n: int\n :type roads: List[List[int]]\n :rtype: int\n \"\"\"\n MAX_N = 100\n MAX_NUM = MAX_N-1\n def counting_sort(arr, key=lambda x:x, reverse=False): # Time: O(n), Space: O(n)\n count = [0]*(MAX_NUM+1)\n for x in arr:\n count[key(x)] += 1\n for i in range(1, len(count)):\n count[i] += count[i-1]\n result = [0]*len(arr)\n if not reverse:\n for x in reversed(arr): # stable sort\n count[key(x)] -= 1\n result[count[key(x)]] = x\n else:\n for x in arr: # stable sort\n count[key(x)] -= 1\n result[count[key(x)]] = x\n result.reverse()\n return result\n\n degree = [0]*n\n adj = collections.defaultdict(set)\n for a, b in roads:\n degree[a] += 1\n degree[b] += 1\n adj[a].add(b)\n adj[b].add(a)\n sorted_idx = counting_sort(range(n), key=lambda x:degree[x], reverse=True)\n m = 2\n while m < n:\n if degree[sorted_idx[m]] != degree[sorted_idx[1]]:\n break\n m += 1\n result = degree[sorted_idx[0]] + degree[sorted_idx[1]] - 1 # at least sum(top2 values) - 1\n for i in range(m-1): # only need to check pairs of top2 values\n for j in range(i+1, m):\n if degree[sorted_idx[i]]+degree[sorted_idx[j]]-int(sorted_idx[i] in adj and sorted_idx[j] in adj[sorted_idx[i]]) > result: # if equal to ideal sum of top2 values, break\n return degree[sorted_idx[i]]+degree[sorted_idx[j]]-int(sorted_idx[i] in adj and sorted_idx[j] in adj[sorted_idx[i]]) \n return result\n\n\n# Time: O(m + nlogn + k^2), k is the number of values greater or equal to top2\n# Space: O(m + n)\nimport collections\n\n\n# optimized from Solution3\nclass Solution2(object):\n def maximalNetworkRank(self, n, roads):\n \"\"\"\n :type n: int\n :type roads: List[List[int]]\n :rtype: int\n \"\"\"\n degree = [0]*n\n adj = collections.defaultdict(set)\n for a, b in roads:\n degree[a] += 1\n degree[b] += 1\n adj[a].add(b)\n adj[b].add(a)\n sorted_idx = range(n)\n sorted_idx.sort(key=lambda x:-degree[x])\n m = 2\n while m < n:\n if degree[sorted_idx[m]] != degree[sorted_idx[1]]:\n break\n m += 1\n result = degree[sorted_idx[0]] + degree[sorted_idx[1]] - 1 # at least sum(top2 values) - 1\n for i in range(m-1): # only need to check pairs of top2 values\n for j in range(i+1, m):\n if degree[sorted_idx[i]]+degree[sorted_idx[j]]-int(sorted_idx[i] in adj and sorted_idx[j] in adj[sorted_idx[i]]) > result: # if equal to ideal sum of top2 values, break\n return degree[sorted_idx[i]]+degree[sorted_idx[j]]-int(sorted_idx[i] in adj and sorted_idx[j] in adj[sorted_idx[i]]) \n return result\n\n\n# Time: O(m + n^2)\n# Space: O(m + n)\nimport collections\n\n\nclass Solution3(object):\n def maximalNetworkRank(self, n, roads):\n \"\"\"\n :type n: int\n :type roads: List[List[int]]\n :rtype: int\n \"\"\"\n degree = [0]*n\n adj = collections.defaultdict(set)\n for a, b in roads:\n degree[a] += 1\n degree[b] += 1\n adj[a].add(b)\n adj[b].add(a)\n result = 0\n for i in range(n-1):\n for j in range(i+1, n):\n result = max(result, degree[i]+degree[j]-int(i in adj and j in adj[i]))\n return result\n"}} diff --git a/cp/cp-11004.jsonl b/cp/cp-11004.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd6025ae1f1e615ce0537d6717913b472afdf523 --- /dev/null +++ b/cp/cp-11004.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11004", "name": "LeetCode 1616: Split Two Strings To Make Palindrome"} +{"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 Two Strings to Make Palindrome (Difficulty: Medium)\nTags: Two Pointers, String\n\nYou are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome.\nWhen you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = \"abc\", then \"\" + \"abc\", \"a\" + \"bc\", \"ab\" + \"c\" , and \"abc\" + \"\" are valid splits.\nReturn true if it is possible to form a palindrome string, otherwise return false.\nNotice that x + y denotes the concatenation of strings x and y.\n\nExample 1:\nInput: a = \"x\", b = \"y\"\nOutput: true\nExplaination: If either a or b are palindromes the answer is true since you can split in the following way:\naprefix = \"\", asuffix = \"x\"\nbprefix = \"\", bsuffix = \"y\"\nThen, aprefix + bsuffix = \"\" + \"y\" = \"y\", which is a palindrome.\n\nExample 2:\nInput: a = \"xbdef\", b = \"xecab\"\nOutput: false\n\nExample 3:\nInput: a = \"ulacfd\", b = \"jizalu\"\nOutput: true\nExplaination: Split them at index 3:\naprefix = \"ula\", asuffix = \"cfd\"\nbprefix = \"jiz\", bsuffix = \"alu\"\nThen, aprefix + bsuffix = \"ula\" + \"alu\" = \"ulaalu\", which is a palindrome.\n\nConstraints:\n- 1 <= a.length, b.length <= 10^5\n- a.length == b.length\n- a and b consist of lowercase English letters"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def checkPalindromeFormation(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: bool\n \"\"\"\n def is_palindrome(s, i, j):\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n\n def check(a, b):\n i, j = 0, len(b)-1\n while i < j:\n if a[i] != b[j]:\n return is_palindrome(a, i, j) or is_palindrome(b, i, j)\n i += 1\n j -= 1\n return True\n\n return check(a, b) or check(b, a)\n"}} diff --git a/cp/cp-11005.jsonl b/cp/cp-11005.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..559ca02b41d9b30ec56a6fae67cd01aa68a9805d --- /dev/null +++ b/cp/cp-11005.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11005", "name": "LeetCode 1617: Count Subtrees With Max Distance Between Cities"} +{"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: Count Subtrees With Max Distance Between Cities (Difficulty: Hard)\nTags: Dynamic Programming, Bit Manipulation, Tree, Enumeration, Bitmask\n\nThere are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree.\nA subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other.\nFor each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d.\nReturn an array of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d.\nNotice that the distance between the two cities is the number of edges in the path between them.\n\nExample 1:\nInput: n = 4, edges = [[1,2],[2,3],[2,4]]\r\nOutput: [3,4,0]\r\nExplanation:\r\nThe subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.\r\nThe subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.\r\nNo subtree has two nodes where the max distance between them is 3.\n\nExample 2:\nInput: n = 2, edges = [[1,2]]\r\nOutput: [1]\n\nExample 3:\nInput: n = 3, edges = [[1,2],[2,3]]\r\nOutput: [2,1]\n\nConstraints:\n- 2 <= n <= 15\n- edges.length == n-1\n- edges[i].length == 2\n- 1 <= ui, vi <= n\n- All pairs (ui, vi) are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^6)\n# Space: O(n^3)\n\nimport collections\n\n\nclass Solution(object):\n def countSubgraphsForEachDiameter(self, n, edges):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :rtype: List[int]\n \"\"\"\n def dfs(n, adj, curr, parent, lookup, count, dp):\n for child in adj[curr]:\n if child == parent or lookup[child]:\n continue\n dfs(n, adj, child, curr, lookup, count, dp)\n dp[curr][0][0] = 1\n for child in adj[curr]:\n if child == parent or lookup[child]:\n continue\n new_dp_curr = [row[:] for row in dp[curr]]\n for curr_d in range(count[curr]):\n for curr_max_d in range(curr_d, min(2*curr_d+1, count[curr])):\n if not dp[curr][curr_d][curr_max_d]: # pruning\n continue\n for child_d in range(count[child]):\n for child_max_d in range(child_d, min(2*child_d+1, count[child])):\n new_dp_curr[max(curr_d, child_d+1)][max(curr_max_d, child_max_d, curr_d+child_d+1)] += \\\n dp[curr][curr_d][curr_max_d]*dp[child][child_d][child_max_d] # count subtrees with new child\n count[curr] += count[child] # merge new child\n dp[curr] = new_dp_curr\n\n adj = collections.defaultdict(list)\n for u, v in edges:\n u -= 1\n v -= 1\n adj[u].append(v)\n adj[v].append(u)\n lookup, result = [0]*n, [0]*(n-1)\n for i in range(n): # Time: sum(O(k^5) for k in [1, n]) = O(n^6)\n dp = [[[0]*n for _ in range(n)] for _ in range(n)]\n count = [1]*n\n dfs(n, adj, i, -1, lookup, count, dp) # Time: O(k^5), k is the number of the remaining cities\n lookup[i] = 1\n for d in range(1, n): # for each depth from city i\n for max_d in range(d, min(2*d+1, n)): # for each max distance\n result[max_d-1] += dp[i][d][max_d]\n return result\n \n\n# Time: O(n * 2^n)\n# Space: O(n)\nimport collections\nimport math\n\n\nclass Solution2(object):\n def countSubgraphsForEachDiameter(self, n, edges):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :rtype: List[int]\n \"\"\"\n def popcount(mask):\n count = 0\n while mask:\n mask &= mask-1\n count += 1\n return count\n\n def bfs(adj, mask, start):\n q = collections.deque([(start, 0)])\n lookup = 1<= 0:\n result[max_d-1] += 1\n return result\n\n"}} diff --git a/cp/cp-11007.jsonl b/cp/cp-11007.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2bdc13b54f024381075956dc38336db1e5af0bc7 --- /dev/null +++ b/cp/cp-11007.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11007", "name": "LeetCode 1619: Mean Of Array After Removing Some 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: Mean of Array After Removing Some Elements (Difficulty: Easy)\nTags: Array, Sorting\n\nGiven an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.\nAnswers within 10-5 of the actual answer will be considered accepted.\n\nExample 1:\nInput: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]\nOutput: 2.00000\nExplanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.\n\nExample 2:\nInput: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]\nOutput: 4.00000\n\nExample 3:\nInput: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]\nOutput: 4.77778\n\nConstraints:\n- 20 <= arr.length <= 1000\n- arr.length is a multiple of 20.\n- 0 <= arr[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n) on average, using Median of Medians could achieve O(n) (Intro Select)\n# Space: O(1)\n\nimport random\n\n\nclass Solution(object):\n def trimMean(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: float\n \"\"\"\n P = 20\n def nth_element(nums, n, left=0, compare=lambda a, b: a < b):\n def tri_partition(nums, left, right, target, compare):\n mid = left\n while mid <= right:\n if nums[mid] == target:\n mid += 1\n elif compare(nums[mid], target):\n nums[left], nums[mid] = nums[mid], nums[left]\n left += 1\n mid += 1\n else:\n nums[mid], nums[right] = nums[right], nums[mid]\n right -= 1\n return left, right\n\n right = len(nums)-1\n while left <= right:\n pivot_idx = random.randint(left, right)\n pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)\n if pivot_left <= n <= pivot_right:\n return\n elif pivot_left > n:\n right = pivot_left-1\n else: # pivot_right < n.\n left = pivot_right+1\n \n k = len(arr)//P\n nth_element(arr, k-1)\n nth_element(arr, len(arr)-k, left=k)\n return float(sum(arr[i] for i in range(k, len(arr)-k)))/(len(arr)-2*k)\n"}} diff --git a/cp/cp-11008.jsonl b/cp/cp-11008.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b6cd5737127f812ebe190443a8588e3083c002b9 --- /dev/null +++ b/cp/cp-11008.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11008", "name": "LeetCode 1620: Coordinate With Maximum Network Quality"} +{"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: Coordinate With Maximum Network Quality (Difficulty: Medium)\nTags: Array, Enumeration\n\nYou are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance.\nYou are also given an integer radius where a tower is reachable if the distance is less than or equal to radius. Outside that distance, the signal becomes garbled, and the tower is not reachable.\nThe signal quality of the ith tower at a coordinate (x, y) is calculated with the formula ⌊qi / (1 + d)⌋, where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers.\nReturn the array [cx, cy] representing the integral coordinate (cx, cy) where the network quality is maximum. If there are multiple coordinates with the same network quality, return the lexicographically minimum non-negative coordinate.\nNote:\n\nExample 1:\nInput: towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2\nOutput: [2,1]\nExplanation: At coordinate (2, 1) the total quality is 13.\n- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7\n- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2\n- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4\nNo other coordinate has a higher network quality.\n\nExample 2:\nInput: towers = [[23,11,21]], radius = 9\nOutput: [23,11]\nExplanation: Since there is only one tower, the network quality is highest right at the tower's location.\n\nExample 3:\nInput: towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2\nOutput: [1,2]\nExplanation: Coordinate (1, 2) has the highest network quality.\n\nConstraints:\n- 1 <= towers.length <= 50\n- towers[i].length == 3\n- 0 <= xi, yi, qi <= 50\n- 1 <= radius <= 50"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(1)\n\nclass Solution(object):\n def bestCoordinate(self, towers, radius):\n \"\"\"\n :type towers: List[List[int]]\n :type radius: int\n :rtype: List[int]\n \"\"\"\n min_x = min(towers, key=lambda x:x[0])[0]\n max_x = max(towers, key=lambda x:x[0])[0]\n min_y = min(towers, key=lambda x:x[1])[1]\n max_y = max(towers, key=lambda x:x[1])[1]\n max_quality = 0\n for x in range(min_x, max_x+1):\n for y in range(min_y, max_y+1):\n q = 0\n for nx, ny, nq in towers:\n d = ((nx-x)**2+(ny-y)**2)**0.5\n if d <= radius:\n q += int(nq/(1+d))\n if q > max_quality:\n max_quality = q\n result = x, y\n return result\n"}} diff --git a/cp/cp-11009.jsonl b/cp/cp-11009.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..171b291fe57ef7fd50259f2f0dfcdd254ea8cdac --- /dev/null +++ b/cp/cp-11009.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11009", "name": "LeetCode 1621: Number Of Sets Of K Non Overlapping Line Segments"} +{"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 Sets of K Non-Overlapping Line Segments (Difficulty: Medium)\nTags: Math, Dynamic Programming, Combinatorics\n\nGiven n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints.\nReturn the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 109 + 7.\n\nExample 1:\nInput: n = 4, k = 2\nOutput: 5\nExplanation: The two line segments are shown in red and blue.\nThe image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.\n\nExample 2:\nInput: n = 3, k = 1\nOutput: 3\nExplanation: The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.\n\nExample 3:\nInput: n = 30, k = 7\nOutput: 796297179\nExplanation: The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.\n\nConstraints:\n- 2 <= n <= 1000\n- 1 <= k <= n-1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1), excluding precomputation time\n# Space: O(n)\n\n# precompute\nMOD = 10**9+7\nMAX_N = 1000\nfact = [0]*(2*MAX_N-1+1)\ninv = [0]*(2*MAX_N-1+1)\ninv_fact = [0]*(2*MAX_N-1+1)\nfact[0] = inv_fact[0] = fact[1] = inv_fact[1] = inv[1] = 1\nfor i in range(2, len(fact)):\n fact[i] = fact[i-1]*i % MOD\n inv[i] = inv[MOD%i]*(MOD-MOD//i) % MOD # https://cp-algorithms.com/algebra/module-inverse.html\n inv_fact[i] = inv_fact[i-1]*inv[i] % MOD\n\nclass Solution(object):\n def numberOfSets(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n def nCr(n, k, mod):\n return (fact[n]*inv_fact[n-k] % mod) * inv_fact[k] % mod\n \n # find k segments with 1+ length and (k+1) spaces with 0+ length s.t. total length is n-1\n # => find k segments with 0+ length and (k+1) spaces with 0+ length s.t. total length is n-k-1\n # => find the number of combinations of 2k+1 variables with total sum n-k-1\n # => H(2k+1, n-k-1)\n # => C((2k+1) + (n-k-1) - 1, n-k-1)\n # => C(n+k-1, n-k-1) = C(n+k-1, 2k)\n return nCr(n+k-1, 2*k, MOD)\n\n\n# Time: O(min(k, min(n - k)))\n# Space: O(1)\nclass Solution2(object):\n def numberOfSets(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n def nCr(n, r): # Time: O(n), Space: O(1)\n if n-r < r:\n return nCr(n, n-r)\n c = 1\n for k in range(1, r+1):\n c *= n-k+1\n c //= k\n return c\n \n # find k segments with 1+ length and (k+1) spaces with 0+ length s.t. total length is n-1\n # => find k segments with 0+ length and (k+1) spaces with 0+ length s.t. total length is n-k-1\n # => find the number of combinations of 2k+1 variables with total sum n-k-1\n # => H(2k+1, n-k-1)\n # => C((2k+1) + (n-k-1) - 1, n-k-1)\n # => C(n+k-1, n-k-1) = C(n+k-1, 2k)\n return nCr(n+k-1, 2*k) % MOD\n"}} diff --git a/cp/cp-11010.jsonl b/cp/cp-11010.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a0751a7e553163d697bc2de04bfc12bcfa32142d --- /dev/null +++ b/cp/cp-11010.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11010", "name": "LeetCode 1622: Fancy Sequence"} +{"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: Fancy Sequence (Difficulty: Hard)\nTags: Math, Design, Segment Tree\n\nWrite an API that generates fancy sequences using the append, addAll, and multAll operations.\nImplement the Fancy class:\n\nExample 1:\nInput\n[\"Fancy\", \"append\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"getIndex\", \"getIndex\"]\n[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]\nOutput\n[null, null, null, null, null, 10, null, null, null, 26, 34, 20]\n\nExplanation\nFancy fancy = new Fancy();\nfancy.append(2); // fancy sequence: [2]\nfancy.addAll(3); // fancy sequence: [2+3] -> [5]\nfancy.append(7); // fancy sequence: [5, 7]\nfancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14]\nfancy.getIndex(0); // return 10\nfancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17]\nfancy.append(10); // fancy sequence: [13, 17, 10]\nfancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]\nfancy.getIndex(0); // return 26\nfancy.getIndex(1); // return 34\nfancy.getIndex(2); // return 20\n\nConstraints:\n- 1 <= val, inc, m <= 100\n- 0 <= idx <= 10^5\n- At most 105 calls total will be made to append, addAll, multAll, and getIndex."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(n)\n\nMOD = 10**9+7\n\nclass Fancy(object):\n\n def __init__(self):\n self.__arr = []\n self.__ops = [[1, 0]]\n\n def append(self, val):\n \"\"\"\n :type val: int\n :rtype: None\n \"\"\"\n self.__arr.append(val)\n self.__ops.append(self.__ops[-1][:])\n\n def addAll(self, inc):\n \"\"\"\n :type inc: int\n :rtype: None\n \"\"\"\n self.__ops[-1][1] = (self.__ops[-1][1]+inc) % MOD\n\n def multAll(self, m):\n \"\"\"\n :type m: int\n :rtype: None\n \"\"\"\n self.__ops[-1] = [(self.__ops[-1][0]*m) % MOD, (self.__ops[-1][1]*m) % MOD]\n\n def getIndex(self, idx):\n \"\"\"\n :type idx: int\n :rtype: int\n \"\"\"\n if idx >= len(self.__arr):\n return -1\n a1, b1 = self.__ops[idx]\n a2, b2 = self.__ops[-1]\n a = a2*pow(a1, MOD-2, MOD)%MOD # O(logMOD), we treat it as O(1) here\n b = (b2 - b1*a) % MOD\n return (self.__arr[idx]*a + b) % MOD\n\n\n# Time: O(1)\n# Space: O(n)\nclass Fancy2(object):\n\n def __init__(self):\n self.__arr = []\n self.__op = [1, 0]\n\n def append(self, val):\n \"\"\"\n :type val: int\n :rtype: None\n \"\"\"\n self.__arr.append((val-self.__op[1])*pow(self.__op[0], MOD-2, MOD)%MOD) # O(logMOD), we treat it as O(1) here\n\n def addAll(self, inc):\n \"\"\"\n :type inc: int\n :rtype: None\n \"\"\"\n self.__op[1] = (self.__op[1]+inc) % MOD\n\n def multAll(self, m):\n \"\"\"\n :type m: int\n :rtype: None\n \"\"\"\n self.__op = [(self.__op[0]*m) % MOD, (self.__op[1]*m) % MOD]\n\n def getIndex(self, idx):\n \"\"\"\n :type idx: int\n :rtype: int\n \"\"\"\n if idx >= len(self.__arr):\n return -1\n a, b = self.__op\n return (self.__arr[idx]*a + b) % MOD\n"}} diff --git a/cp/cp-11011.jsonl b/cp/cp-11011.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..099b68e47dabac032468b160f270f48cdd1ffdb4 --- /dev/null +++ b/cp/cp-11011.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11011", "name": "LeetCode 1624: Largest Substring Between Two Equal Characters"} +{"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: Largest Substring Between Two Equal Characters (Difficulty: Easy)\nTags: Hash Table, String\n\nGiven a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.\nA substring is a contiguous sequence of characters within a string.\n\nExample 1:\nInput: s = \"aa\"\nOutput: 0\nExplanation: The optimal substring here is an empty substring between the two 'a's.\n\nExample 2:\nInput: s = \"abca\"\nOutput: 2\nExplanation: The optimal substring here is \"bc\".\n\nExample 3:\nInput: s = \"cbzxy\"\nOutput: -1\nExplanation: There are no characters that appear twice in s.\n\nConstraints:\n- 1 <= s.length <= 300\n- s contains only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxLengthBetweenEqualCharacters(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result, lookup = -1, {}\n for i, c in enumerate(s):\n result = max(result, i-lookup.setdefault(c, i)-1)\n return result\n"}} diff --git a/cp/cp-11012.jsonl b/cp/cp-11012.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5201efd7283d8058ff3ba1248a91829d87b625e1 --- /dev/null +++ b/cp/cp-11012.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11012", "name": "LeetCode 1625: Lexicographically Smallest String After Applying Operations"} +{"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: Lexicographically Smallest String After Applying Operations (Difficulty: Medium)\nTags: String, Depth-First Search, Breadth-First Search, Enumeration\n\nYou are given a string s of even length consisting of digits from 0 to 9, and two integers a and b.\nYou can apply either of the following two operations any number of times and in any order on s:\nReturn the lexicographically smallest string you can obtain by applying the above operations any number of times on s.\nA string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, \"0158\" is lexicographically smaller than \"0190\" because the first position they differ is at the third letter, and '5' comes before '9'.\n\nExample 1:\nInput: s = \"5525\", a = 9, b = 2\nOutput: \"2050\"\nExplanation: We can apply the following operations:\nStart: \"5525\"\nRotate: \"2555\"\nAdd: \"2454\"\nAdd: \"2353\"\nRotate: \"5323\"\nAdd: \"5222\"\nAdd: \"5121\"\nRotate: \"2151\"\nAdd: \"2050\"​​​​​\nThere is no way to obtain a string that is lexicographically smaller than \"2050\".\n\nExample 2:\nInput: s = \"74\", a = 5, b = 1\nOutput: \"24\"\nExplanation: We can apply the following operations:\nStart: \"74\"\nRotate: \"47\"\n​​​​​​​Add: \"42\"\n​​​​​​​Rotate: \"24\"​​​​​​​​​​​​\nThere is no way to obtain a string that is lexicographically smaller than \"24\".\n\nExample 3:\nInput: s = \"0011\", a = 4, b = 2\nOutput: \"0011\"\nExplanation: There are no sequence of operations that will give us a lexicographically smaller string than \"0011\".\n\nConstraints:\n- 2 <= s.length <= 100\n- s.length is even.\n- s consists of digits from 0 to 9 only.\n- 1 <= a <= 9\n- 1 <= b <= s.length - 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(100 * n^2) = O(n^2)\n# Space: O(1)\n\nclass Solution(object):\n def findLexSmallestString(self, s, a, b):\n \"\"\"\n :type s: str\n :type a: int\n :type b: int\n :rtype: str\n \"\"\"\n def less(s, i, j):\n for k in range(len(s)):\n if s[(k+i)%len(s)] != s[(k+j)%len(s)]:\n return s[(k+i)%len(s)] < s[(k+j)%len(s)]\n return False\n\n s = list(s)\n result = s[:]\n even = [False]*10\n while not even[int(s[0])]: # at most O(10) times\n even[int(s[0])] = True\n odd = [False]*10\n while not odd[int(s[1])]: # at most O(10) times\n odd[int(s[1])] = True\n best_rotate = 0\n lookup = [False]*len(s)\n i = b\n while not lookup[i]: # find best rotation, at most O(n) times\n lookup[i] = True\n if less(s, i, best_rotate): # O(n) time\n best_rotate = i\n i = (i+b)%len(s)\n result = min(result, s[best_rotate:] + s[:best_rotate])\n for k in range(1, len(s), 2): # flip odd index\n s[k] = str((int(s[k])+a) % 10)\n if b%2: # if rotate length is odd, even index could be also flipped\n for k in range(0, len(s), 2): # flip even index\n s[k] = str((int(s[k])+a) % 10)\n return \"\".join(result)\n\n\n# Time: O(100 * n^2), at most O(100n) strings and each compare costs O(n)\n# Space: O(n^2)\nimport collections\n\n\nclass Solution2(object):\n def findLexSmallestString(self, s, a, b):\n \"\"\"\n :type s: str\n :type a: int\n :type b: int\n :rtype: str\n \"\"\"\n q, lookup, result = collections.deque([s]), {s}, s\n while q:\n curr = q.popleft()\n if curr < result:\n result = curr\n add_a = list(curr) \n for i, c in enumerate(add_a):\n if i%2:\n add_a[i] = str((int(c)+a) % 10)\n add_a = \"\".join(add_a) \n if add_a not in lookup:\n lookup.add(add_a)\n q.append(add_a)\n rotate_b = curr[b:] + curr[:b]\n if rotate_b not in lookup:\n lookup.add(rotate_b)\n q.append(rotate_b)\n return result\n"}} diff --git a/cp/cp-11013.jsonl b/cp/cp-11013.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..80426089adae8f8928dfdaadb1822125c54ef17d --- /dev/null +++ b/cp/cp-11013.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11013", "name": "LeetCode 1626: Best Team With No Conflicts"} +{"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: Best Team With No Conflicts (Difficulty: Medium)\nTags: Array, Dynamic Programming, Sorting\n\nYou are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.\nHowever, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.\nGiven two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams.\n\nExample 1:\nInput: scores = [1,3,5,10,15], ages = [1,2,3,4,5]\nOutput: 34\nExplanation: You can choose all the players.\n\nExample 2:\nInput: scores = [4,5,6,5], ages = [2,1,2,1]\nOutput: 16\nExplanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.\n\nExample 3:\nInput: scores = [1,2,3,5], ages = [8,9,10,1]\nOutput: 6\nExplanation: It is best to choose the first 3 players.\n\nConstraints:\n- 1 <= scores.length, ages.length <= 1000\n- scores.length == ages.length\n- 1 <= scores[i] <= 10^6\n- 1 <= ages[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nloga)\n# Space: O(n)\n\n# Range Maximum Query\nclass SegmentTree(object): # 0-based index\n def __init__(self, N,\n build_fn=lambda x, y: [y]*(2*x),\n query_fn=lambda x, y: y if x is None else max(x, y), # (lambda x, y: y if x is None else min(x, y))\n update_fn=lambda x, y: y,\n default_val=0):\n self.N = N\n self.H = (N-1).bit_length()\n self.query_fn = query_fn\n self.update_fn = update_fn\n self.default_val = default_val\n self.tree = build_fn(N, default_val)\n self.lazy = [None]*N\n\n def __apply(self, x, val):\n self.tree[x] = self.update_fn(self.tree[x], val)\n if x < self.N:\n self.lazy[x] = self.update_fn(self.lazy[x], val)\n\n def update(self, L, R, h): # Time: O(logN), Space: O(N)\n def pull(x):\n while x > 1:\n x //= 2\n self.tree[x] = self.query_fn(self.tree[x*2], self.tree[x*2+1])\n if self.lazy[x] is not None:\n self.tree[x] = self.update_fn(self.tree[x], self.lazy[x])\n\n L += self.N\n R += self.N\n L0, R0 = L, R\n while L <= R:\n if L & 1: # is right child\n self.__apply(L, h) \n L += 1\n if R & 1 == 0: # is left child\n self.__apply(R, h)\n R -= 1\n L //= 2\n R //= 2\n pull(L0)\n pull(R0)\n\n def query(self, L, R): # Time: O(logN), Space: O(N)\n def push(x):\n n = 2**self.H\n while n != 1:\n y = x // n\n if self.lazy[y] is not None:\n self.__apply(y*2, self.lazy[y])\n self.__apply(y*2 + 1, self.lazy[y])\n self.lazy[y] = None\n n //= 2\n\n result = None\n if L > R:\n return result\n\n L += self.N\n R += self.N\n push(L)\n push(R)\n while L <= R:\n if L & 1: # is right child\n result = self.query_fn(result, self.tree[L])\n L += 1\n if R & 1 == 0: # is left child\n result = self.query_fn(result, self.tree[R])\n R -= 1\n L //= 2\n R //= 2\n return result\n \n def __str__(self):\n showList = []\n for i in range(self.N):\n showList.append(self.query(i, i))\n return \",\".join(map(str, showList))\n\n\n# optimized from Solution3\nclass Solution(object):\n def bestTeamScore(self, scores, ages):\n \"\"\"\n :type scores: List[int]\n :type ages: List[int]\n :rtype: int\n \"\"\"\n players = sorted(zip(scores, ages))\n sorted_ages = sorted(set(ages))\n lookup = {age:i for i, age in enumerate(sorted_ages)} # coordinate compression\n segment_tree = SegmentTree(len(lookup))\n result = 0\n for score, age in players:\n segment_tree.update(lookup[age], lookup[age], segment_tree.query(0, lookup[age])+score)\n return segment_tree.query(0, len(lookup)-1)\n\n\n# Time: O(nlogs)\n# Space: O(n)\n# optimized from Solution4\nclass Solution2(object):\n def bestTeamScore(self, scores, ages):\n \"\"\"\n :type scores: List[int]\n :type ages: List[int]\n :rtype: int\n \"\"\"\n players = sorted(zip(ages, scores))\n sorted_scores = sorted(set(scores))\n lookup = {score:i for i, score in enumerate(sorted_scores)} # coordinate compression\n segment_tree = SegmentTree(len(lookup))\n result = 0\n for age, score in players:\n segment_tree.update(lookup[score], lookup[score], segment_tree.query(0, lookup[score])+score)\n return segment_tree.query(0, len(lookup)-1)\n \n\n# Time: O(n * a)\n# Space: O(n)\nimport collections\n\n\n# optimized from Solution5\nclass Solution3(object):\n def bestTeamScore(self, scores, ages):\n \"\"\"\n :type scores: List[int]\n :type ages: List[int]\n :rtype: int\n \"\"\"\n players = sorted(zip(scores, ages))\n sorted_ages = sorted(set(ages))\n dp = collections.defaultdict(int)\n result = 0\n for score, age in players:\n dp[age] = max(dp[a] for a in sorted_ages if a <= age) + score\n return max(dp.itervalues())\n\n\n# Time: O(n * s)\n# Space: O(n)\nimport collections\n\n\n# optimized from Solution6\nclass Solution4(object):\n def bestTeamScore(self, scores, ages):\n \"\"\"\n :type scores: List[int]\n :type ages: List[int]\n :rtype: int\n \"\"\"\n players = sorted(zip(ages, scores))\n sorted_scores = sorted(set(scores))\n dp = collections.defaultdict(int)\n result = 0\n for age, score in players:\n dp[score] = max(dp[s] for s in sorted_scores if s <= score) + score\n return max(dp.itervalues())\n\n\n# Time: O(n^2)\n# Space: O(n)\n# longest_increasing_subsequence like dp solution\nclass Solution5(object):\n def bestTeamScore(self, scores, ages):\n \"\"\"\n :type scores: List[int]\n :type ages: List[int]\n :rtype: int\n \"\"\"\n players = sorted(zip(scores, ages))\n dp = [0]*len(players)\n result = 0\n for i in range(len(players)):\n dp[i] = players[i][0]\n for j in range(i):\n if players[j][1] <= players[i][1]:\n dp[i] = max(dp[i], dp[j] + players[i][0])\n result = max(result, dp[i])\n return result\n\n\n# Time: O(n^2)\n# Space: O(n)\n# longest_increasing_subsequence like dp solution\nclass Solution6(object):\n def bestTeamScore(self, scores, ages):\n \"\"\"\n :type scores: List[int]\n :type ages: List[int]\n :rtype: int\n \"\"\"\n players = sorted(zip(ages, scores))\n dp = [0]*len(players)\n result = 0\n for i in range(len(players)):\n dp[i] = players[i][1]\n for j in range(i):\n if players[j][1] <= players[i][1]:\n dp[i] = max(dp[i], dp[j] + players[i][1])\n result = max(result, dp[i])\n return result\n"}} diff --git a/cp/cp-11014.jsonl b/cp/cp-11014.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..de8390c29b7d59b1d7be324a8b3b854f3f864910 --- /dev/null +++ b/cp/cp-11014.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11014", "name": "LeetCode 1627: Graph Connectivity With Threshold"} +{"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: Graph Connectivity With Threshold (Difficulty: Hard)\nTags: Array, Math, Union Find, Number Theory\n\nWe have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold. More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true:\nGiven the two integers, n and threshold, and an array of queries, you must determine for each queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly. (i.e. there is some path between them).\nReturn an array answer, where answer.length == queries.length and answer[i] is true if for the ith query, there is a path between ai and bi, or answer[i] is false if there is no path.\n\nExample 1:\nInput: n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]\nOutput: [false,false,true]\nExplanation: The divisors for each number:\n1: 1\n2: 1, 2\n3: 1, 3\n4: 1, 2, 4\n5: 1, 5\n6: 1, 2, 3, 6\nUsing the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the\nonly ones directly connected. The result of each query:\n[1,4] 1 is not connected to 4\n[2,5] 2 is not connected to 5\n[3,6] 3 is connected to 6 through path 3--6\n\nExample 2:\nInput: n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]\nOutput: [true,true,true,true,true]\nExplanation: The divisors for each number are the same as the previous example. However, since the threshold is 0,\nall divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.\n\nExample 3:\nInput: n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]\nOutput: [false,false,false,false,false]\nExplanation: Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.\nPlease notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].\n\nConstraints:\n- 2 <= n <= 10^4\n- 0 <= threshold <= n\n- 1 <= queries.length <= 10^5\n- queries[i].length == 2\n- 1 <= ai, bi <= cities\n- ai != bi"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((nlogn + q) * α(n)) ~= O(nlogn + q)\n# Space: O(n)\n\nclass UnionFind(object): # Time: O(n * α(n)), Space: O(n)\n def __init__(self, n):\n self.set = range(n)\n self.rank = [0]*n\n\n def find_set(self, x):\n stk = []\n while self.set[x] != x: # path compression\n stk.append(x)\n x = self.set[x]\n while stk:\n self.set[stk.pop()] = x\n return x\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n if self.rank[x_root] < self.rank[y_root]: # union by rank\n self.set[x_root] = y_root\n elif self.rank[x_root] > self.rank[y_root]:\n self.set[y_root] = x_root\n else:\n self.set[y_root] = x_root\n self.rank[x_root] += 1\n return True\n\n\nclass Solution(object):\n def areConnected(self, n, threshold, queries):\n \"\"\"\n :type n: int\n :type threshold: int\n :type queries: List[List[int]]\n :rtype: List[bool]\n \"\"\"\n union_find = UnionFind(n)\n for i in range(threshold+1, n+1):\n # https://stackoverflow.com/questions/25905118/finding-big-o-of-the-harmonic-series\n # sum of harmonic series is O(logn)\n for j in range(2*i, n+1, i): # step by i\n union_find.union_set(i-1, j-1)\n return [union_find.find_set(q[0]-1) == union_find.find_set(q[1]-1) for q in queries]\n"}} diff --git a/cp/cp-11016.jsonl b/cp/cp-11016.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e2c9e86b1285323e4e85e69fd75175436f58d2bc --- /dev/null +++ b/cp/cp-11016.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11016", "name": "LeetCode 1629: Slowest Key"} +{"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: Slowest Key (Difficulty: Easy)\nTags: Array, String\n\nA newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.\nYou are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released.\nThe tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0].\nNote that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration.\nReturn the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses.\n\nExample 1:\nInput: releaseTimes = [9,29,49,50], keysPressed = \"cbcd\"\nOutput: \"c\"\nExplanation: The keypresses were as follows:\nKeypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).\nKeypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).\nKeypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).\nKeypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).\nThe longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.\n'c' is lexicographically larger than 'b', so the answer is 'c'.\n\nExample 2:\nInput: releaseTimes = [12,23,36,46,62], keysPressed = \"spuda\"\nOutput: \"a\"\nExplanation: The keypresses were as follows:\nKeypress for 's' had a duration of 12.\nKeypress for 'p' had a duration of 23 - 12 = 11.\nKeypress for 'u' had a duration of 36 - 23 = 13.\nKeypress for 'd' had a duration of 46 - 36 = 10.\nKeypress for 'a' had a duration of 62 - 46 = 16.\nThe longest of these was the keypress for 'a' with duration 16.\n\nConstraints:\n- releaseTimes.length == n\n- keysPressed.length == n\n- 2 <= n <= 1000\n- 1 <= releaseTimes[i] <= 10^9\n- releaseTimes[i] < releaseTimes[i+1]\n- keysPressed contains only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def slowestKey(self, releaseTimes, keysPressed):\n \"\"\"\n :type releaseTimes: List[int]\n :type keysPressed: str\n :rtype: str\n \"\"\"\n result, lookup = 'a', collections.Counter()\n for i, c in enumerate(keysPressed):\n lookup[c] = max(lookup[c], releaseTimes[i]-(releaseTimes[i-1] if i > 0 else 0))\n if lookup[c] > lookup[result] or lookup[c] == lookup[result] and c > result:\n result = c\n return result\n"}} diff --git a/cp/cp-11017.jsonl b/cp/cp-11017.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..40461929588d2cb3a772808b13442eb0d61cfdd4 --- /dev/null +++ b/cp/cp-11017.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11017", "name": "LeetCode 1630: Arithmetic Subarrays"} +{"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: Arithmetic Subarrays (Difficulty: Medium)\nTags: Array, Hash Table, Sorting\n\nA sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i.\nFor example, these are arithmetic sequences:\nThe following sequence is not arithmetic:\nYou are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed.\nReturn a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise.\n\nExample 1:\n1, 3, 5, 7, 9\n7, 7, 7, 7\n3, -1, -5, -9\n\nExample 2:\n1, 1, 2, 5, 7\n\nExample 3:\nInput: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]\nOutput: [true,false,true]\nExplanation:\nIn the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.\nIn the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.\nIn the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an arithmetic sequence.\n\nExample 4:\nInput: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]\nOutput: [false,true,false,false,true,true]\n\nConstraints:\n- n == nums.length\n- m == l.length\n- m == r.length\n- 2 <= n <= 500\n- 1 <= m <= 500\n- 0 <= l[i] < r[i] < n\n- -10^5 <= nums[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * q)\n# Space: O(n)\n\nimport itertools\n\n\nclass Solution(object):\n def checkArithmeticSubarrays(self, nums, l, r):\n \"\"\"\n :type nums: List[int]\n :type l: List[int]\n :type r: List[int]\n :rtype: List[bool]\n \"\"\"\n def is_arith(n):\n mx, mn, lookup = max(n), min(n), set(n)\n if mx == mn:\n return True\n d, r = divmod(mx-mn, len(n)-1)\n if r:\n return False\n return all(i in lookup for i in range(mn, mx, d))\n \n result = []\n for left, right in itertools.izip(l, r):\n result.append(is_arith(nums[left:right+1]))\n return result\n"}} diff --git a/cp/cp-11018.jsonl b/cp/cp-11018.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d5dff39acc6829aa2095cdd89ed33d5d73972c69 --- /dev/null +++ b/cp/cp-11018.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11018", "name": "LeetCode 1631: Path With Minimum Effort"} +{"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: Path With Minimum Effort (Difficulty: Medium)\nTags: Array, Binary Search, Depth-First Search, Breadth-First Search, Union Find, Heap (Priority Queue), Matrix\n\nYou are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.\nA route's effort is the maximum absolute difference in heights between two consecutive cells of the route.\nReturn the minimum effort required to travel from the top-left cell to the bottom-right cell.\n\nExample 1:\nInput: heights = [[1,2,2],[3,8,2],[5,3,5]]\nOutput: 2\nExplanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\nThis is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.\n\nExample 2:\nInput: heights = [[1,2,3],[3,8,4],[5,3,5]]\nOutput: 1\nExplanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].\n\nExample 3:\nInput: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]\nOutput: 0\nExplanation: This route does not require any effort.\n\nConstraints:\n- rows == heights.length\n- columns == heights[i].length\n- 1 <= rows, columns <= 100\n- 1 <= heights[i][j] <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n * log(m * n))\n# Space: O(m * n)\n\nimport heapq\n\n\n# Dijkstra algorithm solution\nclass Solution(object):\n def minimumEffortPath(self, heights):\n \"\"\"\n :type heights: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n dst = (len(heights)-1, len(heights[0])-1)\n dist = [[float(\"inf\")]*len(heights[0]) for _ in range(len(heights))]\n dist[0][0] = 0\n min_heap = [(0, 0, 0)]\n lookup = [[False]*len(heights[0]) for _ in range(len(heights))]\n while min_heap:\n d, r, c = heapq.heappop(min_heap)\n if lookup[r][c]:\n continue\n lookup[r][c] = True\n if (r, c) == dst:\n return d\n for dr, dc in directions:\n nr, nc = r+dr, c+dc\n if not (0 <= nr < len(heights) and 0 <= nc < len(heights[0]) and not lookup[nr][nc]):\n continue\n nd = max(d, abs(heights[nr][nc]-heights[r][c]))\n if nd < dist[nr][nc]:\n dist[nr][nc] = nd\n heapq.heappush(min_heap, (nd, nr, nc))\n return -1\n\n\n# Time: O(m * n * log(m * n) + m * n * α(m * n)) = O(m * n * log(m * n))\n# Space: O(m * n)\nimport collections\n\n\nclass UnionFind(object): # Time: O(n * α(n)), Space: O(n)\n def __init__(self, n):\n self.set = range(n)\n self.rank = [0]*n\n\n def find_set(self, x):\n stk = []\n while self.set[x] != x: # path compression\n stk.append(x)\n x = self.set[x]\n while stk:\n self.set[stk.pop()] = x\n return x\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n if self.rank[x_root] < self.rank[y_root]: # union by rank\n self.set[x_root] = y_root\n elif self.rank[x_root] > self.rank[y_root]:\n self.set[y_root] = x_root\n else:\n self.set[y_root] = x_root\n self.rank[x_root] += 1\n return True\n\n\n# union find solution\nclass Solution2(object):\n def minimumEffortPath(self, heights):\n \"\"\"\n :type heights: List[List[int]]\n :rtype: int\n \"\"\"\n def index(n, i, j):\n return i*n + j\n \n diffs = []\n for i in range(len(heights)):\n for j in range(len(heights[0])):\n if i > 0:\n diffs.append((abs(heights[i][j]-heights[i-1][j]), index(len(heights[0]), i-1, j), index(len(heights[0]), i, j)))\n if j > 0:\n diffs.append((abs(heights[i][j]-heights[i][j-1]), index(len(heights[0]), i, j-1), index(len(heights[0]), i, j)))\n diffs.sort()\n union_find = UnionFind(len(heights)*len(heights[0]))\n for d, i, j in diffs:\n if union_find.union_set(i, j):\n if union_find.find_set(index(len(heights[0]), 0, 0)) == \\\n union_find.find_set(index(len(heights[0]), len(heights)-1, len(heights[0])-1)):\n return d\n return 0\n\n\n# Time: O(m * n * logh)\n# Space: O(m * n)\n# bi-bfs solution\nclass Solution3(object):\n def minimumEffortPath(self, heights):\n \"\"\"\n :type heights: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n def check(heights, x): # bi-bfs\n lookup = [[False]*len(heights[0]) for _ in range(len(heights))]\n left, right = {(0, 0)}, {(len(heights)-1, len(heights[0])-1)}\n while left:\n for r, c in left:\n lookup[r][c] = True\n new_left = set()\n for r, c in left:\n if (r, c) in right: \n return True\n for dr, dc in directions:\n nr, nc = r+dr, c+dc\n if not (0 <= nr < len(heights) and\n 0 <= nc < len(heights[0]) and\n abs(heights[nr][nc]-heights[r][c]) <= x and\n not lookup[nr][nc]):\n continue\n new_left.add((nr, nc))\n left = new_left\n if len(left) > len(right): \n left, right = right, left\n return False \n \n\n left, right = 0, 10**6\n while left <= right:\n mid = left + (right-left)//2\n if check(heights, mid):\n right = mid-1\n else:\n left = mid+1\n return left\n\n\n# Time: O(m * n * logh)\n# Space: O(m * n)\nimport collections\n\n\n# bfs solution\nclass Solution4(object):\n def minimumEffortPath(self, heights):\n \"\"\"\n :type heights: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n def check(heights, x):\n lookup = [[False]*len(heights[0]) for _ in range(len(heights))]\n q = collections.deque([(0, 0)])\n while q:\n r, c = q.popleft()\n if (r, c) == (len(heights)-1, len(heights[0])-1):\n return True\n for dr, dc in directions:\n nr, nc = r+dr, c+dc\n if not (0 <= nr < len(heights) and\n 0 <= nc < len(heights[0]) and\n abs(heights[nr][nc]-heights[r][c]) <= x and\n not lookup[nr][nc]):\n continue\n lookup[nr][nc] = True\n q.append((nr, nc))\n return False \n \n left, right = 0, 10**6\n while left <= right:\n mid = left + (right-left)//2\n if check(heights, mid):\n right = mid-1\n else:\n left = mid+1\n return left\n\n\n# Time: O(m * n * logh)\n# Space: O(m * n)\n# dfs solution\nclass Solution5(object):\n def minimumEffortPath(self, heights):\n \"\"\"\n :type heights: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n def check(heights, x):\n lookup = [[False]*len(heights[0]) for _ in range(len(heights))]\n stk = [(0, 0)]\n while stk:\n r, c = stk.pop()\n if (r, c) == (len(heights)-1, len(heights[0])-1):\n return True\n for dr, dc in directions:\n nr, nc = r+dr, c+dc\n if not (0 <= nr < len(heights) and\n 0 <= nc < len(heights[0]) and\n abs(heights[nr][nc]-heights[r][c]) <= x and\n not lookup[nr][nc]):\n continue\n lookup[nr][nc] = True\n stk.append((nr, nc))\n return False \n \n left, right = 0, 10**6\n while left <= right:\n mid = left + (right-left)//2\n if check(heights, mid):\n right = mid-1\n else:\n left = mid+1\n return left\n"}} diff --git a/cp/cp-11019.jsonl b/cp/cp-11019.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1c4f4695c6892bd390b352c7d82bb5b92a382877 --- /dev/null +++ b/cp/cp-11019.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11019", "name": "LeetCode 1632: Rank Transform Of A Matrix"} +{"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: Rank Transform of a Matrix (Difficulty: Hard)\nTags: Array, Union Find, Graph, Topological Sort, Sorting, Matrix\n\nGiven an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col].\nThe rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules:\nThe test cases are generated so that answer is unique under the given rules.\n\nExample 1:\nInput: matrix = [[1,2],[3,4]]\nOutput: [[1,2],[2,3]]\nExplanation:\nThe rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.\nThe rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.\n\nExample 2:\nInput: matrix = [[7,7],[7,7]]\nOutput: [[1,1],[1,1]]\n\nExample 3:\nInput: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]\nOutput: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]\n\nConstraints:\n- m == matrix.length\n- n == matrix[i].length\n- 1 <= m, n <= 500\n- -10^9 <= matrix[row][col] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n * log(m * n) + m * n * α(m * n)) = O(m * n * log(m * n))\n# Space: O(m * n)\n\nimport collections\n\n\nclass UnionFind(object): # Time: O(n * α(n)), Space: O(n)\n def __init__(self, n, cb):\n self.set = range(n)\n self.rank = [0]*n\n self.cb = cb\n\n def find_set(self, x):\n stk = []\n while self.set[x] != x: # path compression\n stk.append(x)\n x = self.set[x]\n while stk:\n self.set[stk.pop()] = x\n return x\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n if self.rank[x_root] < self.rank[y_root]: # union by rank\n self.set[x_root] = y_root\n self.cb(y_root, x_root, y_root)\n elif self.rank[x_root] > self.rank[y_root]:\n self.set[y_root] = x_root\n self.cb(x_root, x_root, y_root)\n else:\n self.set[y_root] = x_root\n self.rank[x_root] += 1\n self.cb(x_root, x_root, y_root)\n return True\n\n\nclass Solution(object):\n def matrixRankTransform(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n def cb(x, y, z):\n new_rank[x] = max(new_rank[y], new_rank[z])\n\n lookup = collections.defaultdict(list)\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n lookup[matrix[i][j]].append([i, j])\n rank = [0]*(len(matrix)+len(matrix[0]))\n for x in sorted(lookup):\n new_rank = rank[:]\n union_find = UnionFind(len(matrix)+len(matrix[0]), cb)\n for i, j in lookup[x]:\n union_find.union_set(i, j+len(matrix))\n for i, j in lookup[x]:\n matrix[i][j] = rank[i] = rank[j+len(matrix)] = new_rank[union_find.find_set(i)]+1\n return matrix\n"}} diff --git a/cp/cp-11022.jsonl b/cp/cp-11022.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2b06fda46c5efe9a524f44203aaa5f21a0c07131 --- /dev/null +++ b/cp/cp-11022.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11022", "name": "LeetCode 1637: Widest Vertical Area Between Two Points Containing No Points"} +{"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: Widest Vertical Area Between Two Points Containing No Points (Difficulty: Easy)\nTags: Array, Sorting\n\nGiven n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area.\nA vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.\nNote that points on the edge of a vertical area are not considered included in the area.\n\nExample 1:\nInput: points = [[8,7],[9,9],[7,4],[9,7]]\nOutput: 1\nExplanation: Both the red and the blue area are optimal.\n\nExample 2:\nInput: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]\nOutput: 3\n\nConstraints:\n- n == points.length\n- 2 <= n <= 10^5\n- points[i].length == 2\n- 0 <= xi, yi <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport itertools\n\n\nclass Solution(object):\n def maxWidthOfVerticalArea(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n sorted_x = sorted({x for x, y in points})\n return max([b-a for a, b in itertools.izip(sorted_x, sorted_x[1:])] + [0])\n"}} diff --git a/cp/cp-11023.jsonl b/cp/cp-11023.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..78752878650fb3f5c1b43b990a01858896561913 --- /dev/null +++ b/cp/cp-11023.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11023", "name": "LeetCode 1638: Count Substrings That Differ By One Character"} +{"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: Count Substrings That Differ by One Character (Difficulty: Medium)\nTags: Hash Table, String, Dynamic Programming, Enumeration\n\nGiven two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character.\nFor example, the underlined substrings in \"computer\" and \"computation\" only differ by the 'e'/'a', so this is a valid way.\nReturn the number of substrings that satisfy the condition above.\nA substring is a contiguous sequence of characters within a string.\n\nExample 1:\nInput: s = \"aba\", t = \"baba\"\nOutput: 6\nExplanation: The following are the pairs of substrings from s and t that differ by exactly 1 character:\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\nThe underlined portions are the substrings that are chosen from s and t.\n\nExample 2:\nInput: s = \"ab\", t = \"bb\"\nOutput: 3\nExplanation: The following are the pairs of substrings from s and t that differ by 1 character:\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n​​​​The underlined portions are the substrings that are chosen from s and t.\n\nConstraints:\n- 1 <= s.length, t.length <= 100\n- s and t consist of lowercase English letters only."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def countSubstrings(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: int\n \"\"\"\n def count(i, j): # for each possible alignment, count the number of substrs that differ by 1 char\n result = left_cnt = right_cnt = 0 # left and right consecutive same counts relative to the different char\n for k in range(min(len(s)-i, len(t)-j)):\n right_cnt += 1\n if s[i+k] != t[j+k]:\n left_cnt, right_cnt = right_cnt, 0\n # prev_i = i+k-prev+1\n result += left_cnt # target substrs are [s[left_i+c:i+k+1] for c in range(left_cnt)]\n return result\n\n return sum(count(i, 0) for i in range(len(s))) + \\\n sum(count(0, j) for j in range(1, len(t)))\n"}} diff --git a/cp/cp-11024.jsonl b/cp/cp-11024.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e99f073c2a5647f61fcbd6492d14b7694780b24d --- /dev/null +++ b/cp/cp-11024.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11024", "name": "LeetCode 1639: Number Of Ways To Form A Target String Given A 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: Number of Ways to Form a Target String Given a Dictionary (Difficulty: Hard)\nTags: Array, String, Dynamic Programming\n\nYou are given a list of strings of the same length words and a string target.\nYour task is to form target using the given words under the following rules:\nNotice that you can use multiple characters from the same string in words provided the conditions above are met.\nReturn the number of ways to form target from words. Since the answer may be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: words = [\"acca\",\"bbbb\",\"caca\"], target = \"aba\"\nOutput: 6\nExplanation: There are 6 ways to form target.\n\"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"caca\")\n\"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"caca\")\n\"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"acca\")\n\"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n\"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n\"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"caca\")\n\nExample 2:\nInput: words = [\"abba\",\"baab\"], target = \"bab\"\nOutput: 4\nExplanation: There are 4 ways to form target.\n\"bab\" -> index 0 (\"baab\"), index 1 (\"baab\"), index 2 (\"abba\")\n\"bab\" -> index 0 (\"baab\"), index 1 (\"baab\"), index 3 (\"baab\")\n\"bab\" -> index 0 (\"baab\"), index 2 (\"baab\"), index 3 (\"baab\")\n\"bab\" -> index 1 (\"abba\"), index 2 (\"baab\"), index 3 (\"baab\")\n\nConstraints:\n- 1 <= words.length <= 1000\n- 1 <= words[i].length <= 1000\n- All strings in words have the same length.\n- 1 <= target.length <= 1000\n- words[i] and target contain only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(l * (w + n)), l is the length of a word, w is the number of words, n is the length of target\n# Space: O(n)\n\nimport collections\n\n\n# optimized from Solution2\nclass Solution(object):\n def numWays(self, words, target):\n \"\"\"\n :type words: List[str]\n :type target: str\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n dp = [0]*(len(target)+1)\n dp[0] = 1\n for i in range(len(words[0])):\n count = collections.Counter(w[i] for w in words)\n for j in reversed(range(len(target))):\n dp[j+1] += dp[j]*count[target[j]] % MOD\n return dp[-1] % MOD\n\n\n# Time: O(l * (w + n)), l is the length of a word, w is the number of words, n is the length of target\n# Space: O(n)\nimport collections\n\n\nclass Solution2(object):\n def numWays(self, words, target):\n \"\"\"\n :type words: List[str]\n :type target: str\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n # dp[i+1][j+1]: number of ways of target[0..j] using count[0..i].\n dp = [[0]*(len(target)+1) for _ in range(2)]\n for i in range(len(dp)):\n dp[i][0] = 1\n for i in range(len(words[0])):\n count = collections.Counter(w[i] for w in words)\n for j in reversed(range(len(target))):\n dp[(i+1)%2][j+1] = dp[i%2][j+1]+dp[i%2][j]*count[target[j]] % MOD\n return dp[(len(words[0]))%2][-1] % MOD\n"}} diff --git a/cp/cp-11025.jsonl b/cp/cp-11025.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..49023df3d27c2a983d78a2e72d99a2d9bbe4fb3e --- /dev/null +++ b/cp/cp-11025.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11025", "name": "LeetCode 1640: Check Array Formation Through Concatenation"} +{"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: Check Array Formation Through Concatenation (Difficulty: Easy)\nTags: Array, Hash Table\n\nYou are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i].\nReturn true if it is possible to form the array arr from pieces. Otherwise, return false.\n\nExample 1:\nInput: arr = [15,88], pieces = [[88],[15]]\nOutput: true\nExplanation: Concatenate [15] then [88]\n\nExample 2:\nInput: arr = [49,18,16], pieces = [[16,18,49]]\nOutput: false\nExplanation: Even though the numbers match, we cannot reorder pieces[0].\n\nExample 3:\nInput: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]\nOutput: true\nExplanation: Concatenate [91] then [4,64] then [78]\n\nConstraints:\n- 1 <= pieces.length <= arr.length <= 100\n- sum(pieces[i].length) == arr.length\n- 1 <= pieces[i].length <= arr.length\n- 1 <= arr[i], pieces[i][j] <= 100\n- The integers in arr are distinct.\n- The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct)."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def canFormArray(self, arr, pieces):\n \"\"\"\n :type arr: List[int]\n :type pieces: List[List[int]]\n :rtype: bool\n \"\"\"\n lookup = {x[0]: i for i, x in enumerate(pieces)}\n i = 0\n while i < len(arr): \n if arr[i] not in lookup:\n return False\n for c in pieces[lookup[arr[i]]]:\n if i == len(arr) or arr[i] != c:\n return False\n i += 1\n return True \n"}} diff --git a/cp/cp-11026.jsonl b/cp/cp-11026.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ea43c8c934171fe16c688cbd1b6b53178499cd70 --- /dev/null +++ b/cp/cp-11026.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11026", "name": "LeetCode 1641: Count Sorted Vowel Strings"} +{"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: Count Sorted Vowel Strings (Difficulty: Medium)\nTags: Math, Dynamic Programming, Combinatorics\n\nGiven an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.\nA string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet.\n\nExample 1:\nInput: n = 1\nOutput: 5\nExplanation: The 5 sorted strings that consist of vowels only are [\"a\",\"e\",\"i\",\"o\",\"u\"].\n\nExample 2:\nInput: n = 2\nOutput: 15\nExplanation: The 15 sorted strings that consist of vowels only are\n[\"aa\",\"ae\",\"ai\",\"ao\",\"au\",\"ee\",\"ei\",\"eo\",\"eu\",\"ii\",\"io\",\"iu\",\"oo\",\"ou\",\"uu\"].\nNote that \"ea\" is not a valid string since 'e' comes after 'a' in the alphabet.\n\nExample 3:\nInput: n = 33\nOutput: 66045\n\nConstraints:\n- 1 <= n <= 50"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def countVowelStrings(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n def nCr(n, r): # Time: O(n), Space: O(1)\n if n-r < r:\n return nCr(n, n-r)\n c = 1\n for k in range(1, r+1):\n c *= n-k+1\n c //= k\n return c\n \n return nCr(n+4, 4) # H(5, n) = C(n+5-1, n) = C(n+4, 4)\n"}} diff --git a/cp/cp-11027.jsonl b/cp/cp-11027.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..08d307ab59aca6d278ee206f08b6ba8d9c7e7738 --- /dev/null +++ b/cp/cp-11027.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11027", "name": "LeetCode 1642: Furthest Building You Can Reach"} +{"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: Furthest Building You Can Reach (Difficulty: Medium)\nTags: Array, Greedy, Heap (Priority Queue)\n\nYou are given an integer array heights representing the heights of buildings, some bricks, and some ladders.\nYou start your journey from building 0 and move to the next building by possibly using bricks or ladders.\nWhile moving from building i to building i+1 (0-indexed),\nReturn the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.\n\nExample 1:\nInput: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1\nOutput: 4\nExplanation: Starting at building 0, you can follow these steps:\n- Go to building 1 without using ladders nor bricks since 4 >= 2.\n- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.\n- Go to building 3 without using ladders nor bricks since 7 >= 6.\n- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.\nIt is impossible to go beyond building 4 because you do not have any more bricks or ladders.\n\nExample 2:\nInput: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2\nOutput: 7\n\nExample 3:\nInput: heights = [14,3,19,3], bricks = 17, ladders = 0\nOutput: 3\n\nConstraints:\n- 1 <= heights.length <= 10^5\n- 1 <= heights[i] <= 10^6\n- 0 <= bricks <= 10^9\n- 0 <= ladders <= heights.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogk)\n# Space: O(k)\n\nimport heapq\n\n\nclass Solution(object):\n def furthestBuilding(self, heights, bricks, ladders):\n \"\"\"\n :type heights: List[int]\n :type bricks: int\n :type ladders: int\n :rtype: int\n \"\"\"\n min_heap = []\n for i in range(len(heights)-1):\n diff = heights[i+1]-heights[i]\n if diff > 0:\n heapq.heappush(min_heap, diff)\n if len(min_heap) <= ladders: # ladders are reserved for largest diffs\n continue\n bricks -= heapq.heappop(min_heap) # use bricks if ladders are not enough\n if bricks < 0: # not enough bricks\n return i\n return len(heights)-1\n"}} diff --git a/cp/cp-11028.jsonl b/cp/cp-11028.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1b4d0689c44f15209599f39447e0950a86b5a182 --- /dev/null +++ b/cp/cp-11028.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11028", "name": "LeetCode 1643: Kth Smallest Instructions"} +{"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 Instructions (Difficulty: Hard)\nTags: Array, Math, Dynamic Programming, Combinatorics\n\nBob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination.\nThe instructions are represented as a string, where each character is either:\nMultiple instructions will lead Bob to destination. For example, if destination is (2, 3), both \"HHHVV\" and \"HVHVH\" are valid instructions.\nHowever, Bob is very picky. Bob has a lucky number k, and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed.\nGiven an integer array destination and an integer k, return the kth lexicographically smallest instructions that will take Bob to destination.\n\nExample 1:\nInput: destination = [2,3], k = 1\nOutput: \"HHHVV\"\nExplanation: All the instructions that reach (2, 3) in lexicographic order are as follows:\n[\"HHHVV\", \"HHVHV\", \"HHVVH\", \"HVHHV\", \"HVHVH\", \"HVVHH\", \"VHHHV\", \"VHHVH\", \"VHVHH\", \"VVHHH\"].\n\nExample 2:\nInput: destination = [2,3], k = 2\nOutput: \"HHVHV\"\n\nExample 3:\nInput: destination = [2,3], k = 3\nOutput: \"HHVVH\"\n\nConstraints:\n- destination.length == 2\n- 1 <= row, column <= 15\n- 1 <= k <= nCr(row + column, row), where nCr(a, b) denotes a choose b​​​​​."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((m + n)^2)\n# Space: O(1)\n\nclass Solution(object):\n def kthSmallestPath(self, destination, k):\n \"\"\"\n :type destination: List[int]\n :type k: int\n :rtype: str\n \"\"\"\n def nCr(n, r): # Time: O(n), Space: O(1)\n if n < r:\n return 0\n if n-r < r:\n return nCr(n, n-r)\n c = 1\n for k in range(1, r+1):\n c *= n-k+1\n c //= k\n return c\n\n r, c = destination \n result = []\n while r+c:\n count = nCr(r+(c-1), r) # the number of HX..X combinations\n if k <= count: # the kth instruction is one of HX..X combinations, so go right\n c -= 1\n result.append('H')\n else: # the kth instruction is one of VX..X combinations, so go down\n k -= count # the kth one of XX..X combinations is the (k-count)th one of VX..X combinations\n r -= 1\n result.append('V')\n return \"\".join(result)\n"}} diff --git a/cp/cp-11030.jsonl b/cp/cp-11030.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c3910f7c8d8f195886f0406fb60977874c34aedf --- /dev/null +++ b/cp/cp-11030.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11030", "name": "LeetCode 1646: Get Maximum In Generated 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: Get Maximum in Generated Array (Difficulty: Easy)\nTags: Array, Simulation\n\nYou are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way:\nReturn the maximum integer in the array nums​​​.\n\nExample 1:\nInput: n = 7\nOutput: 3\nExplanation: According to the given rules:\n nums[0] = 0\n nums[1] = 1\n nums[(1 * 2) = 2] = nums[1] = 1\n nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2\n nums[(2 * 2) = 4] = nums[2] = 1\n nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3\n nums[(3 * 2) = 6] = nums[3] = 2\n nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3\nHence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3.\n\nExample 2:\nInput: n = 2\nOutput: 1\nExplanation: According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1.\n\nExample 3:\nInput: n = 3\nOutput: 2\nExplanation: According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2.\n\nConstraints:\n- 0 <= n <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nnums = [0, 1]\ndp = [0, 1]\nclass Solution(object):\n def getMaximumGenerated(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n+1 > len(dp):\n for i in range(len(nums), n+1):\n if i%2 == 0:\n nums.append(nums[i//2])\n else:\n nums.append(nums[i//2] + nums[i//2+1])\n dp.append(max(dp[-1], nums[-1]))\n return dp[n]\n\n\n# Time: O(n)\n# Space: O(n)\nclass Solution2(object):\n def getMaximumGenerated(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n == 0:\n return 0\n nums = [0]*(n+1)\n nums[1] = 1\n result = 1\n for i in range(2, n+1):\n if i%2 == 0:\n nums[i] = nums[i//2]\n else:\n nums[i] = nums[i//2] + nums[i//2+1]\n result = max(result, nums[i])\n return result\n"}} diff --git a/cp/cp-11031.jsonl b/cp/cp-11031.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9a80cc35e08da2449781cfe261739b6d237d54c0 --- /dev/null +++ b/cp/cp-11031.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11031", "name": "LeetCode 1647: Minimum Deletions To Make Character Frequencies Unique"} +{"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: Minimum Deletions to Make Character Frequencies Unique (Difficulty: Medium)\nTags: Hash Table, String, Greedy, Sorting\n\nA string s is called good if there are no two different characters in s that have the same frequency.\nGiven a string s, return the minimum number of characters you need to delete to make s good.\nThe frequency of a character in a string is the number of times it appears in the string. For example, in the string \"aab\", the frequency of 'a' is 2, while the frequency of 'b' is 1.\n\nExample 1:\nInput: s = \"aab\"\nOutput: 0\nExplanation: s is already good.\n\nExample 2:\nInput: s = \"aaabbbcc\"\nOutput: 2\nExplanation: You can delete two 'b's resulting in the good string \"aaabcc\".\nAnother way it to delete one 'b' and one 'c' resulting in the good string \"aaabbc\".\n\nExample 3:\nInput: s = \"ceabaacb\"\nOutput: 2\nExplanation: You can delete both 'c's resulting in the good string \"eabaab\".\nNote that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s contains only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\nimport string\n\nclass Solution(object):\n def minDeletions(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n count = collections.Counter(s)\n result = 0\n lookup = set()\n for c in string.ascii_lowercase:\n for i in reversed(range(1, count[c]+1)):\n if i not in lookup:\n lookup.add(i)\n break\n result += 1\n return result\n"}} diff --git a/cp/cp-11032.jsonl b/cp/cp-11032.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c2061a080bc6becf7f953cbe51089443bf1b0782 --- /dev/null +++ b/cp/cp-11032.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11032", "name": "LeetCode 1648: Sell Diminishing Valued Colored Balls"} +{"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: Sell Diminishing-Valued Colored Balls (Difficulty: Medium)\nTags: Array, Math, Binary Search, Greedy, Sorting, Heap (Priority Queue)\n\nYou have an inventory of different colored balls, and there is a customer that wants orders balls of any color.\nThe customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer).\nYou are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order.\nReturn the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: inventory = [2,5], orders = 4\nOutput: 14\nExplanation: Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).\nThe maximum total value is 2 + 5 + 4 + 3 = 14.\n\nExample 2:\nInput: inventory = [3,5], orders = 6\nOutput: 19\nExplanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).\nThe maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.\n\nConstraints:\n- 1 <= inventory.length <= 10^5\n- 1 <= inventory[i] <= 10^9\n- 1 <= orders <= min(sum(inventory[i]), 109)"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogm), m is the max of inventory, n is the size of inventory\n# Space: O(1)\n\nclass Solution(object):\n def maxProfit(self, inventory, orders):\n \"\"\"\n :type inventory: List[int]\n :type orders: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n def check(inventory, orders, x):\n return count(inventory, x) > orders\n \n def count(inventory, x):\n return sum(count-x+1 for count in inventory if count >= x)\n\n left, right = 1, max(inventory)\n while left <= right:\n mid = left + (right-left)//2\n if not check(inventory, orders, mid):\n right = mid-1\n else:\n left = mid+1\n # assert(orders-count(inventory, left) >= 0)\n return (sum((left+cnt)*(cnt-left+1)//2 for cnt in inventory if cnt >= left) +\n (left-1)*(orders-count(inventory, left)))% MOD\n"}} diff --git a/cp/cp-11033.jsonl b/cp/cp-11033.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..65ec7e32b4e58a2a4abcba637090c5698668d054 --- /dev/null +++ b/cp/cp-11033.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11033", "name": "LeetCode 1649: Create Sorted Array Through Instructions"} +{"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: Create Sorted Array through Instructions (Difficulty: Hard)\nTags: Array, Binary Search, Divide and Conquer, Binary Indexed Tree, Segment Tree, Merge Sort, Ordered Set\n\nGiven an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following:\nFor example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5].\nReturn the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 109 + 7\n\nExample 1:\nInput: instructions = [1,5,6,2]\r\nOutput: 1\r\nExplanation: Begin with nums = [].\r\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\r\nInsert 5 with cost min(1, 0) = 0, now nums = [1,5].\r\nInsert 6 with cost min(2, 0) = 0, now nums = [1,5,6].\r\nInsert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].\r\nThe total cost is 0 + 0 + 0 + 1 = 1.\n\nExample 2:\nInput: instructions = [1,2,3,6,5,4]\r\nOutput: 3\r\nExplanation: Begin with nums = [].\r\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\r\nInsert 2 with cost min(1, 0) = 0, now nums = [1,2].\r\nInsert 3 with cost min(2, 0) = 0, now nums = [1,2,3].\r\nInsert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].\r\nInsert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].\r\nInsert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].\r\nThe total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.\n\nExample 3:\nInput: instructions = [1,3,3,3,2,4,2,1,2]\r\nOutput: 4\r\nExplanation: Begin with nums = [].\r\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\r\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3].\r\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3,3].\r\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].\r\nInsert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].\r\nInsert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].\r\n​​​​​​​Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].\r\n​​​​​​​Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].\r\n​​​​​​​Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].\r\nThe total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.\n\nConstraints:\n- 1 <= instructions.length <= 10^5\n- 1 <= instructions[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogm)\n# Space: O(m)\n\nclass BIT(object): # 0-indexed.\n def __init__(self, n):\n self.__bit = [0]*(n+1) # Extra one for dummy node.\n\n def add(self, i, val):\n i += 1 # Extra one for dummy node.\n while i < len(self.__bit):\n self.__bit[i] += val\n i += (i & -i)\n\n def query(self, i):\n i += 1 # Extra one for dummy node.\n ret = 0\n while i > 0:\n ret += self.__bit[i]\n i -= (i & -i)\n return ret\n\nclass Solution(object):\n def createSortedArray(self, instructions):\n \"\"\"\n :type instructions: List[int]\n :rtype: int\n \"\"\"\n MOD = 10**9 + 7\n bit = BIT(max(instructions))\n result = 0\n for i, inst in enumerate(instructions):\n inst -= 1\n result += min(bit.query(inst-1), i-bit.query(inst))\n bit.add(inst, 1)\n return result % MOD\n\n\n# Time: O(nlogn)\n# Space: O(n)\nimport itertools\nclass Solution_TLE(object):\n def createSortedArray(self, instructions):\n \"\"\"\n :type instructions: List[int]\n :rtype: int\n \"\"\"\n MOD = 10**9 + 7\n def smallerMergeSort(idxs, start, end, counts):\n if end - start <= 0: # The size of range [start, end] less than 2 is always with count 0.\n return 0\n\n mid = start + (end - start) // 2\n smallerMergeSort(idxs, start, mid, counts)\n smallerMergeSort(idxs, mid + 1, end, counts)\n r = start\n tmp = []\n for i in range(mid+1, end + 1):\n # Merge the two sorted arrays into tmp.\n while r <= mid and idxs[r][0] < idxs[i][0]:\n tmp.append(idxs[r])\n r += 1\n tmp.append(idxs[i])\n counts[idxs[i][1]] += r - start\n while r <= mid:\n tmp.append(idxs[r])\n r += 1\n # Copy tmp back to idxs\n idxs[start:start+len(tmp)] = tmp\n \n def largerMergeSort(idxs, start, end, counts):\n if end - start <= 0: # The size of range [start, end] less than 2 is always with count 0.\n return 0\n\n mid = start + (end - start) // 2\n largerMergeSort(idxs, start, mid, counts)\n largerMergeSort(idxs, mid + 1, end, counts)\n r = start\n tmp = []\n for i in range(mid+1, end + 1):\n # Merge the two sorted arrays into tmp.\n while r <= mid and idxs[r][0] <= idxs[i][0]:\n tmp.append(idxs[r])\n r += 1\n if r <= mid:\n tmp.append(idxs[i])\n counts[idxs[i][1]] += mid - r + 1\n while r <= mid:\n tmp.append(idxs[r])\n r += 1\n # Copy tmp back to idxs\n idxs[start:start+len(tmp)] = tmp\n\n idxs = []\n smaller_counts, larger_counts = [[0] * len(instructions) for _ in range(2)]\n for i, inst in enumerate(instructions):\n idxs.append((inst, i))\n smallerMergeSort(idxs[:], 0, len(idxs)-1, smaller_counts)\n largerMergeSort(idxs, 0, len(idxs)-1, larger_counts)\n return sum(min(s, l) for s, l in itertools.izip(smaller_counts, larger_counts)) % MOD\n"}} diff --git a/cp/cp-11035.jsonl b/cp/cp-11035.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ea0480665fb3d97942d4e1759fcb9c810c5f85db --- /dev/null +++ b/cp/cp-11035.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11035", "name": "LeetCode 1652: Defuse The Bomb"} +{"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: Defuse the Bomb (Difficulty: Easy)\nTags: Array, Sliding Window\n\nYou have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k.\nTo decrypt the code, you must replace every number. All the numbers are replaced simultaneously.\nAs code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1].\nGiven the circular array code and an integer key k, return the decrypted code to defuse the bomb!\n\nExample 1:\nInput: code = [5,7,1,4], k = 3\nOutput: [12,10,16,13]\nExplanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around.\n\nExample 2:\nInput: code = [1,2,3,4], k = 0\nOutput: [0,0,0,0]\nExplanation: When k is zero, the numbers are replaced by 0.\n\nExample 3:\nInput: code = [2,4,9,3], k = -2\nOutput: [12,5,6,13]\nExplanation: The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the previous numbers.\n\nConstraints:\n- n == code.length\n- 1 <= n <= 100\n- 1 <= code[i] <= 100\n- -(n - 1) <= k <= n - 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def decrypt(self, code, k):\n \"\"\"\n :type code: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n result = [0]*len(code)\n if k == 0:\n return result\n left, right = 1, k\n if k < 0:\n k = -k\n left, right = len(code)-k, len(code)-1\n total = sum(code[i] for i in range(left, right+1))\n for i in range(len(code)):\n result[i] = total\n total -= code[left%len(code)]\n total += code[(right+1)%len(code)]\n left += 1\n right += 1\n return result\n"}} diff --git a/cp/cp-11036.jsonl b/cp/cp-11036.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a59f34ff513207092238fbb32ff96475cbd0ed33 --- /dev/null +++ b/cp/cp-11036.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11036", "name": "LeetCode 1653: Minimum Deletions To Make String Balanced"} +{"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: Minimum Deletions to Make String Balanced (Difficulty: Medium)\nTags: String, Dynamic Programming, Stack\n\nYou are given a string s consisting only of characters 'a' and 'b'​​​​.\nYou can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'.\nReturn the minimum number of deletions needed to make s balanced.\n\nExample 1:\nInput: s = \"aababbab\"\nOutput: 2\nExplanation: You can either:\nDelete the characters at 0-indexed positions 2 and 6 (\"aababbab\" -> \"aaabbb\"), or\nDelete the characters at 0-indexed positions 3 and 6 (\"aababbab\" -> \"aabbbb\").\n\nExample 2:\nInput: s = \"bbaaaaabb\"\nOutput: 2\nExplanation: The only solution is to delete the first two characters.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s[i] is 'a' or 'b'​​."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minimumDeletions(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result = b_cnt = 0\n for c in s:\n if c == 'b':\n b_cnt += 1\n elif b_cnt:\n b_cnt -= 1\n result += 1\n return result\n"}} diff --git a/cp/cp-11037.jsonl b/cp/cp-11037.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..47c5c94f02b8a07c38c0fd705ab0fc324e330365 --- /dev/null +++ b/cp/cp-11037.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11037", "name": "LeetCode 1654: Minimum Jumps To Reach Home"} +{"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: Minimum Jumps to Reach Home (Difficulty: Medium)\nTags: Array, Dynamic Programming, Breadth-First Search\n\nA certain bug's home is on the x-axis at position x. Help them get there from position 0.\nThe bug jumps according to the following rules:\nThe bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers.\nGiven an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1.\n\nExample 1:\nInput: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9\nOutput: 3\nExplanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home.\n\nExample 2:\nInput: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11\nOutput: -1\n\nExample 3:\nInput: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7\nOutput: 2\nExplanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.\n\nConstraints:\n- 1 <= forbidden.length <= 1000\n- 1 <= a, b, forbidden[i] <= 2000\n- 0 <= x <= 2000\n- All the elements in forbidden are distinct.\n- Position x is not forbidden."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(max(x, max(forbidden)) + a + (b+a))\n# Space: O(max(x, max(forbidden)) + a + (b+a))\n\nclass Solution(object):\n def minimumJumps(self, forbidden, a, b, x):\n \"\"\"\n :type forbidden: List[int]\n :type a: int\n :type b: int\n :type x: int\n :rtype: int\n \"\"\"\n max_f = max(forbidden)\n max_val = x+b if a >= b else max(x, max_f)+a+(b+a) # a may be a non-periodic area, (a+b) is a periodic area which is divided by gcd(a, b) and all points are reachable\n lookup = set() \n for pos in forbidden:\n lookup.add((pos, True))\n lookup.add((pos, False))\n result = 0\n q = [(0, True)]\n lookup.add((0, True))\n while q:\n new_q = []\n for pos, can_back in q:\n if pos == x:\n return result\n if pos+a <= max_val and (pos+a, True) not in lookup:\n lookup.add((pos+a, True))\n new_q.append((pos+a, True))\n if not can_back:\n continue\n if pos-b >= 0 and (pos-b, False) not in lookup:\n lookup.add((pos-b, False))\n new_q.append((pos-b, False))\n q = new_q\n result += 1\n return -1\n"}} diff --git a/cp/cp-11038.jsonl b/cp/cp-11038.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ad684f744346a453f74bf5c6a6ac098bdf366a5d --- /dev/null +++ b/cp/cp-11038.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11038", "name": "LeetCode 1655: Distribute Repeating Integers"} +{"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: Distribute Repeating Integers (Difficulty: Hard)\nTags: Array, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask\n\nYou are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that:\nReturn true if it is possible to distribute nums according to the above conditions.\n\nExample 1:\nInput: nums = [1,2,3,4], quantity = [2]\nOutput: false\nExplanation: The 0th customer cannot be given two different integers.\n\nExample 2:\nInput: nums = [1,2,3,3], quantity = [2]\nOutput: true\nExplanation: The 0th customer is given [3,3]. The integers [1,2] are not used.\n\nExample 3:\nInput: nums = [1,1,2,2], quantity = [2,2]\nOutput: true\nExplanation: The 0th customer is given [1,1], and the 1st customer is given [2,2].\n\nConstraints:\n- n == nums.length\n- 1 <= n <= 10^5\n- 1 <= nums[i] <= 1000\n- m == quantity.length\n- 1 <= m <= 10\n- 1 <= quantity[i] <= 10^5\n- There are at most 50 unique values in nums."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + m * 3^m) \n# Space: O(n + 2^m)\n\nimport collections\nimport random\n\n\nclass Solution(object):\n def canDistribute(self, nums, quantity):\n \"\"\"\n :type nums: List[int]\n :type quantity: List[int]\n :rtype: bool\n \"\"\"\n def nth_element(nums, n, compare=lambda a, b: a < b):\n def tri_partition(nums, left, right, target, compare):\n mid = left\n while mid <= right:\n if nums[mid] == target:\n mid += 1\n elif compare(nums[mid], target):\n nums[left], nums[mid] = nums[mid], nums[left]\n left += 1\n mid += 1\n else:\n nums[mid], nums[right] = nums[right], nums[mid]\n right -= 1\n return left, right\n\n left, right = 0, len(nums)-1\n while left <= right:\n pivot_idx = random.randint(left, right)\n pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)\n if pivot_left <= n <= pivot_right:\n return\n elif pivot_left > n:\n right = pivot_left-1\n else: # pivot_right < n.\n left = pivot_right+1\n\n count = collections.Counter(nums)\n total = (1< b)\n cnts = cnts[:len(quantity)]\n for cnt in cnts: # Time: O(m)\n dp[(i+1)%2] = [0]*(total+1)\n # submask enumeration:\n # => sum(nCr(m, k) * 2^k for k in range(m+1)) = (1 + 2)^m = 3^m\n # => Time: O(3^m), see https://cp-algorithms.com/algebra/all-submasks.html\n for mask in reversed(range(total+1)):\n dp[(i+1)%2][mask] |= dp[i%2][mask]\n submask = mask\n while submask > 0:\n if requirement[submask] <= cnt and dp[i%2][mask^submask]:\n dp[(i+1)%2][mask] = 1\n submask = (submask-1)&mask\n i += 1\n return dp[len(cnts)%2][total]\n"}} diff --git a/cp/cp-11039.jsonl b/cp/cp-11039.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..650f080f2a0576b954b2d35d5039d2c908356ea5 --- /dev/null +++ b/cp/cp-11039.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11039", "name": "LeetCode 1656: Design An Ordered Stream"} +{"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 an Ordered Stream (Difficulty: Easy)\nTags: Array, Hash Table, Design, Data Stream\n\nThere is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id.\nDesign a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values.\nImplement the OrderedStream class:\nExample:\n\nExample 1:\nInput\n[\"OrderedStream\", \"insert\", \"insert\", \"insert\", \"insert\", \"insert\"]\n[[5], [3, \"ccccc\"], [1, \"aaaaa\"], [2, \"bbbbb\"], [5, \"eeeee\"], [4, \"ddddd\"]]\nOutput\n[null, [], [\"aaaaa\"], [\"bbbbb\", \"ccccc\"], [], [\"ddddd\", \"eeeee\"]]\n\nExplanation\n// Note that the values ordered by ID is [\"aaaaa\", \"bbbbb\", \"ccccc\", \"ddddd\", \"eeeee\"].\nOrderedStream os = new OrderedStream(5);\nos.insert(3, \"ccccc\"); // Inserts (3, \"ccccc\"), returns [].\nos.insert(1, \"aaaaa\"); // Inserts (1, \"aaaaa\"), returns [\"aaaaa\"].\nos.insert(2, \"bbbbb\"); // Inserts (2, \"bbbbb\"), returns [\"bbbbb\", \"ccccc\"].\nos.insert(5, \"eeeee\"); // Inserts (5, \"eeeee\"), returns [].\nos.insert(4, \"ddddd\"); // Inserts (4, \"ddddd\"), returns [\"ddddd\", \"eeeee\"].\n// Concatentating all the chunks returned:\n// [] + [\"aaaaa\"] + [\"bbbbb\", \"ccccc\"] + [] + [\"ddddd\", \"eeeee\"] = [\"aaaaa\", \"bbbbb\", \"ccccc\", \"ddddd\", \"eeeee\"]\n// The resulting order is the same as the order above.\n\nConstraints:\n- 1 <= n <= 1000\n- 1 <= id <= n\n- value.length == 5\n- value consists only of lowercase letters.\n- Each call to insert will have a unique id.\n- Exactly n calls will be made to insert."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1), amortized\n# Space: O(n)\n\nclass OrderedStream(object):\n\n def __init__(self, n):\n \"\"\"\n :type n: int\n \"\"\"\n self.__i = 0 \n self.__values = [None]*n\n\n def insert(self, id, value):\n \"\"\"\n :type id: int\n :type value: str\n :rtype: List[str]\n \"\"\"\n id -= 1\n self.__values[id] = value\n result = []\n if self.__i != id:\n return result\n while self.__i < len(self.__values) and self.__values[self.__i]:\n result.append(self.__values[self.__i])\n self.__i += 1\n return result\n"}} diff --git a/cp/cp-11040.jsonl b/cp/cp-11040.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..699e8be1e70069cdbab81f58aac1652cf96077c2 --- /dev/null +++ b/cp/cp-11040.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11040", "name": "LeetCode 1657: Determine If Two Strings Are Close"} +{"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: Determine if Two Strings Are Close (Difficulty: Medium)\nTags: Hash Table, String, Sorting, Counting\n\nTwo strings are considered close if you can attain one from the other using the following operations:\nYou can use the operations on either string as many times as necessary.\nGiven two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.\n\nExample 1:\nInput: word1 = \"abc\", word2 = \"bca\"\nOutput: true\nExplanation: You can attain word2 from word1 in 2 operations.\nApply Operation 1: \"abc\" -> \"acb\"\nApply Operation 1: \"acb\" -> \"bca\"\n\nExample 2:\nInput: word1 = \"a\", word2 = \"aa\"\nOutput: false\nExplanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.\n\nExample 3:\nInput: word1 = \"cabbba\", word2 = \"abbccc\"\nOutput: true\nExplanation: You can attain word2 from word1 in 3 operations.\nApply Operation 1: \"cabbba\" -> \"caabbb\"\nApply Operation 2: \"caabbb\" -> \"baaccc\"\nApply Operation 2: \"baaccc\" -> \"abbccc\"\n\nConstraints:\n- 1 <= word1.length, word2.length <= 10^5\n- word1 and word2 contain only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def closeStrings(self, word1, word2):\n \"\"\"\n :type word1: str\n :type word2: str\n :rtype: bool\n \"\"\"\n if len(word1) != len(word2):\n return False \n \n cnt1, cnt2 = collections.Counter(word1), collections.Counter(word2) # Reuse of keys\n return set(cnt1.iterkeys()) == set(cnt2.iterkeys()) and \\\n collections.Counter(cnt1.itervalues()) == collections.Counter(cnt2.itervalues())\n"}} diff --git a/cp/cp-11041.jsonl b/cp/cp-11041.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..760bce0ba2e037aaf7c5dd84a92ceaf3d7306da6 --- /dev/null +++ b/cp/cp-11041.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11041", "name": "LeetCode 1658: Minimum Operations To Reduce X To Zero"} +{"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: Minimum Operations to Reduce X to Zero (Difficulty: Medium)\nTags: Array, Hash Table, Binary Search, Sliding Window, Prefix Sum\n\nYou are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.\nReturn the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1.\n\nExample 1:\nInput: nums = [1,1,4,2,3], x = 5\nOutput: 2\nExplanation: The optimal solution is to remove the last two elements to reduce x to zero.\n\nExample 2:\nInput: nums = [5,6,7,8,9], x = 4\nOutput: -1\n\nExample 3:\nInput: nums = [3,2,20,1,1,3], x = 10\nOutput: 5\nExplanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i] <= 10^4\n- 1 <= x <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minOperations(self, nums, x):\n \"\"\"\n :type nums: List[int]\n :type x: int\n :rtype: int\n \"\"\"\n target = sum(nums)-x\n result = -1\n curr = left = 0\n for right in range(len(nums)):\n curr += nums[right]\n while left < len(nums) and curr > target:\n curr -= nums[left]\n left += 1\n if curr == target:\n result = max(result, right-left+1)\n return len(nums)-result if result != -1 else -1\n"}} diff --git a/cp/cp-11042.jsonl b/cp/cp-11042.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3e02334aa7ed04cdd3f120653ccbf9ec03878180 --- /dev/null +++ b/cp/cp-11042.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11042", "name": "LeetCode 1659: Maximize Grid Happiness"} +{"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: Maximize Grid Happiness (Difficulty: Hard)\nTags: Dynamic Programming, Bit Manipulation, Memoization, Bitmask\n\nYou are given four integers, m, n, introvertsCount, and extrovertsCount. You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts.\nYou should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid.\nThe happiness of each person is calculated as follows:\nNeighbors live in the directly adjacent cells north, east, south, and west of a person's cell.\nThe grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness.\n\nExample 1:\nInput: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2\nOutput: 240\nExplanation: Assume the grid is 1-indexed with coordinates (row, column).\nWe can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120\n- Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\n- Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\nThe grid happiness is 120 + 60 + 60 = 240.\nThe above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.\n\nExample 2:\nInput: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1\nOutput: 260\nExplanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\n- Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80\n- Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\nThe grid happiness is 90 + 80 + 90 = 260.\n\nExample 3:\nInput: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0\nOutput: 240\n\nConstraints:\n- 1 <= m, n <= 5\n- 0 <= introvertsCount, extrovertsCount <= min(m * n, 6)"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(C(m * n, i) * C(m * n - i, e))\n# Space: O(min(m * n, i + e))\n\nclass Solution(object):\n def getMaxGridHappiness(self, m, n, introvertsCount, extrovertsCount):\n \"\"\"\n :type m: int\n :type n: int\n :type introvertsCount: int\n :type extrovertsCount: int\n :rtype: int\n \"\"\"\n def left(curr):\n return curr[-1] if len(curr)%n else 0\n\n def up(curr):\n return curr[-n] if len(curr) >= n else 0 \n\n def count_total(curr, t, total):\n return (total\n - 30*((left(curr) == 1)+(up(curr) == 1))\n + 20*((left(curr) == 2)+(up(curr) == 2))\n + (120 - 30*((left(curr) != 0)+(up(curr) != 0)))*(t == 1)\n + ( 40 + 20*((left(curr) != 0)+(up(curr) != 0)))*(t == 2))\n \n def iter_backtracking(i, e):\n result = 0\n curr = []\n stk = [(2, (i, e, 0))]\n while stk:\n step, params = stk.pop()\n if step == 2:\n i, e, total = params \n if len(curr) == m*n or (i == 0 and e == 0):\n result = max(result, total) \n continue\n if total + (i+e)*120 < result: # pruning\n continue\n if e > 0:\n stk.append((3, tuple()))\n stk.append((2, (i, e-1, count_total(curr, 2, total))))\n stk.append((1, (2,)))\n if i > 0:\n stk.append((3, tuple()))\n stk.append((2, (i-1, e, count_total(curr, 1, total))))\n stk.append((1, (1,)))\n if left(curr) or up(curr): # leave unoccupied iff left or up is occupied\n stk.append((3, tuple()))\n stk.append((2, (i, e, total)))\n stk.append((1, (0,)))\n elif step == 1:\n x = params[0]\n curr.append(x)\n elif step == 3:\n curr.pop()\n return result\n \n return iter_backtracking(introvertsCount, extrovertsCount)\n\n\n# Time: O(C(m * n, i) * C(m * n - i, e))\n# Space: O(min(m * n, i + e))\nclass Solution2(object):\n def getMaxGridHappiness(self, m, n, introvertsCount, extrovertsCount):\n \"\"\"\n :type m: int\n :type n: int\n :type introvertsCount: int\n :type extrovertsCount: int\n :rtype: int\n \"\"\"\n def left(curr):\n return curr[-1] if len(curr)%n else 0\n\n def up(curr):\n return curr[-n] if len(curr) >= n else 0 \n\n def count_total(curr, t, total):\n return (total\n - 30*((left(curr) == 1)+(up(curr) == 1))\n + 20*((left(curr) == 2)+(up(curr) == 2))\n + (120 - 30*((left(curr) != 0)+(up(curr) != 0)))*(t == 1)\n + ( 40 + 20*((left(curr) != 0)+(up(curr) != 0)))*(t == 2))\n \n def backtracking(i, e, total, curr, result): \n if len(curr) == m*n or (i == 0 and e == 0):\n result[0] = max(result[0], total) \n return\n if total + (i+e)*120 < result[0]: # pruning\n return\n if left(curr) or up(curr): # leave unoccupied iff left or up is occupied\n curr.append(0)\n backtracking(i, e, total, curr, result)\n curr.pop()\n if i > 0:\n new_total = count_total(curr, 1, total)\n curr.append(1)\n backtracking(i-1, e, new_total, curr, result)\n curr.pop()\n if e > 0:\n new_total = count_total(curr, 2, total)\n curr.append(2)\n backtracking(i, e-1, new_total, curr, result)\n curr.pop()\n\n result = [0]\n backtracking(introvertsCount, extrovertsCount, 0, [], result)\n return result[0]\n"}} diff --git a/cp/cp-11044.jsonl b/cp/cp-11044.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..18dab5769f0b10fbc76f7e3ce7a8b32c288a8879 --- /dev/null +++ b/cp/cp-11044.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11044", "name": "LeetCode 1662: Check If Two String Arrays Are Equivalent"} +{"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: Check If Two String Arrays are Equivalent (Difficulty: Easy)\nTags: Array, String\n\nGiven two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.\nA string is represented by an array if the array elements concatenated in order forms the string.\n\nExample 1:\nInput: word1 = [\"ab\", \"c\"], word2 = [\"a\", \"bc\"]\nOutput: true\nExplanation:\nword1 represents string \"ab\" + \"c\" -> \"abc\"\nword2 represents string \"a\" + \"bc\" -> \"abc\"\nThe strings are the same, so return true.\n\nExample 2:\nInput: word1 = [\"a\", \"cb\"], word2 = [\"ab\", \"c\"]\nOutput: false\n\nExample 3:\nInput: word1 = [\"abc\", \"d\", \"defg\"], word2 = [\"abcddefg\"]\nOutput: true\n\nConstraints:\n- 1 <= word1.length, word2.length <= 103\n- 1 <= word1[i].length, word2[i].length <= 103\n- 1 <= sum(word1[i].length), sum(word2[i].length) <= 103\n- word1[i] and word2[i] consist of lowercase letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n), n is the total length of word1 and word2\n# Space: O(1)\n\nclass Solution(object):\n def arrayStringsAreEqual(self, word1, word2):\n \"\"\"\n :type word1: List[str]\n :type word2: List[str]\n :rtype: bool\n \"\"\"\n idx1 = idx2 = arr_idx1 = arr_idx2 = 0\n while arr_idx1 < len(word1) and arr_idx2 < len(word2):\n if word1[arr_idx1][idx1] != word2[arr_idx2][idx2]:\n break\n idx1 += 1\n if idx1 == len(word1[arr_idx1]):\n idx1 = 0\n arr_idx1 += 1\n idx2 += 1\n if idx2 == len(word2[arr_idx2]):\n idx2 = 0\n arr_idx2 += 1\n return arr_idx1 == len(word1) and arr_idx2 == len(word2)\n"}} diff --git a/cp/cp-11045.jsonl b/cp/cp-11045.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9d661d96eaf4df85add304083f8b551cfeec1fa9 --- /dev/null +++ b/cp/cp-11045.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11045", "name": "LeetCode 1663: Smallest String With A Given Numeric Value"} +{"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: Smallest String With A Given Numeric Value (Difficulty: Medium)\nTags: String, Greedy\n\nThe numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.\nThe numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string \"abe\" is equal to 1 + 2 + 5 = 8.\nYou are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k.\nNote that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.\n\nExample 1:\nInput: n = 3, k = 27\nOutput: \"aay\"\nExplanation: The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.\n\nExample 2:\nInput: n = 5, k = 73\nOutput: \"aaszz\"\n\nConstraints:\n- 1 <= n <= 10^5\n- n <= k <= 26 * n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def getSmallestString(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n MAX_DIFF = ord('z')-ord('a')\n\n k -= n\n result = ['a']*n\n for i in reversed(range(n)):\n tmp = min(k, MAX_DIFF)\n result[i] = chr(ord('a')+tmp)\n k -= tmp\n if k == 0:\n break\n return \"\".join(result)\n"}} diff --git a/cp/cp-11046.jsonl b/cp/cp-11046.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..00ea76783bd657f1d2eac90742fb56d654622dc0 --- /dev/null +++ b/cp/cp-11046.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11046", "name": "LeetCode 1664: Ways To Make A Fair 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: Ways to Make a Fair Array (Difficulty: Medium)\nTags: Array, Prefix Sum\n\nYou are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.\nFor example, if nums = [6,1,7,4,1]:\nAn array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.\nReturn the number of indices that you could choose such that after the removal, nums is fair.\n\nExample 1:\nInput: nums = [2,1,6,4]\nOutput: 1\nExplanation:\nRemove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.\nRemove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.\nRemove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.\nRemove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.\nThere is 1 index that you can remove to make nums fair.\n\nExample 2:\nInput: nums = [1,1,1]\nOutput: 3\nExplanation: You can remove any index and the remaining array is fair.\n\nExample 3:\nInput: nums = [1,2,3]\nOutput: 0\nExplanation: You cannot make a fair array after removing any index.\n\nConstraints:\n- 1 <= nums.length <= 10^5\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 waysToMakeFair(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n prefix = [0]*2\n suffix = [sum(nums[i] for i in range(k, len(nums), 2)) for k in range(2)]\n result = 0\n for i, num in enumerate(nums):\n suffix[i%2] -= num\n result += int(prefix[0]+suffix[1] == prefix[1]+suffix[0])\n prefix[i%2] += num\n return result\n"}} diff --git a/cp/cp-11047.jsonl b/cp/cp-11047.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a9b0e526991a6713964903e1774444ba73418737 --- /dev/null +++ b/cp/cp-11047.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11047", "name": "LeetCode 1665: Minimum Initial Energy To Finish Tasks"} +{"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: Minimum Initial Energy to Finish Tasks (Difficulty: Hard)\nTags: Array, Greedy, Sorting\n\nYou are given an array tasks where tasks[i] = [actuali, minimumi]:\nFor example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it.\nYou can finish the tasks in any order you like.\nReturn the minimum initial amount of energy you will need to finish all the tasks.\n\nExample 1:\nInput: tasks = [[1,2],[2,4],[4,8]]\nOutput: 8\nExplanation:\nStarting with 8 energy, we finish the tasks in the following order:\n - 3rd task. Now energy = 8 - 4 = 4.\n - 2nd task. Now energy = 4 - 2 = 2.\n - 1st task. Now energy = 2 - 1 = 1.\nNotice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.\n\nExample 2:\nInput: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]\nOutput: 32\nExplanation:\nStarting with 32 energy, we finish the tasks in the following order:\n - 1st task. Now energy = 32 - 1 = 31.\n - 2nd task. Now energy = 31 - 2 = 29.\n - 3rd task. Now energy = 29 - 10 = 19.\n - 4th task. Now energy = 19 - 10 = 9.\n - 5th task. Now energy = 9 - 8 = 1.\n\nExample 3:\nInput: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]\nOutput: 27\nExplanation:\nStarting with 27 energy, we finish the tasks in the following order:\n - 5th task. Now energy = 27 - 5 = 22.\n - 2nd task. Now energy = 22 - 2 = 20.\n - 3rd task. Now energy = 20 - 3 = 17.\n - 1st task. Now energy = 17 - 1 = 16.\n - 4th task. Now energy = 16 - 4 = 12.\n - 6th task. Now energy = 12 - 6 = 6.\n\nConstraints:\n- 1 <= tasks.length <= 10^5\n- 1 <= actual​i <= minimumi <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def minimumEffort(self, tasks):\n \"\"\"\n :type tasks: List[List[int]]\n :rtype: int\n \"\"\"\n tasks.sort(key=lambda x: x[1]-x[0]) # sort by waste in asc\n result = 0\n # you can see proof here, https://leetcode.com/problems/minimum-initial-energy-to-finish-tasks/discuss/944633/Explanation-on-why-sort-by-difference\n for a, m in tasks: # we need to pick all the wastes, so greedily to pick the least waste first is always better\n result = max(result+a, m)\n return result\n\n\n# Time: O(nlogn)\n# Space: O(1)\nclass Solution2(object):\n def minimumEffort(self, tasks):\n \"\"\"\n :type tasks: List[List[int]]\n :rtype: int\n \"\"\"\n tasks.sort(key=lambda x: x[0]-x[1]) # sort by save in desc\n result = curr = 0\n for a, m in tasks: # we need to pick all the saves, so greedily to pick the most save first is always better\n result += max(m-curr, 0)\n curr = max(curr, m)-a\n return result\n"}} diff --git a/cp/cp-11049.jsonl b/cp/cp-11049.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0869fe7b939850b33d2edccd8f2c3751c2cd589e --- /dev/null +++ b/cp/cp-11049.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11049", "name": "LeetCode 1668: Maximum Repeating Substring"} +{"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 Repeating Substring (Difficulty: Easy)\nTags: String, Dynamic Programming, String Matching\n\nFor a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0.\nGiven strings sequence and word, return the maximum k-repeating value of word in sequence.\n\nExample 1:\nInput: sequence = \"ababc\", word = \"ab\"\nOutput: 2\nExplanation: \"abab\" is a substring in \"ababc\".\n\nExample 2:\nInput: sequence = \"ababc\", word = \"ba\"\nOutput: 1\nExplanation: \"ba\" is a substring in \"ababc\". \"baba\" is not a substring in \"ababc\".\n\nExample 3:\nInput: sequence = \"ababc\", word = \"ac\"\nOutput: 0\nExplanation: \"ac\" is not a substring in \"ababc\".\n\nConstraints:\n- 1 <= sequence.length <= 100\n- 1 <= word.length <= 100\n- sequence and word contains only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n), n is the length of sequence\n# Space: O(m), m is the length of word\n\n# optimized kmp solution\nclass Solution(object):\n def maxRepeating(self, sequence, word):\n \"\"\"\n :type sequence: str\n :type word: str\n :rtype: int\n \"\"\"\n def getPrefix(pattern):\n prefix = [-1] * len(pattern)\n j = -1\n for i in range(1, len(pattern)):\n while j > -1 and pattern[j + 1] != pattern[i]:\n j = prefix[j]\n if pattern[j+1] == pattern[i]:\n j += 1\n prefix[i] = j\n return prefix\n\n if len(sequence) < len(word):\n return 0\n\n prefix = getPrefix(word)\n result, count, j, prev = 0, 0, -1, -1\n for i in range(len(sequence)):\n while j > -1 and word[j+1] != sequence[i]:\n j = prefix[j]\n if word[j+1] == sequence[i]:\n j += 1\n if j+1 == len(word): \n count = count+1 if i-prev == len(word) else 1\n result = max(result, count)\n j, prev = -1, i\n return result\n\n\n# Time: O(n), n is the length of sequence\n# Space: O(n)\n# kmp solution\nclass Solution2(object):\n def maxRepeating(self, sequence, word):\n \"\"\"\n :type sequence: str\n :type word: str\n :rtype: int\n \"\"\"\n def getPrefix(pattern):\n prefix = [-1] * len(pattern)\n j = -1\n for i in range(1, len(pattern)):\n while j > -1 and pattern[j + 1] != pattern[i]:\n j = prefix[j]\n if pattern[j+1] == pattern[i]:\n j += 1\n prefix[i] = j\n return prefix\n\n if len(sequence) < len(word):\n return 0\n\n new_word = word*(len(sequence)//len(word))\n prefix = getPrefix(new_word)\n result, j = 0, -1\n for i in range(len(sequence)):\n while j > -1 and new_word[j+1] != sequence[i]:\n j = prefix[j]\n if new_word[j+1] == sequence[i]:\n j += 1\n result = max(result, j+1)\n if j+1 == len(new_word): \n break\n return result//len(word)\n"}} diff --git a/cp/cp-11050.jsonl b/cp/cp-11050.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a2b345f99a04c751878944ec49714124fb62e8e8 --- /dev/null +++ b/cp/cp-11050.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11050", "name": "LeetCode 1669: Merge In Between Linked Lists"} +{"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 In Between Linked Lists (Difficulty: Medium)\nTags: Linked List\n\nYou are given two linked lists: list1 and list2 of sizes n and m respectively.\nRemove list1's nodes from the ath node to the bth node, and put list2 in their place.\nThe blue edges and nodes in the following figure indicate the result:\nBuild the result list and return its head.\n\nExample 1:\nInput: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]\nOutput: [10,1,13,1000000,1000001,1000002,5]\nExplanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.\n\nExample 2:\nInput: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]\nOutput: [0,1,1000000,1000001,1000002,1000003,1000004,6]\nExplanation: The blue edges and nodes in the above figure indicate the result.\n\nConstraints:\n- 3 <= list1.length <= 10^4\n- 1 <= a <= b < list1.length - 1\n- 1 <= list2.length <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n)\n# Space: O(1)\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, val=0, next=None):\n pass\n\n\nclass Solution(object):\n def mergeInBetween(self, list1, a, b, list2):\n \"\"\"\n :type list1: ListNode\n :type a: int\n :type b: int\n :type list2: ListNode\n :rtype: ListNode\n \"\"\"\n prev_first, last = None, list1\n for i in range(b):\n if i == a-1:\n prev_first = last\n last = last.next\n prev_first.next = list2\n while list2.next:\n list2 = list2.next\n list2.next = last.next\n last.next = None\n return list1\n"}} diff --git a/cp/cp-11051.jsonl b/cp/cp-11051.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4db606d5eb4b7019ab3403836faa87457468b1b2 --- /dev/null +++ b/cp/cp-11051.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11051", "name": "LeetCode 1670: Design Front Middle Back 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 Front Middle Back Queue (Difficulty: Medium)\nTags: Array, Linked List, Design, Queue, Data Stream\n\nDesign a queue that supports push and pop operations in the front, middle, and back.\nImplement the FrontMiddleBack class:\nNotice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example:\n\nExample 1:\nInput:\n[\"FrontMiddleBackQueue\", \"pushFront\", \"pushBack\", \"pushMiddle\", \"pushMiddle\", \"popFront\", \"popMiddle\", \"popMiddle\", \"popBack\", \"popFront\"]\n[[], [1], [2], [3], [4], [], [], [], [], []]\nOutput:\n[null, null, null, null, null, 1, 3, 4, 2, -1]\n\nExplanation:\nFrontMiddleBackQueue q = new FrontMiddleBackQueue();\nq.pushFront(1); // [1]\nq.pushBack(2); // [1, 2]\nq.pushMiddle(3); // [1, 3, 2]\nq.pushMiddle(4); // [1, 4, 3, 2]\nq.popFront(); // return 1 -> [4, 3, 2]\nq.popMiddle(); // return 3 -> [4, 2]\nq.popMiddle(); // return 4 -> [2]\nq.popBack(); // return 2 -> []\nq.popFront(); // return -1 -> [] (The queue is empty)\n\nConstraints:\n- 1 <= val <= 10^9\n- At most 1000 calls will be made to pushFront, pushMiddle, pushBack, popFront, popMiddle, and popBack."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(n)\n\nimport collections\n\n\nclass FrontMiddleBackQueue(object):\n\n def __init__(self):\n self.__left, self.__right = collections.deque(), collections.deque() \n\n def pushFront(self, val):\n \"\"\"\n :type val: int\n :rtype: None\n \"\"\"\n self.__left.appendleft(val)\n self.__balance() \n\n def pushMiddle(self, val):\n \"\"\"\n :type val: int\n :rtype: None\n \"\"\"\n if len(self.__left) > len(self.__right):\n self.__right.appendleft(self.__left.pop())\n self.__left.append(val)\n\n def pushBack(self, val):\n \"\"\"\n :type val: int\n :rtype: None\n \"\"\"\n self.__right.append(val)\n self.__balance()\n\n def popFront(self):\n \"\"\"\n :rtype: int\n \"\"\"\n val = (self.__left or collections.deque([-1])).popleft()\n self.__balance()\n return val\n\n def popMiddle(self):\n \"\"\"\n :rtype: int\n \"\"\"\n val = (self.__left or [-1]).pop()\n self.__balance()\n return val\n\n def popBack(self):\n \"\"\"\n :rtype: int\n \"\"\"\n val = (self.__right or self.__left or [-1]).pop()\n self.__balance()\n return val\n\n def __balance(self):\n if len(self.__left) > len(self.__right)+1:\n self.__right.appendleft(self.__left.pop())\n elif len(self.__left) < len(self.__right):\n self.__left.append(self.__right.popleft())\n"}} diff --git a/cp/cp-11052.jsonl b/cp/cp-11052.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5e9c917775a5f0f6fa9259721e30a4ee486a15b2 --- /dev/null +++ b/cp/cp-11052.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11052", "name": "LeetCode 1671: Minimum Number Of Removals To Make Mountain 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: Minimum Number of Removals to Make Mountain Array (Difficulty: Hard)\nTags: Array, Binary Search, Dynamic Programming, Greedy\n\nYou may recall that an array arr is a mountain array if and only if:\nGiven an integer array nums​​​, return the minimum number of elements to remove to make nums​​​ a mountain array.\n\nExample 1:\nInput: nums = [1,3,1]\nOutput: 0\nExplanation: The array itself is a mountain array so we do not need to remove any elements.\n\nExample 2:\nInput: nums = [2,1,1,5,6,2,3,1]\nOutput: 3\nExplanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].\n\nConstraints:\n- 3 <= nums.length <= 1000\n- 1 <= nums[i] <= 10^9\n- It is guaranteed that you can make a mountain array out of nums."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport bisect\n\n\nclass Solution(object):\n def minimumMountainRemovals(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n left_lis_len = [0]*len(nums)\n lis = []\n for i in range(len(nums)-1):\n j = bisect.bisect_left(lis, nums[i])\n if j == len(lis):\n lis.append(nums[i])\n else:\n lis[j] = nums[i]\n left_lis_len[i] = j\n max_len = 0\n lis = []\n for i in reversed(range(1, len(nums))):\n j = bisect.bisect_left(lis, nums[i])\n if j == len(lis):\n lis.append(nums[i])\n else:\n lis[j] = nums[i]\n if i < len(nums)-1:\n max_len = max(max_len, left_lis_len[i]+j)\n return len(nums) - (1+max_len)\n"}} diff --git a/cp/cp-11054.jsonl b/cp/cp-11054.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..51a4ad36d589f5e49e4b6e5e23fcbe1409e7c0e5 --- /dev/null +++ b/cp/cp-11054.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11054", "name": "LeetCode 1673: Find The Most Competitive 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: Find the Most Competitive Subsequence (Difficulty: Medium)\nTags: Array, Stack, Greedy, Monotonic Stack\n\nGiven an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k.\nAn array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.\nWe define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5.\n\nExample 1:\nInput: nums = [3,5,2,6], k = 2\nOutput: [2,6]\nExplanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.\n\nExample 2:\nInput: nums = [2,4,3,3,5,4,9,6], k = 4\nOutput: [2,3,3,4]\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 0 <= nums[i] <= 10^9\n- 1 <= k <= nums.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(k)\n\nclass Solution(object):\n def mostCompetitive(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n stk = []\n for i, x in enumerate(nums):\n while stk and stk[-1] > x and len(stk)+(len(nums)-i) > k:\n stk.pop()\n if len(stk) < k:\n stk.append(x)\n return stk\n"}} diff --git a/cp/cp-11055.jsonl b/cp/cp-11055.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ef70c22c57d9ff8a5d7ce3ae50b444e5387f1881 --- /dev/null +++ b/cp/cp-11055.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11055", "name": "LeetCode 1674: Minimum Moves To Make Array Complementary"} +{"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: Minimum Moves to Make Array Complementary (Difficulty: Medium)\nTags: Array, Hash Table, Prefix Sum\n\nYou are given an integer array nums of even length n and an integer limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive.\nThe array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i, nums[i] + nums[n - 1 - i] = 5.\nReturn the minimum number of moves required to make nums complementary.\n\nExample 1:\nInput: nums = [1,2,4,3], limit = 4\nOutput: 1\nExplanation: In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).\nnums[0] + nums[3] = 1 + 3 = 4.\nnums[1] + nums[2] = 2 + 2 = 4.\nnums[2] + nums[1] = 2 + 2 = 4.\nnums[3] + nums[0] = 3 + 1 = 4.\nTherefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary.\n\nExample 2:\nInput: nums = [1,2,2,1], limit = 2\nOutput: 2\nExplanation: In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit.\n\nExample 3:\nInput: nums = [1,2,1,2], limit = 2\nOutput: 0\nExplanation: nums is already complementary.\n\nConstraints:\n- n == nums.length\n- 2 <= n <= 10^5\n- 1 <= nums[i] <= limit <= 10^5\n- n is even."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + k)\n# Space: O(k)\n\nclass Solution(object):\n def minMoves(self, nums, limit):\n \"\"\"\n :type nums: List[int]\n :type limit: int\n :rtype: int\n \"\"\"\n diff = [0]*(2*(limit+1))\n for i in range(len(nums)//2):\n left, right = nums[i], nums[-1-i]\n diff[min(left, right)+1] -= 1 # if target total grows to min(left, right)+1, one less move\n diff[left+right] -= 1 # if target total grows to left+right, one less move\n diff[left+right+1] += 1 # if target total grows to left+right+1, one more move\n diff[max(left, right)+limit+1] += 1 # if target total grows to max(left, right)+limit+1, one more move\n result = count = len(nums) # default is to move all nums\n for total in range(2, 2*limit+1): # enumerate all possible target totals\n count += diff[total]\n result = min(result, count)\n return result\n"}} diff --git a/cp/cp-11056.jsonl b/cp/cp-11056.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..faf8945620876aba01dcd15cb407feb65d612656 --- /dev/null +++ b/cp/cp-11056.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11056", "name": "LeetCode 1675: Minimize Deviation In 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: Minimize Deviation in Array (Difficulty: Hard)\nTags: Array, Greedy, Heap (Priority Queue), Ordered Set\n\nYou are given an array nums of n positive integers.\nYou can perform two types of operations on any element of the array any number of times:\nThe deviation of the array is the maximum difference between any two elements in the array.\nReturn the minimum deviation the array can have after performing some number of operations.\n\nExample 1:\nInput: nums = [1,2,3,4]\nOutput: 1\nExplanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.\n\nExample 2:\nInput: nums = [4,1,5,20,3]\nOutput: 3\nExplanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.\n\nExample 3:\nInput: nums = [2,10,8]\nOutput: 3\n\nConstraints:\n- n == nums.length\n- 2 <= n <= 5 * 10^4\n- 1 <= nums[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((n * log(max_num)) * logn)\n# Space: O(n)\n\nimport heapq\n\n\nclass Solution(object):\n def minimumDeviation(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n max_heap = [-num*2 if num%2 else -num for num in nums]\n heapq.heapify(max_heap)\n min_elem = -max(max_heap)\n result = float(\"inf\")\n while len(max_heap) == len(nums):\n num = -heapq.heappop(max_heap)\n result = min(result, num-min_elem)\n if not num%2:\n min_elem = min(min_elem, num//2)\n heapq.heappush(max_heap, -num//2)\n return result\n"}} diff --git a/cp/cp-11058.jsonl b/cp/cp-11058.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..34e28586c2399d2986c819768a9d1e9192a3250e --- /dev/null +++ b/cp/cp-11058.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11058", "name": "LeetCode 1678: Goal Parser Interpretation"} +{"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: Goal Parser Interpretation (Difficulty: Easy)\nTags: String\n\nYou own a Goal Parser that can interpret a string command. The command consists of an alphabet of \"G\", \"()\" and/or \"(al)\" in some order. The Goal Parser will interpret \"G\" as the string \"G\", \"()\" as the string \"o\", and \"(al)\" as the string \"al\". The interpreted strings are then concatenated in the original order.\nGiven the string command, return the Goal Parser's interpretation of command.\n\nExample 1:\nInput: command = \"G()(al)\"\nOutput: \"Goal\"\nExplanation: The Goal Parser interprets the command as follows:\nG -> G\n() -> o\n(al) -> al\nThe final concatenated result is \"Goal\".\n\nExample 2:\nInput: command = \"G()()()()(al)\"\nOutput: \"Gooooal\"\n\nExample 3:\nInput: command = \"(al)G(al)()()G\"\nOutput: \"alGalooG\"\n\nConstraints:\n- 1 <= command.length <= 100\n- command consists of \"G\", \"()\", and/or \"(al)\" in some order."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def interpret(self, command):\n \"\"\"\n :type command: str\n :rtype: str\n \"\"\"\n result, i = [], 0\n while i < len(command):\n if command[i] == 'G':\n result += [\"G\"]\n i += 1\n elif command[i] == '(' and command[i+1] == ')':\n result += [\"o\"]\n i += 2\n else:\n result += [\"al\"]\n i += 4\n return \"\".join(result)\n"}} diff --git a/cp/cp-11059.jsonl b/cp/cp-11059.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..786b95e97e7d2d43ca720fa6d9bfee4d35b13fd5 --- /dev/null +++ b/cp/cp-11059.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11059", "name": "LeetCode 1679: Max Number Of K 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: Max Number of K-Sum Pairs (Difficulty: Medium)\nTags: Array, Hash Table, Two Pointers, Sorting\n\nYou are given an integer array nums and an integer k.\nIn one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.\nReturn the maximum number of operations you can perform on the array.\n\nExample 1:\nInput: nums = [1,2,3,4], k = 5\nOutput: 2\nExplanation: Starting with nums = [1,2,3,4]:\n- Remove numbers 1 and 4, then nums = [2,3]\n- Remove numbers 2 and 3, then nums = []\nThere are no more pairs that sum up to 5, hence a total of 2 operations.\n\nExample 2:\nInput: nums = [3,1,3,4,3], k = 6\nOutput: 1\nExplanation: Starting with nums = [3,1,3,4,3]:\n- Remove the first two 3's, then nums = [1,4,3]\nThere are no more pairs that sum up to 6, hence a total of 1 operation.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i] <= 10^9\n- 1 <= k <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def maxOperations(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n count = collections.Counter()\n result = 0\n for x in nums:\n if k-x in count and count[k-x]:\n count[k-x] -= 1\n result += 1\n else:\n count[x] += 1\n return result\n"}} diff --git a/cp/cp-11060.jsonl b/cp/cp-11060.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7dfd29892f84872cb4c9ea097b1e78992725e6ac --- /dev/null +++ b/cp/cp-11060.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11060", "name": "LeetCode 1680: Concatenation Of Consecutive Binary 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: Concatenation of Consecutive Binary Numbers (Difficulty: Medium)\nTags: Math, Bit Manipulation, Simulation\n\nGiven an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7.\n\nExample 1:\nInput: n = 1\nOutput: 1\nExplanation: \"1\" in binary corresponds to the decimal value 1.\n\nExample 2:\nInput: n = 3\nOutput: 27\nExplanation: In binary, 1, 2, and 3 corresponds to \"1\", \"10\", and \"11\".\nAfter concatenating them, we have \"11011\", which corresponds to the decimal value 27.\n\nExample 3:\nInput: n = 12\nOutput: 505379714\nExplanation: The concatenation results in \"1101110010111011110001001101010111100\".\nThe decimal value of that is 118505380540.\nAfter modulo 109 + 7, the result is 505379714.\n\nConstraints:\n- 1 <= n <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def concatenatedBinary(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n result = l = 0\n for i in range(1, n+1):\n if i&(i-1) == 0:\n l += 1\n result = ((result< sum(nCr(n, k) * 2^k for k in range(n+1)) = (1 + 2)^n = 3^n\n # => Time: O(3^n), see https://cp-algorithms.com/algebra/all-submasks.html\n submask = mask\n while submask:\n dp[mask] = min(dp[mask], dp[mask-submask] + candidates[submask])\n submask = (submask-1)&mask\n return dp[-1] if dp[-1] != inf else -1\n\n\n# Time: O(nlogn)\n# Space: O(n)\nimport collections\nimport sortedcontainers\n# wrong with greedy solution\n# nums = [15, 9, 7, 10, 15, 14, 12, 2, 10, 8, 10, 13, 4, 11, 2]\n# k = 5\n# greedy => [[2, 4, 7], [2, 8, 9], [10, 11, 12], [10, 13, 15], [10, 14, 15]] => 24\n# correct => [[2, 4, 7], [2, 8, 10], [9, 10, 11], [10, 12, 15], [13, 14, 15]] => 22\n# optimized from Solution_Greedy, using SortedList (which is not supported in GoogleCodeJam / GoogleKickStart)\nclass Solution_Wrong_Greedy_SortedList(object):\n def minimumIncompatibility(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n def greedy(nums, k, is_reversed):\n count = collections.Counter(nums)\n if max(count.itervalues()) > k:\n return -1\n ordered_set = sortedcontainers.SortedList(count.iterkeys())\n freq_to_nodes = collections.defaultdict(collections.OrderedDict)\n for x in ordered_set:\n freq_to_nodes[count[x]][x] = count[x]\n stks = [[] for _ in range(k)] \n curr = 0\n while ordered_set: # the while loop runs O(k) times\n if len(stks)-curr in freq_to_nodes: # fill the deterministic elements into the remaining subsets\n for x in freq_to_nodes[len(stks)-curr].iterkeys(): # total time = O(n)\n for i in range(curr, len(stks)):\n stks[i].append(x)\n count.pop(x)\n ordered_set.remove(x)\n freq_to_nodes.pop(len(stks)-curr)\n # greedily fill the contiguous ordered elements into the first vacant subset until it is full,\n # otherwise, the result sum would get larger => in fact, this is wrong\n to_remove = []\n direction = (lambda x:x) if not is_reversed else reversed\n for x in direction(ordered_set):\n stks[curr].append(x)\n freq_to_nodes[count[x]].pop(x)\n if not freq_to_nodes[count[x]]:\n freq_to_nodes.pop(count[x])\n count[x] -= 1 # total time = O(n)\n if not count[x]:\n count.pop(x)\n to_remove.append(x)\n else:\n freq_to_nodes[count[x]][x] = count[x]\n if len(stks[curr]) == len(nums)//k:\n curr += 1\n break\n for x in to_remove:\n ordered_set.remove(x) # total time = O(nlogn)\n return sum([max(stk)-min(stk) for stk in stks])\n\n return min(greedy(nums, k, False), greedy(nums, k, True)) # two possible minimas\n\n\n# Time: O(nlogn)\n# Space: O(n)\nimport collections\nfrom random import randint, seed\n\n\n# Template modified from:\n# https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/design-skiplist.py\nclass SkipNode(object):\n def __init__(self, level=0, val=None):\n self.val = val\n self.nexts = [None]*level\n self.prevs = [None]*level\n\nclass SkipList(object):\n P_NUMERATOR, P_DENOMINATOR = 1, 2 # P = 1/4 in redis implementation\n MAX_LEVEL = 32 # enough for 2^32 elements\n\n def __init__(self, end=float(\"inf\"), can_duplicated=False, cmp=lambda x, y: x < y):\n seed(0)\n self.__head = SkipNode()\n self.__len = 0\n self.__can_duplicated = can_duplicated\n self.__cmp = cmp\n self.add(end)\n self.__end = self.find(end)\n\n def begin(self):\n return self.__head.nexts[0]\n \n def end(self):\n return self.__end\n\n def lower_bound(self, target):\n return self.__lower_bound(target, self.__find_prev_nodes(target))\n\n def find(self, target):\n return self.__find(target, self.__find_prev_nodes(target))\n \n def add(self, val):\n if not self.__can_duplicated and self.find(val):\n return self.find(val), False\n node = SkipNode(self.__random_level(), val)\n if len(self.__head.nexts) < len(node.nexts): \n self.__head.nexts.extend([None]*(len(node.nexts)-len(self.__head.nexts)))\n prevs = self.__find_prev_nodes(val)\n for i in range(len(node.nexts)):\n node.nexts[i] = prevs[i].nexts[i]\n if prevs[i].nexts[i]:\n prevs[i].nexts[i].prevs[i] = node\n prevs[i].nexts[i] = node\n node.prevs[i] = prevs[i]\n self.__len += 1\n return node if self.__can_duplicated else (node, True)\n\n def remove(self, it):\n prevs = it.prevs\n curr = self.__find(it.val, prevs)\n if not curr:\n return self.__end\n self.__len -= 1 \n for i in reversed(range(len(curr.nexts))):\n prevs[i].nexts[i] = curr.nexts[i]\n if curr.nexts[i]:\n curr.nexts[i].prevs[i] = prevs[i]\n if not self.__head.nexts[i]:\n self.__head.nexts.pop()\n return curr.nexts[0]\n \n def __lower_bound(self, val, prevs):\n if prevs:\n candidate = prevs[0].nexts[0]\n if candidate:\n return candidate\n return None\n\n def __find(self, val, prevs):\n candidate = self.__lower_bound(val, prevs)\n if candidate and candidate.val == val:\n return candidate\n return None\n\n def __find_prev_nodes(self, val):\n prevs = [None]*len(self.__head.nexts)\n curr = self.__head\n for i in reversed(range(len(self.__head.nexts))):\n while curr.nexts[i] and self.__cmp(curr.nexts[i].val, val):\n curr = curr.nexts[i]\n prevs[i] = curr\n return prevs\n\n def __random_level(self):\n level = 1\n while randint(1, SkipList.P_DENOMINATOR) <= SkipList.P_NUMERATOR and \\\n level < SkipList.MAX_LEVEL:\n level += 1\n return level\n \n def __iter__(self):\n it = self.begin()\n while it != self.end():\n yield it.val\n it = it.nexts[0]\n\n def __len__(self):\n return self.__len-1 # excluding end node\n\n def __str__(self):\n result = []\n for i in reversed(range(len(self.__head.nexts))):\n result.append([])\n curr = self.__head.nexts[i]\n while curr:\n result[-1].append(str(curr.val))\n curr = curr.nexts[i]\n return \"\\n\".join(map(lambda x: \"->\".join(x), result))\n\n# wrong with greedy solution\n# nums = [15, 9, 7, 10, 15, 14, 12, 2, 10, 8, 10, 13, 4, 11, 2]\n# k = 5\n# greedy => [[2, 4, 7], [2, 8, 9], [10, 11, 12], [10, 13, 15], [10, 14, 15]] => 24\n# correct => [[2, 4, 7], [2, 8, 10], [9, 10, 11], [10, 12, 15], [13, 14, 15]] => 22\n# optimized from Solution_Wrong_Greedy, using SkipList\nclass Solution_Wrong_Greedy_SkipList(object):\n def minimumIncompatibility(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n def greedy(nums, k, is_reversed):\n count = collections.Counter(nums)\n if max(count.itervalues()) > k:\n return -1\n ordered_set = SkipList() if not is_reversed else SkipList(end=float(\"-inf\"), cmp=lambda x, y: x > y)\n freq_to_nodes = collections.defaultdict(collections.OrderedDict)\n for x in sorted(count.keys(), reverse=is_reversed):\n ordered_set.add(x)\n freq_to_nodes[count[x]][x] = count[x]\n stks = [[] for _ in range(k)] \n curr = 0\n while ordered_set: # the while loop runs O(k) times\n if len(stks)-curr in freq_to_nodes: # fill the deterministic elements into the remaining subsets\n for x in freq_to_nodes[len(stks)-curr].iterkeys(): # total time = O(n)\n for i in range(curr, len(stks)):\n stks[i].append(x)\n count.pop(x)\n ordered_set.remove(ordered_set.find(x))\n freq_to_nodes.pop(len(stks)-curr)\n # greedily fill the contiguous ordered elements into the first vacant subset until it is full,\n # otherwise, the result sum would get larger => in fact, this is wrong\n it = ordered_set.begin()\n while it != ordered_set.end():\n x = it.val\n stks[curr].append(x)\n freq_to_nodes[count[x]].pop(x)\n if not freq_to_nodes[count[x]]:\n freq_to_nodes.pop(count[x])\n count[x] -= 1 # total time = O(n)\n if not count[x]:\n count.pop(x)\n it = ordered_set.remove(it) # total time = O(nlogn)\n else:\n freq_to_nodes[count[x]][x] = count[x]\n it = it.nexts[0]\n if len(stks[curr]) == len(nums)//k:\n curr += 1\n break\n return sum([max(stk)-min(stk) for stk in stks])\n\n return min(greedy(nums, k, False), greedy(nums, k, True)) # two possible minimas\n\n\n# Time: O(nlogn + k * n), could be improved to O(nlogn) by skiplist or orderedlist\n# Space: O(n)\nimport collections\n# wrong with greedy solution\n# nums = [15, 9, 7, 10, 15, 14, 12, 2, 10, 8, 10, 13, 4, 11, 2]\n# k = 5\n# greedy => [[2, 4, 7], [2, 8, 9], [10, 11, 12], [10, 13, 15], [10, 14, 15]] => 24\n# correct => [[2, 4, 7], [2, 8, 10], [9, 10, 11], [10, 12, 15], [13, 14, 15]] => 22\nclass Solution_Wrong_Greedy(object):\n def minimumIncompatibility(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n def greedy(nums, k, is_reversed):\n count = collections.Counter(nums)\n if max(count.itervalues()) > k:\n return -1\n sorted_keys = sorted(count.keys(), reverse=is_reversed)\n stks = [[] for _ in range(k)] \n curr, remain = 0, len(nums)\n while remain: # the while loop runs O(k) times, and the inner loops runs O(n) times\n for x in sorted_keys: # fill the deterministic elements into the remaining subsets\n if count[x] != len(stks)-curr:\n continue\n for i in range(curr, len(stks)):\n stks[i].append(x)\n remain -= count[x]\n count[x] = 0\n # greedily fill the contiguous ordered elements into the first vacant subset until it is full,\n # otherwise, the result sum would get larger => in fact, this is wrong\n for x in sorted_keys:\n if not count[x]:\n continue\n stks[curr].append(x)\n remain -= 1\n count[x] -= 1\n if len(stks[curr]) == len(nums)//k:\n curr += 1\n break\n return sum([max(stk)-min(stk) for stk in stks])\n\n return min(greedy(nums, k, False), greedy(nums, k, True)) # two possible minimas\n\n"}} diff --git a/cp/cp-11063.jsonl b/cp/cp-11063.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..11b660b532da92fe07bfc886669eb4fd57619281 --- /dev/null +++ b/cp/cp-11063.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11063", "name": "LeetCode 1684: Count The Number Of Consistent Strings"} +{"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: Count the Number of Consistent Strings (Difficulty: Easy)\nTags: Array, Hash Table, String, Bit Manipulation, Counting\n\nYou are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed.\nReturn the number of consistent strings in the array words.\n\nExample 1:\nInput: allowed = \"ab\", words = [\"ad\",\"bd\",\"aaab\",\"baa\",\"badab\"]\nOutput: 2\nExplanation: Strings \"aaab\" and \"baa\" are consistent since they only contain characters 'a' and 'b'.\n\nExample 2:\nInput: allowed = \"abc\", words = [\"a\",\"b\",\"c\",\"ab\",\"ac\",\"bc\",\"abc\"]\nOutput: 7\nExplanation: All strings are consistent.\n\nExample 3:\nInput: allowed = \"cad\", words = [\"cc\",\"acd\",\"b\",\"ba\",\"bac\",\"bad\",\"ac\",\"d\"]\nOutput: 4\nExplanation: Strings \"cc\", \"acd\", \"ac\", and \"d\" are consistent.\n\nConstraints:\n- 1 <= words.length <= 10^4\n- 1 <= allowed.length <= 26\n- 1 <= words[i].length <= 10\n- The characters in allowed are distinct.\n- words[i] and allowed contain only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def countConsistentStrings(self, allowed, words):\n \"\"\"\n :type allowed: str\n :type words: List[str]\n :rtype: int\n \"\"\"\n lookup = [False]*26\n for c in allowed:\n lookup[ord(c)-ord('a')] = True\n result = len(words)\n for word in words:\n for c in word:\n if not lookup[ord(c)-ord('a')]:\n result -= 1\n break\n return result\n"}} diff --git a/cp/cp-11064.jsonl b/cp/cp-11064.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..317a8591844ecdffcab26ca3a02c76c62a90ea8d --- /dev/null +++ b/cp/cp-11064.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11064", "name": "LeetCode 1685: Sum Of Absolute Differences In A Sorted 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: Sum of Absolute Differences in a Sorted Array (Difficulty: Medium)\nTags: Array, Math, Prefix Sum\n\nYou are given an integer array nums sorted in non-decreasing order.\nBuild and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.\nIn other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed).\n\nExample 1:\nInput: nums = [2,3,5]\nOutput: [4,3,5]\nExplanation: Assuming the arrays are 0-indexed, then\nresult[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,\nresult[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,\nresult[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.\n\nExample 2:\nInput: nums = [1,4,6,8,10]\nOutput: [24,15,13,15,21]\n\nConstraints:\n- 2 <= nums.length <= 10^5\n- 1 <= nums[i] <= nums[i + 1] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def getSumAbsoluteDifferences(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n prefix, suffix = 0, sum(nums)\n result = []\n for i, num in enumerate(nums):\n suffix -= num\n result.append((i*num-prefix) + (suffix-((len(nums)-1)-i)*num))\n prefix += num\n return result\n"}} diff --git a/cp/cp-11065.jsonl b/cp/cp-11065.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3a2ae87fe75ebaac5e680df0310325b05ac5d929 --- /dev/null +++ b/cp/cp-11065.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11065", "name": "LeetCode 1686: Stone Game Vi"} +{"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: Stone Game VI (Difficulty: Medium)\nTags: Array, Math, Greedy, Sorting, Heap (Priority Queue), Game Theory\n\nAlice and Bob take turns playing a game, with Alice starting first.\nThere are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently.\nYou are given two integer arrays of length n, aliceValues and bobValues. Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the ith stone.\nThe winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally. Both players know the other's values.\nDetermine the result of the game, and:\n\nExample 1:\nInput: aliceValues = [1,3], bobValues = [2,1]\nOutput: 1\nExplanation:\nIf Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.\nBob can only choose stone 0, and will only receive 2 points.\nAlice wins.\n\nExample 2:\nInput: aliceValues = [1,2], bobValues = [3,1]\nOutput: 0\nExplanation:\nIf Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.\nDraw.\n\nExample 3:\nInput: aliceValues = [2,4,3], bobValues = [1,6,7]\nOutput: -1\nExplanation:\nRegardless of how Alice plays, Bob will be able to have more points than Alice.\nFor example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7.\nBob wins.\n\nConstraints:\n- n == aliceValues.length == bobValues.length\n- 1 <= n <= 10^5\n- 1 <= aliceValues[i], bobValues[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass Solution(object):\n def stoneGameVI(self, aliceValues, bobValues):\n \"\"\"\n :type aliceValues: List[int]\n :type bobValues: List[int]\n :rtype: int\n \"\"\"\n sorted_vals = sorted(((a, b) for a, b in zip(aliceValues, bobValues)), key=sum, reverse=True)\n return cmp(sum(a for a, _ in sorted_vals[::2]), sum(b for _, b in sorted_vals[1::2]))\n"}} diff --git a/cp/cp-11066.jsonl b/cp/cp-11066.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dd6bbfa04bed300cdb9e887aa8822d0c0bbd284c --- /dev/null +++ b/cp/cp-11066.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11066", "name": "LeetCode 1687: Delivering Boxes From Storage To Ports"} +{"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: Delivering Boxes from Storage to Ports (Difficulty: Hard)\nTags: Array, Dynamic Programming, Segment Tree, Queue, Heap (Priority Queue), Prefix Sum, Monotonic Queue\n\nYou have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry.\nYou are given an array boxes, where boxes[i] = [ports​​i​, weighti], and three integers portsCount, maxBoxes, and maxWeight.\nThe boxes need to be delivered in the order they are given. The ship will follow these steps:\nThe ship must end at storage after all the boxes have been delivered.\nReturn the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.\n\nExample 1:\nInput: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3\nOutput: 4\nExplanation: The optimal strategy is as follows: \n- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.\nSo the total number of trips is 4.\nNote that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).\n\nExample 2:\nInput: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6\nOutput: 6\nExplanation: The optimal strategy is as follows: \n- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.\n- The ship takes the fifth box, goes to port 2, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.\n\nExample 3:\nInput: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7\nOutput: 6\nExplanation: The optimal strategy is as follows:\n- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.\n- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.\n\nConstraints:\n- 1 <= boxes.length <= 10^5\n- 1 <= portsCount, maxBoxes, maxWeight <= 10^5\n- 1 <= ports​​i <= portsCount\n- 1 <= weightsi <= maxWeight"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def boxDelivering(self, boxes, portsCount, maxBoxes, maxWeight):\n \"\"\"\n :type boxes: List[List[int]]\n :type portsCount: int\n :type maxBoxes: int\n :type maxWeight: int\n :rtype: int\n \"\"\"\n dp = [0]*(len(boxes)+1)\n left, cost, curr = 0, 1, 0\n for right in range(len(boxes)):\n if right == 0 or boxes[right][0] != boxes[right-1][0]:\n cost += 1\n curr += boxes[right][1]\n while right-left+1 > maxBoxes or \\\n curr > maxWeight or \\\n (left+1 < right+1 and dp[left+1] == dp[left]): # greedily drop box to make cost as smaller as possible\n curr -= boxes[left][1]\n if boxes[left+1][0] != boxes[left][0]:\n cost -= 1\n left += 1\n dp[right+1] = dp[(left-1)+1] + cost\n return dp[len(boxes)]\n"}} diff --git a/cp/cp-11069.jsonl b/cp/cp-11069.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..be612698cffa7a0a5ddd5107875d551563eb116b --- /dev/null +++ b/cp/cp-11069.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11069", "name": "LeetCode 1690: Stone Game Vii"} +{"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: Stone Game VII (Difficulty: Medium)\nTags: Array, Math, Dynamic Programming, Game Theory\n\nAlice and Bob take turns playing a game, with Alice starting first.\nThere are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove.\nBob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score.\nGiven an array of integers stones where stones[i] represents the value of the ith stone from the left, return the difference in Alice and Bob's score if they both play optimally.\n\nExample 1:\nInput: stones = [5,3,1,4,2]\nOutput: 6\nExplanation: \n- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4].\n- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4].\n- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4].\n- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4].\n- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = [].\nThe score difference is 18 - 12 = 6.\n\nExample 2:\nInput: stones = [7,90,5,1,100,10,10,2]\nOutput: 122\n\nConstraints:\n- n == stones.length\n- 2 <= n <= 1000\n- 1 <= stones[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def stoneGameVII(self, stones):\n \"\"\"\n :type stones: List[int]\n :rtype: int\n \"\"\"\n def score(i, j):\n return prefix[j+1]-prefix[i]\n\n prefix = [0]\n for stone in stones:\n prefix.append(prefix[-1]+stone)\n dp = [[0 for _ in range(len(stones))] for _ in range(2)]\n for i in reversed(range(len(stones))):\n for j in range(i+1, len(stones)):\n dp[i%2][j] = max(score(i+1, j)-dp[(i+1)%2][j], score(i, j-1)-dp[i%2][j-1])\n return dp[0][-1]\n"}} diff --git a/cp/cp-11070.jsonl b/cp/cp-11070.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5752c3f9d15f702a94a9641f49e2f65ca160b2b7 --- /dev/null +++ b/cp/cp-11070.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11070", "name": "LeetCode 1691: Maximum Height By Stacking Cuboids"} +{"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 Height by Stacking Cuboids (Difficulty: Hard)\nTags: Array, Dynamic Programming, Sorting\n\nGiven n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] (0-indexed). Choose a subset of cuboids and place them on each other.\nYou can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid.\nReturn the maximum height of the stacked cuboids.\n\nExample 1:\nInput: cuboids = [[50,45,20],[95,37,53],[45,23,12]]\nOutput: 190\nExplanation:\nCuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.\nCuboid 0 is placed next with the 45x20 side facing down with height 50.\nCuboid 2 is placed next with the 23x12 side facing down with height 45.\nThe total height is 95 + 50 + 45 = 190.\n\nExample 2:\nInput: cuboids = [[38,25,45],[76,35,3]]\nOutput: 76\nExplanation:\nYou can't place any of the cuboids on the other.\nWe choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.\n\nExample 3:\nInput: cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]\nOutput: 102\nExplanation:\nAfter rearranging the cuboids, you can see that all cuboids have the same dimension.\nYou can place the 11x7 side down on all cuboids so their heights are 17.\nThe maximum height of stacked cuboids is 6 * 17 = 102.\n\nConstraints:\n- n == cuboids.length\n- 1 <= n <= 100\n- 1 <= widthi, lengthi, heighti <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n \nclass Solution(object):\n def maxHeight(self, cuboids):\n \"\"\"\n :type cuboids: List[List[int]]\n :rtype: int\n \"\"\"\n for cuboid in cuboids:\n cuboid.sort()\n cuboids.append([0, 0, 0])\n cuboids.sort()\n dp = [0]*len(cuboids)\n for i in range(1, len(cuboids)):\n for j in range(i):\n if all(cuboids[j][k] <= cuboids[i][k] for k in range(3)):\n dp[i] = max(dp[i], dp[j]+cuboids[i][2])\n return max(dp)\n"}} diff --git a/cp/cp-11072.jsonl b/cp/cp-11072.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4a8d3d28443ee1dd36aa640e78631798f440a910 --- /dev/null +++ b/cp/cp-11072.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11072", "name": "LeetCode 1694: Reformat Phone 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: Reformat Phone Number (Difficulty: Easy)\nTags: String\n\nYou are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'.\nYou would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows:\nThe blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2.\nReturn the phone number after formatting.\n\nExample 1:\nInput: number = \"1-23-45 6\"\nOutput: \"123-456\"\nExplanation: The digits are \"123456\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is \"456\".\nJoining the blocks gives \"123-456\".\n\nExample 2:\nInput: number = \"123 4-567\"\nOutput: \"123-45-67\"\nExplanation: The digits are \"1234567\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are \"45\" and \"67\".\nJoining the blocks gives \"123-45-67\".\n\nExample 3:\nInput: number = \"123 4-5678\"\nOutput: \"123-456-78\"\nExplanation: The digits are \"12345678\".\nStep 1: The 1st block is \"123\".\nStep 2: The 2nd block is \"456\".\nStep 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is \"78\".\nJoining the blocks gives \"123-456-78\".\n\nConstraints:\n- 2 <= number.length <= 100\n- number consists of digits and the characters '-' and ' '.\n- There are at least two digits in number."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# inplace solution\nclass Solution(object):\n def reformatNumber(self, number):\n \"\"\"\n :type number: str\n :rtype: str\n \"\"\"\n number = list(number)\n src_len = 0\n for c in number: # remove non-digit characters\n if c.isdigit():\n number[src_len] = c\n src_len += 1\n dst_len = src_len + (src_len-1)//3\n if dst_len > len(number): # resize the buffer to expected final size\n number.extend([0]*(dst_len-len(number)))\n while dst_len < len(number):\n number.pop()\n curr = dst_len-1\n for l, i in enumerate(reversed(range(src_len)), (3-src_len%3)%3):\n if l and l%3 == 0: # group by 3 digits\n number[curr] = '-'\n curr -= 1\n number[curr] = number[i]\n curr -= 1\n if dst_len >= 3 and number[dst_len-2] == '-': # adjust for the 4 digits case\n number[dst_len-3], number[dst_len-2] = number[dst_len-2], number[dst_len-3] \n return \"\".join(number)\n"}} diff --git a/cp/cp-11073.jsonl b/cp/cp-11073.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c14f0c1f95b8b48e803acefd0ebdaa55120e7d39 --- /dev/null +++ b/cp/cp-11073.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11073", "name": "LeetCode 1695: Maximum Erasure Value"} +{"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 Erasure Value (Difficulty: Medium)\nTags: Array, Hash Table, Sliding Window\n\nYou are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.\nReturn the maximum score you can get by erasing exactly one subarray.\nAn array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r).\n\nExample 1:\nInput: nums = [4,2,4,5,6]\nOutput: 17\nExplanation: The optimal subarray here is [2,4,5,6].\n\nExample 2:\nInput: nums = [5,2,1,2,5,2,1,2,5]\nOutput: 8\nExplanation: The optimal subarray here is [5,2,1] or [1,2,5].\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def maximumUniqueSubarray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n lookup = {}\n prefix = [0]*(len(nums)+1)\n result, left = 0, 0\n for right, num in enumerate(nums):\n prefix[right+1] = prefix[right]+num\n if num in lookup:\n left = max(left, lookup[num]+1)\n lookup[num] = right\n result = max(result, prefix[right+1]-prefix[left])\n return result\n"}} diff --git a/cp/cp-11074.jsonl b/cp/cp-11074.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8e6db7467e4e0d7de4b5f063fa55541b90c1c8ec --- /dev/null +++ b/cp/cp-11074.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11074", "name": "LeetCode 1696: Jump Game Vi"} +{"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: Jump Game VI (Difficulty: Medium)\nTags: Array, Dynamic Programming, Queue, Heap (Priority Queue), Monotonic Queue\n\nYou are given a 0-indexed integer array nums and an integer k.\nYou are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive.\nYou want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array.\nReturn the maximum score you can get.\n\nExample 1:\nInput: nums = [1,-1,-2,4,-7,3], k = 2\nOutput: 7\nExplanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.\n\nExample 2:\nInput: nums = [10,-5,-2,4,0,3], k = 3\nOutput: 17\nExplanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.\n\nExample 3:\nInput: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2\nOutput: 0\n\nConstraints:\n- 1 <= nums.length, k <= 10^5\n- -10^4 <= nums[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(k)\n\nimport collections\n\n\nclass Solution(object):\n def maxResult(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n score = 0\n dq = collections.deque()\n for i, num in enumerate(nums):\n if dq and dq[0][0] == i-k-1:\n dq.popleft()\n score = num if not dq else dq[0][1]+num\n while dq and dq[-1][1] <= score:\n dq.pop()\n dq.append((i, score))\n return score\n"}} diff --git a/cp/cp-11075.jsonl b/cp/cp-11075.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..39c87adfd8710b6a8d3228a0a1b4ef52d4cde7e1 --- /dev/null +++ b/cp/cp-11075.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11075", "name": "LeetCode 1697: Checking Existence Of Edge Length Limited Paths"} +{"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: Checking Existence of Edge Length Limited Paths (Difficulty: Hard)\nTags: Array, Two Pointers, Union Find, Graph, Sorting\n\nAn undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes.\nGiven an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj .\nReturn a boolean array answer, where answer.length == queries.length and the jth value of answer is true if there is a path for queries[j] is true, and false otherwise.\n\nExample 1:\nInput: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]\nOutput: [false,true]\nExplanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.\nFor the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.\nFor the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.\n\nExample 2:\nInput: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]\nOutput: [true,false]\nExplanation: The above figure shows the given graph.\n\nConstraints:\n- 2 <= n <= 10^5\n- 1 <= edgeList.length, queries.length <= 10^5\n- edgeList[i].length == 3\n- queries[j].length == 3\n- 0 <= ui, vi, pj, qj <= n - 1\n- ui != vi\n- pj != qj\n- 1 <= disi, limitj <= 10^9\n- There may be multiple edges between two nodes."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn + mlogm + n * α(n)) = O(nlogn + mlogm)\n# Space: O(n)\n\nclass UnionFind(object): # Time: O(n * α(n)), Space: O(n)\n def __init__(self, n):\n self.set = range(n)\n self.rank = [0]*n\n\n def find_set(self, x):\n stk = []\n while self.set[x] != x: # path compression\n stk.append(x)\n x = self.set[x]\n while stk:\n self.set[stk.pop()] = x\n return x\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n if self.rank[x_root] < self.rank[y_root]: # union by rank\n self.set[x_root] = y_root\n elif self.rank[x_root] > self.rank[y_root]:\n self.set[y_root] = x_root\n else:\n self.set[y_root] = x_root\n self.rank[x_root] += 1\n return True\n\n\nclass Solution(object):\n def distanceLimitedPathsExist(self, n, edgeList, queries):\n \"\"\"\n :type n: int\n :type edgeList: List[List[int]]\n :type queries: List[List[int]]\n :rtype: List[bool]\n \"\"\"\n for i, q in enumerate(queries):\n q.append(i)\n edgeList.sort(key=lambda x: x[2])\n queries.sort(key=lambda x: x[2])\n \n union_find = UnionFind(n)\n result = [False]*len(queries)\n curr = 0\n for u, v, w, i in queries: \n while curr < len(edgeList) and edgeList[curr][2] < w: \n union_find.union_set(edgeList[curr][0], edgeList[curr][1])\n curr += 1\n result[i] = union_find.find_set(u) == union_find.find_set(v)\n return result \n"}} diff --git a/cp/cp-11077.jsonl b/cp/cp-11077.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..744818a20ebee7e72cc8c7944773bb7ff685ea37 --- /dev/null +++ b/cp/cp-11077.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11077", "name": "LeetCode 1700: Number Of Students Unable To Eat Lunch"} +{"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 Students Unable to Eat Lunch (Difficulty: Easy)\nTags: Array, Stack, Queue, Simulation\n\nThe school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.\nThe number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step:\nThis continues until none of the queue students want to take the top sandwich and are thus unable to eat.\nYou are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i​​​​​​th sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j​​​​​​th student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat.\n\nExample 1:\nInput: students = [1,1,0,0], sandwiches = [0,1,0,1]\nOutput: 0 \nExplanation:\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].\n- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].\n- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].\n- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].\n- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].\nHence all students are able to eat.\n\nExample 2:\nInput: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]\nOutput: 3\n\nConstraints:\n- 1 <= students.length, sandwiches.length <= 100\n- students.length == sandwiches.length\n- sandwiches[i] is 0 or 1.\n- students[i] is 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def countStudents(self, students, sandwiches):\n \"\"\"\n :type students: List[int]\n :type sandwiches: List[int]\n :rtype: int\n \"\"\"\n count = collections.Counter(students)\n for i, s in enumerate(sandwiches):\n if not count[s]:\n break\n count[s] -= 1\n else:\n i = len(sandwiches)\n return len(sandwiches)-i\n"}} diff --git a/cp/cp-11078.jsonl b/cp/cp-11078.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4fa1385e10977cf7d8110fc08813019c891fab89 --- /dev/null +++ b/cp/cp-11078.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11078", "name": "LeetCode 1701: Average Waiting Time"} +{"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 Waiting Time (Difficulty: Medium)\nTags: Array, Simulation\n\nThere is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrivali, timei]:\nWhen a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input.\nReturn the average waiting time of all customers. Solutions within 10-5 from the actual answer are considered accepted.\n\nExample 1:\nInput: customers = [[1,2],[2,5],[4,3]]\nOutput: 5.00000\nExplanation:\n1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2.\n2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6.\n3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7.\nSo the average waiting time = (2 + 6 + 7) / 3 = 5.\n\nExample 2:\nInput: customers = [[5,2],[5,4],[10,3],[20,1]]\nOutput: 3.25000\nExplanation:\n1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2.\n2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6.\n3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4.\n4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1.\nSo the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.\n\nConstraints:\n- 1 <= customers.length <= 10^5\n- 1 <= arrivali, timei <= 10^4\n- arrivali <= arrivali+1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def averageWaitingTime(self, customers):\n \"\"\"\n :type customers: List[List[int]]\n :rtype: float\n \"\"\"\n avai = wait = 0.0\n for a, t in customers:\n avai = max(avai, a)+t\n wait += avai-a\n return wait/len(customers)\n"}} diff --git a/cp/cp-11079.jsonl b/cp/cp-11079.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..02b8f71b1f5dce467b424d9c8f2aea5fff99f4af --- /dev/null +++ b/cp/cp-11079.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11079", "name": "LeetCode 1702: Maximum Binary String After Change"} +{"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 String After Change (Difficulty: Medium)\nTags: String, Greedy\n\nYou are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times:\nReturn the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation.\n\nExample 1:\nInput: binary = \"000110\"\nOutput: \"111011\"\nExplanation: A valid transformation sequence can be:\n\"000110\" -> \"000101\" \n\"000101\" -> \"100101\" \n\"100101\" -> \"110101\" \n\"110101\" -> \"110011\" \n\"110011\" -> \"111011\"\n\nExample 2:\nInput: binary = \"01\"\nOutput: \"01\"\nExplanation: \"01\" cannot be transformed any further.\n\nConstraints:\n- 1 <= binary.length <= 10^5\n- binary consist of '0' and '1'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def maximumBinaryString(self, binary):\n \"\"\"\n :type binary: str\n :rtype: str\n \"\"\"\n result = list(binary)\n zeros = ones = 0\n for i, c in enumerate(result):\n if c == '0':\n zeros += 1\n elif zeros == 0:\n ones += 1\n result[i] = '1'\n if ones != len(result):\n result[zeros+ones-1] = '0'\n return \"\".join(result)\n"}} diff --git a/cp/cp-11080.jsonl b/cp/cp-11080.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..af4169744c5051ffbd1f9717b01d4b0e0d393834 --- /dev/null +++ b/cp/cp-11080.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11080", "name": "LeetCode 1703: Minimum Adjacent Swaps For K 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: Minimum Adjacent Swaps for K Consecutive Ones (Difficulty: Hard)\nTags: Array, Greedy, Sliding Window, Prefix Sum\n\nYou are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values.\nReturn the minimum number of moves required so that nums has k consecutive 1's.\n\nExample 1:\nInput: nums = [1,0,0,1,0,1], k = 2\nOutput: 1\nExplanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.\n\nExample 2:\nInput: nums = [1,0,0,0,0,0,1,1], k = 3\nOutput: 5\nExplanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].\n\nExample 3:\nInput: nums = [1,1,0,1], k = 2\nOutput: 0\nExplanation: nums already has 2 consecutive 1's.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- nums[i] is 0 or 1.\n- 1 <= k <= sum(nums)"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def minMoves(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n def moves(i, j):\n return prefix[j+1]-prefix[i]\n\n idxs = [i for i, x in enumerate(nums) if x]\n prefix = [0]*(len(idxs)+1)\n for i in range(len(idxs)):\n prefix[i+1] = prefix[i]+idxs[i]\n result = float(\"inf\")\n for i in range(len(idxs)-k+1):\n result = min(result, -moves(i, i+k//2-1) + moves(i+(k+1)//2, i+k-1)) # take each i+k//2 as median, find min dist to median\n result -= (k//2)*((k+1)//2) # rollback extra moves to the expected positions\n return result\n"}} diff --git a/cp/cp-11081.jsonl b/cp/cp-11081.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8b7310c6995879c00593ad7ab54be305c30ae146 --- /dev/null +++ b/cp/cp-11081.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11081", "name": "LeetCode 1704: Determine If String Halves Are Alike"} +{"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: Determine if String Halves Are Alike (Difficulty: Easy)\nTags: String, Counting\n\nYou are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.\nTwo strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.\nReturn true if a and b are alike. Otherwise, return false.\n\nExample 1:\nInput: s = \"book\"\nOutput: true\nExplanation: a = \"bo\" and b = \"ok\". a has 1 vowel and b has 1 vowel. Therefore, they are alike.\n\nExample 2:\nInput: s = \"textbook\"\nOutput: false\nExplanation: a = \"text\" and b = \"book\". a has 1 vowel whereas b has 2. Therefore, they are not alike.\nNotice that the vowel o is counted twice.\n\nConstraints:\n- 2 <= s.length <= 1000\n- s.length is even.\n- s consists of uppercase and lowercase letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def halvesAreAlike(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n vowels = set(\"aeiouAEIOU\")\n cnt1 = cnt2 = 0\n left, right = 0, len(s)-1\n while left < right:\n cnt1 += s[left] in vowels\n cnt2 += s[right] in vowels\n left += 1\n right -= 1\n return cnt1 == cnt2\n"}} diff --git a/cp/cp-11082.jsonl b/cp/cp-11082.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd78ff1b3f3fb6da0d3805e0b0563356415569c1 --- /dev/null +++ b/cp/cp-11082.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11082", "name": "LeetCode 1705: Maximum Number Of Eaten Apples"} +{"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 Number of Eaten Apples (Difficulty: Medium)\nTags: Array, Greedy, Heap (Priority Queue)\n\nThere is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0.\nYou decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days.\nGiven two integer arrays days and apples of length n, return the maximum number of apples you can eat.\n\nExample 1:\nInput: apples = [1,2,3,5,2], days = [3,2,1,4,2]\nOutput: 7\nExplanation: You can eat 7 apples:\n- On the first day, you eat an apple that grew on the first day.\n- On the second day, you eat an apple that grew on the second day.\n- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.\n- On the fourth to the seventh days, you eat apples that grew on the fourth day.\n\nExample 2:\nInput: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]\nOutput: 5\nExplanation: You can eat 5 apples:\n- On the first to the third day you eat apples that grew on the first day.\n- Do nothing on the fouth and fifth days.\n- On the sixth and seventh days you eat apples that grew on the sixth day.\n\nConstraints:\n- n == apples.length == days.length\n- 1 <= n <= 2 * 10^4\n- 0 <= apples[i], days[i] <= 2 * 10^4\n- days[i] = 0 if and only if apples[i] = 0."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport heapq\n\n\nclass Solution(object):\n def eatenApples(self, apples, days):\n \"\"\"\n :type apples: List[int]\n :type days: List[int]\n :rtype: int\n \"\"\"\n min_heap = []\n result = i = 0\n while i < len(apples) or min_heap:\n if i < len(apples) and apples[i] > 0:\n heapq.heappush(min_heap, [i+days[i], i])\n while min_heap and (min_heap[0][0] <= i or apples[min_heap[0][1]] == 0):\n heapq.heappop(min_heap)\n if min_heap:\n apples[min_heap[0][1]] -= 1\n result += 1\n i += 1\n return result\n"}} diff --git a/cp/cp-11083.jsonl b/cp/cp-11083.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4b42ff0e44dcda2e1d13faa597658d0e74e9cb7c --- /dev/null +++ b/cp/cp-11083.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11083", "name": "LeetCode 1706: Where Will The Ball Fall"} +{"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: Where Will the Ball Fall (Difficulty: Medium)\nTags: Array, Matrix, Simulation\n\nYou have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides.\nEach cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.\nWe drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a \"V\" shaped pattern between two boards or if a board redirects the ball into either wall of the box.\nReturn an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box.\n\nExample 1:\nInput: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]\nOutput: [1,-1,-1,-1,-1]\nExplanation: This example is shown in the photo.\nBall b0 is dropped at column 0 and falls out of the box at column 1.\nBall b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.\nBall b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.\nBall b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.\nBall b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.\n\nExample 2:\nInput: grid = [[-1]]\nOutput: [-1]\nExplanation: The ball gets stuck against the left wall.\n\nExample 3:\nInput: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]\nOutput: [0,1,2,3,4,-1]\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 100\n- grid[i][j] is 1 or -1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def findBall(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: List[int]\n \"\"\"\n result = []\n for c in range(len(grid[0])):\n for r in range(len(grid)):\n nc = c+grid[r][c]\n if not (0 <= nc < len(grid[0]) and grid[r][nc] == grid[r][c]):\n c = -1\n break\n c = nc\n result.append(c)\n return result\n"}} diff --git a/cp/cp-11084.jsonl b/cp/cp-11084.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0a5f6b6dbbe2eb65d4c44ec84ae911bc5bffa789 --- /dev/null +++ b/cp/cp-11084.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11084", "name": "LeetCode 1707: Maximum Xor With An Element From 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: Maximum XOR With an Element From Array (Difficulty: Hard)\nTags: Array, Bit Manipulation, Trie\n\nYou are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi].\nThe answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1.\nReturn an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.\n\nExample 1:\nInput: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]\nOutput: [3,3,7]\nExplanation:\n1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.\n2) 1 XOR 2 = 3.\n3) 5 XOR 2 = 7.\n\nExample 2:\nInput: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]\nOutput: [15,-1,5]\n\nConstraints:\n- 1 <= nums.length, queries.length <= 10^5\n- queries[i].length == 2\n- 0 <= nums[j], xi, mi <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn + mlogm + nlogk + mlogk), k is max(max(nums), max(xi))\n# Space: O(nlogk)\n\nclass Trie(object):\n def __init__(self, bit_length):\n self.__root = {}\n self.__bit_length = bit_length\n \n def insert(self, num):\n node = self.__root\n for i in reversed(range(self.__bit_length)):\n curr = (num>>i) & 1\n if curr not in node:\n node[curr] = {}\n node = node[curr]\n \n def query(self, num):\n if not self.__root: \n return -1\n node, result = self.__root, 0\n for i in reversed(range(self.__bit_length)):\n curr = (num>>i) & 1\n if 1^curr in node:\n node = node[1^curr]\n result |= 1< box:\n truckSize -= box\n result += box*units\n else:\n result += truckSize*units\n break\n return result\n"}} diff --git a/cp/cp-11087.jsonl b/cp/cp-11087.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2debf7cdbc170ce3eab15fed666adda5019c506f --- /dev/null +++ b/cp/cp-11087.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11087", "name": "LeetCode 1711: Count Good Meals"} +{"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: Count Good Meals (Difficulty: Medium)\nTags: Array, Hash Table\n\nA good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two.\nYou can pick any two different foods to make a good meal.\nGiven an array of integers deliciousness where deliciousness[i] is the deliciousness of the i​​​​​​th​​​​​​​​ item of food, return the number of different good meals you can make from this list modulo 109 + 7.\nNote that items with different indices are considered different even if they have the same deliciousness value.\n\nExample 1:\nInput: deliciousness = [1,3,5,7,9]\nOutput: 4\nExplanation: The good meals are (1,3), (1,7), (3,5) and, (7,9).\nTheir respective sums are 4, 8, 8, and 16, all of which are powers of 2.\n\nExample 2:\nInput: deliciousness = [1,1,1,3,3,3,7]\nOutput: 15\nExplanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.\n\nConstraints:\n- 1 <= deliciousness.length <= 10^5\n- 0 <= deliciousness[i] <= 220"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def countPairs(self, deliciousness):\n \"\"\"\n :type deliciousness: List[int]\n :rtype: int\n \"\"\"\n def floor_log2_x(x):\n return x.bit_length()-1\n\n MOD = 10**9+7\n max_pow = floor_log2_x(max(deliciousness))+1\n cnt = collections.Counter()\n result = 0\n for d in deliciousness:\n p = 1\n for i in range(max_pow+1):\n result = (result+cnt[p-d])%MOD\n p <<= 1\n cnt[d] += 1 \n return result\n"}} diff --git a/cp/cp-11088.jsonl b/cp/cp-11088.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7bff7790364a222b1ef7009b86898a08b80bfe63 --- /dev/null +++ b/cp/cp-11088.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11088", "name": "LeetCode 1712: Ways To Split Array Into Three Subarrays"} +{"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: Ways to Split Array Into Three Subarrays (Difficulty: Medium)\nTags: Array, Two Pointers, Binary Search, Prefix Sum\n\nA split of an integer array is good if:\nGiven nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: nums = [1,1,1]\nOutput: 1\nExplanation: The only good way to split nums is [1] [1] [1].\n\nExample 2:\nInput: nums = [1,2,2,2,5,0]\nOutput: 3\nExplanation: There are three good ways of splitting nums:\n[1] [2] [2,2,5,0]\n[1] [2,2] [2,5,0]\n[1,2] [2,2] [5,0]\n\nExample 3:\nInput: nums = [3,2,1]\nOutput: 0\nExplanation: There is no good way to split nums.\n\nConstraints:\n- 3 <= nums.length <= 10^5\n- 0 <= nums[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def waysToSplit(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n\n prefix = [0]\n for x in nums:\n prefix.append(prefix[-1]+x)\n\n result = left = right = 0 \n for i in range(len(nums)): \n left = max(left, i+1)\n while left+1 < len(nums) and prefix[i+1] > prefix[left+1]-prefix[i+1]:\n left += 1\n right = max(right, left)\n while right+1 < len(nums) and prefix[right+1]-prefix[i+1] <= prefix[-1]-prefix[right+1]:\n right += 1\n result = (result + (right-left))%MOD\n return result\n"}} diff --git a/cp/cp-11089.jsonl b/cp/cp-11089.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6abe0a752033e815ae433ce29f8ab084b30668c4 --- /dev/null +++ b/cp/cp-11089.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11089", "name": "LeetCode 1713: Minimum Operations To Make A 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: Minimum Operations to Make a Subsequence (Difficulty: Hard)\nTags: Array, Hash Table, Binary Search, Greedy\n\nYou are given an array target that consists of distinct integers and another integer array arr that can have duplicates.\nIn one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array.\nReturn the minimum number of operations needed to make target a subsequence of arr.\nA subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.\n\nExample 1:\nInput: target = [5,1,3], arr = [9,4,2,3,4]\nOutput: 2\nExplanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr.\n\nExample 2:\nInput: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1]\nOutput: 3\n\nConstraints:\n- 1 <= target.length, arr.length <= 10^5\n- 1 <= target[i], arr[i] <= 10^9\n- target contains no duplicates."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport bisect\n\n\nclass Solution(object):\n def minOperations(self, target, arr):\n \"\"\"\n :type target: List[int]\n :type arr: List[int]\n :rtype: int\n \"\"\"\n lookup = {x:i for i, x in enumerate(target)}\n lis = []\n for x in arr:\n if x not in lookup:\n continue\n i = bisect.bisect_left(lis, lookup[x])\n if i == len(lis):\n lis.append(lookup[x])\n else:\n lis[i] = lookup[x]\n return len(target)-len(lis)\n \n \n# Range Maximum Query\nclass SegmentTree(object): # 0-based index\n def __init__(self, N,\n build_fn=lambda x, y: [y]*(2*x),\n query_fn=lambda x, y: y if x is None else max(x, y), # (lambda x, y: y if x is None else min(x, y))\n update_fn=lambda x, y: y,\n default_val=0):\n self.N = N\n self.H = (N-1).bit_length()\n self.query_fn = query_fn\n self.update_fn = update_fn\n self.default_val = default_val\n self.tree = build_fn(N, default_val)\n self.lazy = [None]*N\n\n def __apply(self, x, val):\n self.tree[x] = self.update_fn(self.tree[x], val)\n if x < self.N:\n self.lazy[x] = self.update_fn(self.lazy[x], val)\n\n def update(self, L, R, h): # Time: O(logN), Space: O(N)\n def pull(x):\n while x > 1:\n x //= 2\n self.tree[x] = self.query_fn(self.tree[x*2], self.tree[x*2+1])\n if self.lazy[x] is not None:\n self.tree[x] = self.update_fn(self.tree[x], self.lazy[x])\n\n L += self.N\n R += self.N\n L0, R0 = L, R\n while L <= R:\n if L & 1: # is right child\n self.__apply(L, h) \n L += 1\n if R & 1 == 0: # is left child\n self.__apply(R, h)\n R -= 1\n L //= 2\n R //= 2\n pull(L0)\n pull(R0)\n\n def query(self, L, R): # Time: O(logN), Space: O(N)\n def push(x):\n n = 2**self.H\n while n != 1:\n y = x // n\n if self.lazy[y] is not None:\n self.__apply(y*2, self.lazy[y])\n self.__apply(y*2 + 1, self.lazy[y])\n self.lazy[y] = None\n n //= 2\n\n result = None\n if L > R:\n return result\n\n L += self.N\n R += self.N\n push(L)\n push(R)\n while L <= R:\n if L & 1: # is right child\n result = self.query_fn(result, self.tree[L])\n L += 1\n if R & 1 == 0: # is left child\n result = self.query_fn(result, self.tree[R])\n R -= 1\n L //= 2\n R //= 2\n return result\n \n def __str__(self):\n showList = []\n for i in range(self.N):\n showList.append(self.query(i, i))\n return \",\".join(map(str, showList))\n\n\n# Time: O(nlogn)\n# Space: O(n)\n# segment tree solution\nclass Solution2(object):\n def minOperations(self, target, arr):\n \"\"\"\n :type target: List[int]\n :type arr: List[int]\n :rtype: int\n \"\"\"\n lookup = {x:i for i, x in enumerate(target)}\n st = SegmentTree(len(lookup))\n for x in arr:\n if x not in lookup:\n continue\n st.update(lookup[x], lookup[x], st.query(0, lookup[x]-1)+1 if lookup[x] >= 1 else 1)\n return len(target)-(st.query(0, len(lookup)-1) if len(lookup) >= 1 else 0)\n"}} diff --git a/cp/cp-11091.jsonl b/cp/cp-11091.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f9d92cc6b27868f408dfc958846d7d9139cfcb63 --- /dev/null +++ b/cp/cp-11091.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11091", "name": "LeetCode 1716: Calculate Money In Leetcode Bank"} +{"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: Calculate Money in Leetcode Bank (Difficulty: Easy)\nTags: Math\n\nHercy wants to save money for his first car. He puts money in the Leetcode bank every day.\nHe starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday.\nGiven n, return the total amount of money he will have in the Leetcode bank at the end of the nth day.\n\nExample 1:\nInput: n = 4\nOutput: 10\nExplanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10.\n\nExample 2:\nInput: n = 10\nOutput: 37\nExplanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.\n\nExample 3:\nInput: n = 20\nOutput: 96\nExplanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.\n\nConstraints:\n- 1 <= n <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def totalMoney(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n def arithmetic_sequence_sum(a, d, n):\n return (2*a + (n-1)*d) * n //2\n\n cost, day = 1, 7\n first_week_cost = arithmetic_sequence_sum(cost, cost, day)\n week, remain_day = divmod(n, day)\n return arithmetic_sequence_sum(first_week_cost, cost*day, week) + \\\n arithmetic_sequence_sum(cost*(week+1), cost, remain_day)\n"}} diff --git a/cp/cp-11092.jsonl b/cp/cp-11092.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ab8a8dcd75323419a3c3b2fc2ff0a12abfb463f3 --- /dev/null +++ b/cp/cp-11092.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11092", "name": "LeetCode 1717: Maximum Score From Removing 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: Maximum Score From Removing Substrings (Difficulty: Medium)\nTags: String, Stack, Greedy\n\nYou are given a string s and two integers x and y. You can perform two types of operations any number of times.\nReturn the maximum points you can gain after applying the above operations on s.\n\nExample 1:\nInput: s = \"cdbcbbaaabab\", x = 4, y = 5\nOutput: 19\nExplanation:\n- Remove the \"ba\" underlined in \"cdbcbbaaabab\". Now, s = \"cdbcbbaaab\" and 5 points are added to the score.\n- Remove the \"ab\" underlined in \"cdbcbbaaab\". Now, s = \"cdbcbbaa\" and 4 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcbbaa\". Now, s = \"cdbcba\" and 5 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcba\". Now, s = \"cdbc\" and 5 points are added to the score.\nTotal score = 5 + 4 + 5 + 5 = 19.\n\nExample 2:\nInput: s = \"aabbaaxybbaabb\", x = 5, y = 4\nOutput: 20\n\nConstraints:\n- 1 <= s.length <= 10^5\n- 1 <= x, y <= 10^4\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 maximumGain(self, s, x, y):\n \"\"\"\n :type s: str\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n def score(s, a, x):\n i = result = 0\n for j in range(len(s)):\n s[i] = s[j]\n i += 1\n if i >= 2 and s[i-2:i] == a:\n i -= 2\n result += x\n s[:] = s[:i]\n return result\n \n s, a, b = list(s), list(\"ab\"), list(\"ba\")\n if x < y:\n x, y = y, x\n a, b = b, a\n return score(s, a, x) + score(s, b, y)\n"}} diff --git a/cp/cp-11093.jsonl b/cp/cp-11093.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ed2d5be5ddc93c77c1af904cf82c6b9808b652c3 --- /dev/null +++ b/cp/cp-11093.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11093", "name": "LeetCode 1718: Construct The Lexicographically Largest Valid Sequence"} +{"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 the Lexicographically Largest Valid Sequence (Difficulty: Medium)\nTags: Array, Backtracking\n\nGiven an integer n, find a sequence with elements in the range [1, n] that satisfies all of the following:\nThe distance between two numbers on the sequence, a[i] and a[j], is the absolute difference of their indices, |j - i|.\nReturn the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution.\nA sequence a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b. For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5.\n\nExample 1:\nInput: n = 3\nOutput: [3,1,2,3,2]\nExplanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.\n\nExample 2:\nInput: n = 5\nOutput: [5,3,1,4,3,5,2,4,2]\n\nConstraints:\n- 1 <= n <= 20"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n!)\n# Space: O(n)\n\nclass Solution(object):\n def constructDistancedSequence(self, n):\n \"\"\"\n :type n: int\n :rtype: List[int]\n \"\"\"\n def backtracking(n, i, result, lookup):\n if i == len(result):\n return True\n if result[i]:\n return backtracking(n, i+1, result, lookup)\n for x in reversed(range(1, n+1)):\n j = i if x == 1 else i+x\n if lookup[x] or j >= len(result) or result[j]:\n continue\n result[i], result[j], lookup[x] = x, x, True\n if backtracking(n, i+1, result, lookup):\n return True\n result[i], result[j], lookup[x] = 0, 0, False\n return False\n\n result, lookup = [0]*(2*n-1), [False]*(n+1)\n backtracking(n, 0, result, lookup)\n return result\n"}} diff --git a/cp/cp-11094.jsonl b/cp/cp-11094.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9c516f8b5b2256c37a24603138ef284bcc5f9953 --- /dev/null +++ b/cp/cp-11094.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11094", "name": "LeetCode 1719: Number Of Ways To Reconstruct A 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: Number Of Ways To Reconstruct A Tree (Difficulty: Hard)\nTags: Tree, Graph\n\nYou are given an array pairs, where pairs[i] = [xi, yi], and:\nLet ways be the number of rooted trees that satisfy the following conditions:\nTwo ways are considered to be different if there is at least one node that has different parents in both ways.\nReturn:\nA rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root.\nAn ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.\n\nExample 1:\nInput: pairs = [[1,2],[2,3]]\nOutput: 1\nExplanation: There is exactly one valid rooted tree, which is shown in the above figure.\n\nExample 2:\nInput: pairs = [[1,2],[2,3],[1,3]]\nOutput: 2\nExplanation: There are multiple valid rooted trees. Three of them are shown in the above figures.\n\nExample 3:\nInput: pairs = [[1,2],[2,3],[2,4],[1,5]]\nOutput: 0\nExplanation: There are no valid rooted trees.\n\nConstraints:\n- 1 <= pairs.length <= 10^5\n- 1 <= xi < yi <= 500\n- The elements in pairs are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def checkWays(self, pairs):\n \"\"\"\n :type pairs: List[List[int]]\n :rtype: int\n \"\"\"\n adj = collections.defaultdict(set)\n for x, y in pairs:\n adj[x].add(y)\n adj[y].add(x)\n n, mul = len(adj), False\n lookup = set()\n for node in sorted(adj.iterkeys(), key=lambda i: len(adj[i]), reverse=True):\n lookup.add(node)\n parent = 0\n for x in adj[node]:\n if x not in lookup:\n continue\n if parent == 0 or len(adj[x]) < len(adj[parent]):\n parent = x\n if parent:\n if any(True for x in adj[node] if x != parent and x not in adj[parent]):\n return 0\n mul |= len(adj[parent]) == len(adj[node])\n elif len(adj[node]) != n-1:\n return 0\n return 1 + mul\n"}} diff --git a/cp/cp-11095.jsonl b/cp/cp-11095.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e8c5502e7d2e933f6ab2de4d6033b594175ec157 --- /dev/null +++ b/cp/cp-11095.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11095", "name": "LeetCode 1720: Decode Xored 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: Decode XORed Array (Difficulty: Easy)\nTags: Array, Bit Manipulation\n\nThere is a hidden integer array arr that consists of n non-negative integers.\nIt was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3].\nYou are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0].\nReturn the original array arr. It can be proved that the answer exists and is unique.\n\nExample 1:\nInput: encoded = [1,2,3], first = 1\nOutput: [1,0,2,1]\nExplanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]\n\nExample 2:\nInput: encoded = [6,2,7,3], first = 4\nOutput: [4,2,0,7,4]\n\nConstraints:\n- 2 <= n <= 10^4\n- encoded.length == n - 1\n- 0 <= encoded[i] <= 10^5\n- 0 <= first <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def decode(self, encoded, first):\n \"\"\"\n :type encoded: List[int]\n :type first: int\n :rtype: List[int]\n \"\"\"\n result = [first]\n for x in encoded:\n result.append(result[-1]^x)\n return result\n"}} diff --git a/cp/cp-11096.jsonl b/cp/cp-11096.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e43004fcbc6a0cace8e7b48ef393ad51c2d433cd --- /dev/null +++ b/cp/cp-11096.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11096", "name": "LeetCode 1721: Swapping Nodes In A Linked List"} +{"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: Swapping Nodes in a Linked List (Difficulty: Medium)\nTags: Linked List, Two Pointers\n\nYou are given the head of a linked list, and an integer k.\nReturn the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).\n\nExample 1:\nInput: head = [1,2,3,4,5], k = 2\nOutput: [1,4,3,2,5]\n\nExample 2:\nInput: head = [7,9,6,6,7,8,3,0,9,5], k = 5\nOutput: [7,9,6,6,8,7,3,0,9,5]\n\nConstraints:\n- The number of nodes in the list is n.\n- 1 <= k <= n <= 10^5\n- 0 <= Node.val <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, val=0, next=None):\n pass\n\n\nclass Solution(object):\n def swapNodes(self, head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n left, right, curr = None, None, head\n while curr:\n k -= 1\n if right:\n right = right.next\n if k == 0:\n left = curr\n right = head\n curr = curr.next\n left.val, right.val = right.val, left.val\n return head\n"}} diff --git a/cp/cp-11097.jsonl b/cp/cp-11097.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4c09612e4376926d8ededb1d3452093c7f5ee5f8 --- /dev/null +++ b/cp/cp-11097.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11097", "name": "LeetCode 1722: Minimize Hamming Distance After Swap Operations"} +{"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: Minimize Hamming Distance After Swap Operations (Difficulty: Medium)\nTags: Array, Depth-First Search, Union Find\n\nYou are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order.\nThe Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed).\nReturn the minimum Hamming distance of source and target after performing any amount of swap operations on array source.\n\nExample 1:\nInput: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]\nOutput: 1\nExplanation: source can be transformed the following way:\n- Swap indices 0 and 1: source = [2,1,3,4]\n- Swap indices 2 and 3: source = [2,1,4,3]\nThe Hamming distance of source and target is 1 as they differ in 1 position: index 3.\n\nExample 2:\nInput: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []\nOutput: 2\nExplanation: There are no allowed swaps.\nThe Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.\n\nExample 3:\nInput: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]\nOutput: 0\n\nConstraints:\n- n == source.length == target.length\n- 1 <= n <= 10^5\n- 1 <= source[i], target[i] <= 10^5\n- 0 <= allowedSwaps.length <= 10^5\n- allowedSwaps[i].length == 2\n- 0 <= ai, bi <= n - 1\n- ai != bi"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def minimumHammingDistance(self, source, target, allowedSwaps):\n \"\"\"\n :type source: List[int]\n :type target: List[int]\n :type allowedSwaps: List[List[int]]\n :rtype: int\n \"\"\"\n def iter_flood_fill(adj, node, lookup, idxs):\n stk = [node]\n while stk:\n node = stk.pop()\n if node in lookup:\n continue\n lookup.add(node)\n idxs.append(node)\n for child in adj[node]:\n stk.append(child)\n\n adj = [set() for i in range(len(source))]\n for i, j in allowedSwaps:\n adj[i].add(j)\n adj[j].add(i)\n result = 0\n lookup = set()\n for i in range(len(source)):\n if i in lookup:\n continue\n idxs = []\n iter_flood_fill(adj, i, lookup, idxs)\n source_cnt = collections.Counter([source[i] for i in idxs])\n target_cnt = collections.Counter([target[i] for i in idxs])\n diff = source_cnt-target_cnt\n result += sum(diff.itervalues())\n return result\n\n\n# Time: O(n * α(n)) ~= O(n)\n# Space: O(n)\nimport collections\n\n\nclass UnionFind(object): # Time: O(n * α(n)), Space: O(n)\n def __init__(self, n):\n self.set = range(n)\n self.rank = [0]*n\n\n def find_set(self, x):\n stk = []\n while self.set[x] != x: # path compression\n stk.append(x)\n x = self.set[x]\n while stk:\n self.set[stk.pop()] = x\n return x\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n if self.rank[x_root] < self.rank[y_root]: # union by rank\n self.set[x_root] = y_root\n elif self.rank[x_root] > self.rank[y_root]:\n self.set[y_root] = x_root\n else:\n self.set[y_root] = x_root\n self.rank[x_root] += 1\n return True\n\n\nclass Solution2(object):\n def minimumHammingDistance(self, source, target, allowedSwaps):\n \"\"\"\n :type source: List[int]\n :type target: List[int]\n :type allowedSwaps: List[List[int]]\n :rtype: int\n \"\"\"\n uf = UnionFind(len(source))\n for x, y in allowedSwaps: \n uf.union_set(x, y)\n groups = collections.defaultdict(set)\n for i in range(len(source)):\n groups[uf.find_set(i)].add(i)\n result = 0\n for idxs in groups.itervalues():\n source_cnt = collections.Counter([source[i] for i in idxs])\n target_cnt = collections.Counter([target[i] for i in idxs])\n diff = source_cnt-target_cnt\n result += sum(diff.itervalues())\n return result\n"}} diff --git a/cp/cp-11098.jsonl b/cp/cp-11098.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..813d9a9c9ff30b0c6b1c7a53c525bfb2c19ea323 --- /dev/null +++ b/cp/cp-11098.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11098", "name": "LeetCode 1723: Find Minimum Time To Finish All Jobs"} +{"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 Minimum Time to Finish All Jobs (Difficulty: Hard)\nTags: Array, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask\n\nYou are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job.\nThere are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized.\nReturn the minimum possible maximum working time of any assignment.\n\nExample 1:\nInput: jobs = [3,2,3], k = 3\nOutput: 3\nExplanation: By assigning each person one job, the maximum time is 3.\n\nExample 2:\nInput: jobs = [1,2,4,7,8], k = 2\nOutput: 11\nExplanation: Assign the jobs the following way:\nWorker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\nWorker 2: 4, 7 (working time = 4 + 7 = 11)\nThe maximum working time is 11.\n\nConstraints:\n- 1 <= k <= jobs.length <= 12\n- 1 <= jobs[i] <= 10^7"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(k^n * logr), the real complexity shoud be much less, but hard to analyze\n# Space: O(n + k)\n\nclass Solution(object):\n def minimumTimeRequired(self, jobs, k):\n \"\"\"\n :type jobs: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n def backtracking(jobs, i, cap, counts):\n if i == len(jobs):\n return True\n for j in range(len(counts)):\n if counts[j]+jobs[i] <= cap:\n counts[j] += jobs[i]\n if backtracking(jobs, i+1, cap, counts):\n return True\n counts[j] -= jobs[i]\n if counts[j] == 0:\n break\n return False\n\n jobs.sort(reverse=True)\n left, right = max(jobs), sum(jobs)\n while left <= right:\n mid = left + (right-left)//2\n if backtracking(jobs, 0, mid, [0]*k):\n right = mid-1\n else:\n left = mid+1\n return left\n\n\n# Time: O(k * k^n), the real complexity shoud be less, but hard to analyze\n# Space: O(n + k)\nclass Solution2(object):\n def minimumTimeRequired(self, jobs, k):\n \"\"\"\n :type jobs: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n def backtracking(jobs, i, counts, result):\n if i == len(jobs):\n result[0] = min(result[0], max(counts))\n return\n for j in range(len(counts)):\n if counts[j]+jobs[i] <= result[0]:\n counts[j] += jobs[i]\n backtracking(jobs, i+1, counts, result)\n counts[j] -= jobs[i]\n if counts[j] == 0:\n break\n\n jobs.sort(reverse=False)\n result = [sum(jobs)]\n backtracking(jobs, 0, [0]*k, result)\n return result[0]\n"}} diff --git a/cp/cp-11100.jsonl b/cp/cp-11100.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..15ce5289879aaecf95ea42629c94715e5607134f --- /dev/null +++ b/cp/cp-11100.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11100", "name": "LeetCode 1725: Number Of Rectangles That Can Form The Largest Square"} +{"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 Rectangles That Can Form The Largest Square (Difficulty: Easy)\nTags: Array\n\nYou are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi.\nYou can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4.\nLet maxLen be the side length of the largest square you can obtain from any of the given rectangles.\nReturn the number of rectangles that can make a square with a side length of maxLen.\n\nExample 1:\nInput: rectangles = [[5,8],[3,9],[5,12],[16,5]]\r\nOutput: 3\r\nExplanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5].\r\nThe largest possible square is of length 5, and you can get it out of 3 rectangles.\n\nExample 2:\nInput: rectangles = [[2,3],[3,7],[4,3],[3,7]]\r\nOutput: 3\n\nConstraints:\n- 1 <= rectangles.length <= 1000\n- rectangles[i].length == 2\n- 1 <= li, wi <= 10^9\n- li != wi"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def countGoodRectangles(self, rectangles):\n \"\"\"\n :type rectangles: List[List[int]]\n :rtype: int\n \"\"\"\n result = mx = 0\n for l, w in rectangles:\n side = min(l, w)\n if side > mx:\n result, mx = 1, side\n elif side == mx:\n result += 1\n return result\n"}} diff --git a/cp/cp-11101.jsonl b/cp/cp-11101.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e8b1080fa062e5f2f9ebabe8b3580b417df27416 --- /dev/null +++ b/cp/cp-11101.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11101", "name": "LeetCode 1726: Tuple With Same Product"} +{"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: Tuple with Same Product (Difficulty: Medium)\nTags: Array, Hash Table, Counting\n\nGiven an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d.\n\nExample 1:\nInput: nums = [2,3,4,6]\nOutput: 8\nExplanation: There are 8 valid tuples:\n(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)\n(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)\n\nExample 2:\nInput: nums = [1,2,4,5,10]\nOutput: 16\nExplanation: There are 16 valid tuples:\n(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)\n(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)\n(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)\n(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)\n\nConstraints:\n- 1 <= nums.length <= 1000\n- 1 <= nums[i] <= 10^4\n- All elements in nums are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2)\n\nimport collections\n\n\nclass Solution(object):\n def tupleSameProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result = 0\n count = collections.Counter()\n for i in range(len(nums)):\n for j in range(i+1, len(nums)): \n result += count[nums[i]*nums[j]]\n count[nums[i]*nums[j]] += 1\n return 8*result\n"}} diff --git a/cp/cp-11102.jsonl b/cp/cp-11102.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2e602708f66cde5678c1b3400078f4dc60262efe --- /dev/null +++ b/cp/cp-11102.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11102", "name": "LeetCode 1727: Largest Submatrix With Rearrangements"} +{"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: Largest Submatrix With Rearrangements (Difficulty: Medium)\nTags: Array, Greedy, Sorting, Matrix\n\nYou are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order.\nReturn the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.\n\nExample 1:\nInput: matrix = [[0,0,1],[1,1,1],[1,0,1]]\nOutput: 4\nExplanation: You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 4.\n\nExample 2:\nInput: matrix = [[1,0,1,0,1]]\nOutput: 3\nExplanation: You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 3.\n\nExample 3:\nInput: matrix = [[1,1,0],[1,0,1]]\nOutput: 2\nExplanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.\n\nConstraints:\n- m == matrix.length\n- n == matrix[i].length\n- 1 <= m * n <= 10^5\n- matrix[i][j] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def largestSubmatrix(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: int\n \"\"\"\n for c in range(len(matrix[0])):\n h = 0\n for r in range(len(matrix)):\n h = h+1 if matrix[r][c] == 1 else 0\n matrix[r][c] = h\n result = 0\n for row in matrix:\n row.sort()\n for c in range(len(row)):\n result = max(result, (len(row)-c) * row[c])\n return result\n"}} diff --git a/cp/cp-11103.jsonl b/cp/cp-11103.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7023fbae220ad5694c0b57d52d4486d81c39f812 --- /dev/null +++ b/cp/cp-11103.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11103", "name": "LeetCode 1728: Cat And Mouse 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: Cat and Mouse II (Difficulty: Hard)\nTags: Array, Math, Dynamic Programming, Graph, Topological Sort, Memoization, Matrix, Game Theory\n\nA game is played by a cat and a mouse named Cat and Mouse.\nThe environment is represented by a grid of size rows x cols, where each element is a wall, floor, player (Cat, Mouse), or food.\nMouse and Cat play according to the following rules:\nThe game can end in 4 ways:\nGiven a rows x cols matrix grid and two integers catJump and mouseJump, return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false.\n\nExample 1:\nInput: grid = [\"####F\",\"#C...\",\"M....\"], catJump = 1, mouseJump = 2\nOutput: true\nExplanation: Cat cannot catch Mouse on its turn nor can it get the food before Mouse.\n\nExample 2:\nInput: grid = [\"M.C...F\"], catJump = 1, mouseJump = 4\nOutput: true\n\nExample 3:\nInput: grid = [\"M.C...F\"], catJump = 1, mouseJump = 3\nOutput: false\n\nConstraints:\n- rows == grid.length\n- cols = grid[i].length\n- 1 <= rows, cols <= 8\n- grid[i][j] consist only of characters 'C', 'M', 'F', '.', and '#'.\n- There is only one of each character 'C', 'M', and 'F' in grid.\n- 1 <= catJump, mouseJump <= 8"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((m * n)^2 * (m + n))\n# Space: O((m * n)^2)\n\nimport collections\n\n\nclass Solution(object):\n def canMouseWin(self, grid, catJump, mouseJump):\n \"\"\"\n :type grid: List[str]\n :type catJump: int\n :type mouseJump: int\n :rtype: bool\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n DRAW, MOUSE, CAT = range(3)\n def parents(m, c, t):\n if t == CAT:\n for nm in graph[m, MOUSE^CAT^t]:\n yield nm, c, MOUSE^CAT^t\n else:\n for nc in graph[c, MOUSE^CAT^t]:\n yield m, nc, MOUSE^CAT^t\n\n R, C = len(grid), len(grid[0])\n N = R*C\n WALLS = set()\n FOOD, MOUSE_START, CAT_START = [-1]*3\n for r in range(R):\n for c in range(C):\n if grid[r][c] == 'M':\n MOUSE_START = r*C + c\n elif grid[r][c] == 'C':\n CAT_START = r*C + c\n elif grid[r][c] == 'F':\n FOOD = r*C + c\n elif grid[r][c] == '#':\n WALLS.add(r*C + c)\n\n graph = collections.defaultdict(set)\n jump = {MOUSE:mouseJump, CAT:catJump}\n for r in range(R):\n for c in range(C):\n if grid[r][c] == '#':\n continue\n pos = r*C + c\n for t in [MOUSE, CAT]:\n for dr, dc in directions:\n for d in range(jump[t]+1):\n nr, nc = r+dr*d, c+dc*d\n if not (0 <= nr < R and 0 <= nc < C and grid[nr][nc] != '#'):\n break\n graph[pos, t].add(nr*C + nc)\n\n degree = {}\n for m in range(N):\n for c in range(N):\n degree[m, c, MOUSE] = len(graph[m, MOUSE])\n degree[m, c, CAT] = len(graph[c, CAT])\n color = collections.defaultdict(int)\n q = collections.deque()\n for i in range(N):\n if i in WALLS or i == FOOD:\n continue\n color[FOOD, i, CAT] = MOUSE\n q.append((FOOD, i, CAT, MOUSE))\n color[i, FOOD, MOUSE] = CAT\n q.append((i, FOOD, MOUSE, CAT))\n for t in [MOUSE, CAT]:\n color[i, i, t] = CAT\n q.append((i, i, t, CAT))\n while q:\n i, j, t, c = q.popleft()\n for ni, nj, nt in parents(i, j, t):\n if color[ni, nj, nt] != DRAW:\n continue\n if nt == c:\n color[ni, nj, nt] = c\n q.append((ni, nj, nt, c))\n continue\n degree[ni, nj, nt] -= 1\n if not degree[ni, nj, nt]:\n color[ni, nj, nt] = c\n q.append((ni, nj, nt, c))\n return color[MOUSE_START, CAT_START, MOUSE] == MOUSE\n\n\n# Time: O((m * n)^2 * (m + n))\n# Space: O((m * n)^2)\nimport collections\n\n\nclass Solution2(object):\n def canMouseWin(self, grid, catJump, mouseJump):\n \"\"\"\n :type grid: List[str]\n :type catJump: int\n :type mouseJump: int\n :rtype: bool\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n DRAW, MOUSE, CAT = range(3)\n def parents(m, c, t):\n if t == CAT:\n for nm in graph[m, MOUSE^CAT^t]:\n yield nm, c, MOUSE^CAT^t\n else:\n for nc in graph[c, MOUSE^CAT^t]:\n yield m, nc, MOUSE^CAT^t\n\n R, C = len(grid), len(grid[0])\n N = R*C\n WALLS = set()\n FOOD, MOUSE_START, CAT_START = [-1]*3\n for r in range(R):\n for c in range(C):\n if grid[r][c] == 'M':\n MOUSE_START = r*C + c\n elif grid[r][c] == 'C':\n CAT_START = r*C + c\n elif grid[r][c] == 'F':\n FOOD = r*C + c\n elif grid[r][c] == '#':\n WALLS.add(r*C + c)\n graph = collections.defaultdict(set)\n jump = {MOUSE:mouseJump, CAT:catJump}\n for r in range(R):\n for c in range(C):\n if grid[r][c] == '#':\n continue\n pos = r*C + c\n for t in [MOUSE, CAT]:\n for dr, dc in directions:\n for d in range(jump[t]+1):\n nr, nc = r+dr*d, c+dc*d\n if not (0 <= nr < R and 0 <= nc < C and grid[nr][nc] != '#'):\n break\n graph[pos, t].add(nr*C + nc)\n\n degree = {}\n for m in range(N):\n for c in range(N):\n # degree[m, c, MOUSE] = len(graph[m, MOUSE])\n degree[m, c, CAT] = len(graph[c, CAT])\n color = collections.defaultdict(int)\n q1 = collections.deque()\n # q2 = collections.deque()\n for i in range(N):\n if i in WALLS or i == FOOD:\n continue\n color[FOOD, i, CAT] = MOUSE\n q1.append((FOOD, i, CAT))\n color[i, FOOD, MOUSE] = CAT\n # q2.append((i, FOOD, MOUSE))\n for t in [MOUSE, CAT]:\n color[i, i, t] = CAT\n # q2.append((i, i, t))\n while q1:\n i, j, t = q1.popleft()\n for ni, nj, nt in parents(i, j, t):\n if color[ni, nj, nt] != DRAW:\n continue\n if t == CAT:\n color[ni, nj, nt] = MOUSE\n q1.append((ni, nj, nt))\n continue\n degree[ni, nj, nt] -= 1\n if not degree[ni, nj, nt]:\n color[ni, nj, nt] = MOUSE\n q1.append((ni, nj, nt))\n # while q2:\n # i, j, t = q2.popleft()\n # for ni, nj, nt in parents(i, j, t):\n # if color[ni, nj, nt] != DRAW:\n # continue\n # if t == MOUSE:\n # color[ni, nj, nt] = CAT\n # q2.append((ni, nj, nt))\n # continue\n # degree[ni, nj, nt] -= 1\n # if not degree[ni, nj, nt]:\n # color[ni, nj, nt] = CAT\n # q2.append((ni, nj, nt))\n return color[MOUSE_START, CAT_START, MOUSE] == MOUSE\n"}} diff --git a/cp/cp-11106.jsonl b/cp/cp-11106.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7f163acbfe3ded3f19ad8fecb88a64ff17d86377 --- /dev/null +++ b/cp/cp-11106.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11106", "name": "LeetCode 1733: Minimum Number Of People To Teach"} +{"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: Minimum Number of People to Teach (Difficulty: Medium)\nTags: Array, Hash Table, Greedy\n\nOn a social network consisting of m users and some friendships between users, two users can communicate with each other if they know a common language.\nYou are given an integer n, an array languages, and an array friendships where:\nYou can choose one language and teach it to some users so that all friends can communicate with each other. Return the minimum number of users you need to teach.\n\nExample 1:\nInput: n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]]\nOutput: 1\nExplanation: You can either teach user 1 the second language or user 2 the first language.\n\nExample 2:\nInput: n = 3, languages = [[2],[1,3],[1,2],[3]], friendships = [[1,4],[1,2],[3,4],[2,3]]\nOutput: 2\nExplanation: Teach the third language to users 1 and 3, yielding two users to teach.\n\nConstraints:\n- 2 <= n <= 500\n- languages.length == m\n- 1 <= m <= 500\n- 1 <= languages[i].length <= n\n- 1 <= languages[i][j] <= n\n- 1 <= u​​​​​​i < v​​​​​​i <= languages.length\n- 1 <= friendships.length <= 500\n- All tuples (u​​​​​i, v​​​​​​i) are unique\n- languages[i] contains only unique values"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * m^2)\n# Space: O(n * m)\n\nimport collections\n\n\nclass Solution(object):\n def minimumTeachings(self, n, languages, friendships):\n \"\"\"\n :type n: int\n :type languages: List[List[int]]\n :type friendships: List[List[int]]\n :rtype: int\n \"\"\"\n language_sets = map(set, languages) # Space: O(m * n)\n candidates = set(i-1 for u, v in friendships if not language_sets[u-1] & language_sets[v-1] for i in [u, v]) # Time: O(m^2 * n), Space: O(m)\n count = collections.Counter()\n for i in candidates: # Time: O(m * n)\n count += collections.Counter(languages[i])\n return len(candidates) - max(count.values() + [0])\n"}} diff --git a/cp/cp-11107.jsonl b/cp/cp-11107.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d6651e04e173173e20f4458d381d833770e9d699 --- /dev/null +++ b/cp/cp-11107.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11107", "name": "LeetCode 1734: Decode Xored Permutation"} +{"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 XORed Permutation (Difficulty: Medium)\nTags: Array, Bit Manipulation\n\nThere is an integer array perm that is a permutation of the first n positive integers, where n is always odd.\nIt was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1].\nGiven the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique.\n\nExample 1:\nInput: encoded = [3,1]\nOutput: [1,2,3]\nExplanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]\n\nExample 2:\nInput: encoded = [6,5,4,6]\nOutput: [2,4,1,5,3]\n\nConstraints:\n- 3 <= n < 10^5\n- n is odd.\n- encoded.length == n - 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def decode(self, encoded):\n \"\"\"\n :type encoded: List[int]\n :rtype: List[int]\n \"\"\"\n curr = 0\n for i in range(1, (len(encoded)+1) + 1):\n curr ^= i\n if i < len(encoded) and i%2 == 1:\n curr ^= encoded[i]\n result = [curr]\n for x in encoded:\n result.append(result[-1]^x)\n return result\n"}} diff --git a/cp/cp-11108.jsonl b/cp/cp-11108.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..69d9054a05ef055bf7e1e72a6998401daa283028 --- /dev/null +++ b/cp/cp-11108.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11108", "name": "LeetCode 1735: Count Ways To Make Array With Product"} +{"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: Count Ways to Make Array With Product (Difficulty: Hard)\nTags: Array, Math, Dynamic Programming, Combinatorics, Number Theory\n\nYou are given a 2D integer array, queries. For each queries[i], where queries[i] = [ni, ki], find the number of different ways you can place positive integers into an array of size ni such that the product of the integers is ki. As the number of ways may be too large, the answer to the ith query is the number of ways modulo 109 + 7.\nReturn an integer array answer where answer.length == queries.length, and answer[i] is the answer to the ith query.\n\nExample 1:\nInput: queries = [[2,6],[5,1],[73,660]]\nOutput: [4,1,50734910]\nExplanation: Each query is independent.\n[2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].\n[5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].\n[73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910.\n\nExample 2:\nInput: queries = [[1,1],[2,2],[3,3],[4,4],[5,5]]\nOutput: [1,2,3,10,5]\n\nConstraints:\n- 1 <= queries.length <= 10^4\n- 1 <= ni, ki <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(sqrt(m) + n + q * (logm + pi(sqrt(m)))) = O(sqrt(m) + n + q * (logm + sqrt(m)/log(sqrt(m)))), m is max(k for _, k in queries), pi(n) = number of primes in a range [1, n] = O(n/logn) by prime number theorem, see https://en.wikipedia.org/wiki/Prime_number_theorem\n# Space: O(sqrt(m) + n + logm)\n\nimport collections\n\n\nclass Solution(object):\n def waysToFillArray(self, queries):\n \"\"\"\n :type queries: List[List[int]]\n :rtype: List[int]\n \"\"\"\n MOD = 10**9+7\n fact, inv, inv_fact = [[1]*2 for _ in range(3)]\n def nCr(n, k):\n while len(inv) <= n: # lazy initialization\n fact.append(fact[-1]*len(inv) % MOD)\n inv.append(inv[MOD%len(inv)]*(MOD-MOD//len(inv)) % MOD) # https://cp-algorithms.com/algebra/module-inverse.html\n inv_fact.append(inv_fact[-1]*inv[-1] % MOD)\n return (fact[n]*inv_fact[n-k] % MOD) * inv_fact[k] % MOD\n\n def linear_sieve_of_eratosthenes(n): # Time: O(n), Space: O(n)\n primes = []\n spf = [-1]*(n+1) # the smallest prime factor\n for i in range(2, n+1):\n if spf[i] == -1:\n spf[i] = i\n primes.append(i)\n for p in primes:\n if i*p > n or p > spf[i]:\n break\n spf[i*p] = p\n return primes\n\n def prime_factors(x):\n factors = collections.Counter()\n for p in primes:\n if p*p > x:\n break\n while x%p == 0:\n factors[p] += 1\n x //= p\n if x != 1:\n factors[x] += 1\n return factors\n\n primes = linear_sieve_of_eratosthenes(int(max(k for _, k in queries)**0.5))\n result = []\n for n, k in queries:\n total = 1\n for c in prime_factors(k).itervalues():\n total *= nCr(n+c-1, c) # H(n, c) = nCr(n+c-1, n)\n result.append(total % MOD)\n return result\n"}} diff --git a/cp/cp-11109.jsonl b/cp/cp-11109.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9277d5f59c6217e11e677497a53dd7d3a7467238 --- /dev/null +++ b/cp/cp-11109.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11109", "name": "LeetCode 1736: Latest Time By Replacing Hidden Digits"} +{"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: Latest Time by Replacing Hidden Digits (Difficulty: Easy)\nTags: String, Greedy\n\nYou are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?).\nThe valid times are those inclusively between 00:00 and 23:59.\nReturn the latest valid time you can get from time by replacing the hidden digits.\n\nExample 1:\nInput: time = \"2?:?0\"\nOutput: \"23:50\"\nExplanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.\n\nExample 2:\nInput: time = \"0?:3?\"\nOutput: \"09:39\"\n\nExample 3:\nInput: time = \"1?:22\"\nOutput: \"19:22\"\n\nConstraints:\n- time is in the format hh:mm.\n- It is guaranteed that you can produce a valid time from the given string."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def maximumTime(self, time):\n \"\"\"\n :type time: str\n :rtype: str\n \"\"\"\n result = list(time)\n for i, c in enumerate(time): \n if c != \"?\":\n continue\n if i == 0:\n result[i] = '2' if result[i+1] in \"?0123\" else '1'\n elif i == 1:\n result[i] = '3' if result[0] == '2' else '9'\n elif i == 3:\n result[i] = '5'\n elif i == 4:\n result[i] = '9'\n return \"\".join(result)\n"}} diff --git a/cp/cp-11110.jsonl b/cp/cp-11110.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6bebed02fa04a96a0a6c8858dc9c1a19d31b8cf7 --- /dev/null +++ b/cp/cp-11110.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11110", "name": "LeetCode 1737: Change Minimum Characters To Satisfy One Of Three Conditions"} +{"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: Change Minimum Characters to Satisfy One of Three Conditions (Difficulty: Medium)\nTags: Hash Table, String, Counting, Prefix Sum\n\nYou are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter.\nYour goal is to satisfy one of the following three conditions:\nReturn the minimum number of operations needed to achieve your goal.\n\nExample 1:\nInput: a = \"aba\", b = \"caa\"\nOutput: 2\nExplanation: Consider the best way to make each condition true:\n1) Change b to \"ccc\" in 2 operations, then every letter in a is less than every letter in b.\n2) Change a to \"bbb\" and b to \"aaa\" in 3 operations, then every letter in b is less than every letter in a.\n3) Change a to \"aaa\" and b to \"aaa\" in 2 operations, then a and b consist of one distinct letter.\nThe best way was done in 2 operations (either condition 1 or condition 3).\n\nExample 2:\nInput: a = \"dabadd\", b = \"cda\"\nOutput: 3\nExplanation: The best way is to make condition 1 true by changing b to \"eee\".\n\nConstraints:\n- 1 <= a.length, b.length <= 10^5\n- a and b consist only of lowercase letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def minCharacters(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: int\n \"\"\"\n count1 = collections.Counter(ord(c)-ord('a') for c in a)\n count2 = collections.Counter(ord(c)-ord('a') for c in b)\n result = len(a) + len(b) - max((count1+count2).itervalues()) # condition 3\n for i in range(26-1):\n if i > 0:\n count1[i] += count1[i-1]\n count2[i] += count2[i-1]\n result = min(result, len(a) - count1[i] + count2[i]) # condition 1\n result = min(result, len(b) - count2[i] + count1[i]) # condition 2\n return result\n"}} diff --git a/cp/cp-11111.jsonl b/cp/cp-11111.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d971da0e433937b138621f03807b85fa26adf67f --- /dev/null +++ b/cp/cp-11111.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11111", "name": "LeetCode 1738: Find Kth Largest Xor Coordinate Value"} +{"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 Kth Largest XOR Coordinate Value (Difficulty: Medium)\nTags: Array, Divide and Conquer, Bit Manipulation, Sorting, Heap (Priority Queue), Matrix, Prefix Sum, Quickselect\n\nYou are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k.\nThe value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed).\nFind the kth largest value (1-indexed) of all the coordinates of matrix.\n\nExample 1:\nInput: matrix = [[5,2],[1,6]], k = 1\nOutput: 7\nExplanation: The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.\n\nExample 2:\nInput: matrix = [[5,2],[1,6]], k = 2\nOutput: 5\nExplanation: The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.\n\nExample 3:\nInput: matrix = [[5,2],[1,6]], k = 3\nOutput: 4\nExplanation: The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.\n\nConstraints:\n- m == matrix.length\n- n == matrix[i].length\n- 1 <= m, n <= 1000\n- 0 <= matrix[i][j] <= 10^6\n- 1 <= k <= m * n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n) on average\n# Space: O(m * n)\n\nimport random\n\n\nclass Solution(object):\n def kthLargestValue(self, matrix, k):\n \"\"\"\n :type matrix: List[List[int]]\n :type k: int\n :rtype: int\n \"\"\"\n def nth_element(nums, n, compare=lambda a, b: a < b):\n def tri_partition(nums, left, right, target, compare):\n mid = left\n while mid <= right:\n if nums[mid] == target:\n mid += 1\n elif compare(nums[mid], target):\n nums[left], nums[mid] = nums[mid], nums[left]\n left += 1\n mid += 1\n else:\n nums[mid], nums[right] = nums[right], nums[mid]\n right -= 1\n return left, right\n\n left, right = 0, len(nums)-1\n while left <= right:\n pivot_idx = random.randint(left, right)\n pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)\n if pivot_left <= n <= pivot_right:\n return\n elif pivot_left > n:\n right = pivot_left-1\n else: # pivot_right < n.\n left = pivot_right+1\n \n \n vals = []\n for r in range(len(matrix)):\n curr = 0\n for c in range(len(matrix[0])):\n curr = curr^matrix[r][c]\n if r == 0:\n matrix[r][c] = curr\n else:\n matrix[r][c] = curr^matrix[r-1][c]\n vals.append(matrix[r][c])\n nth_element(vals, k-1, compare=lambda a, b: a > b)\n return vals[k-1]\n"}} diff --git a/cp/cp-11112.jsonl b/cp/cp-11112.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1cbf8dd69545a3eb2d8e153fa251d03b12daa613 --- /dev/null +++ b/cp/cp-11112.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11112", "name": "LeetCode 1739: Building Boxes"} +{"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: Building Boxes (Difficulty: Hard)\nTags: Math, Binary Search, Greedy\n\nYou have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:\nGiven an integer n, return the minimum possible number of boxes touching the floor.\n\nExample 1:\nInput: n = 3\nOutput: 3\nExplanation: The figure above is for the placement of the three boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.\n\nExample 2:\nInput: n = 4\nOutput: 3\nExplanation: The figure above is for the placement of the four boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.\n\nExample 3:\nInput: n = 10\nOutput: 6\nExplanation: The figure above is for the placement of the ten boxes.\nThese boxes are placed in the corner of the room, where the corner is on the back side.\n\nConstraints:\n- 1 <= n <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nimport math\n\n\nclass Solution(object):\n def minimumBoxes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n # find max h s.t. sum(k*(k+1)//2 for k in range(1, h+1)) <= n\n # => find max h s.t. h*(h+1)*(h+2)//6 <= n\n h = int((6*n)**(1.0/3)) \n if h*(h+1)*(h+2) > 6*n:\n # (h-1)*h*(h+1) < h^3 <= 6n < h*(h+1)*(h+2) < (h+1)^3\n h -= 1\n n -= h*(h+1)*(h+2)//6\n d = int(math.ceil((-1+(1+8*n)**0.5)/2)) # find min d s.t. d*(d+1)//2 >= n\n return h*(h+1)//2 + d\n"}} diff --git a/cp/cp-11114.jsonl b/cp/cp-11114.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ade95056afb96093854b46ed0d9343efa9e21ec6 --- /dev/null +++ b/cp/cp-11114.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11114", "name": "LeetCode 1742: Maximum Number Of Balls In A Box"} +{"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 Number of Balls in a Box (Difficulty: Easy)\nTags: Hash Table, Math, Counting\n\nYou are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity.\nYour job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1.\nGiven two integers lowLimit and highLimit, return the number of balls in the box with the most balls.\n\nExample 1:\nInput: lowLimit = 1, highLimit = 10\nOutput: 2\nExplanation:\nBox Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 2 1 1 1 1 1 1 1 1 0 0 ...\nBox 1 has the most number of balls with 2 balls.\n\nExample 2:\nInput: lowLimit = 5, highLimit = 15\nOutput: 2\nExplanation:\nBox Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 1 1 1 1 2 2 1 1 1 0 0 ...\nBoxes 5 and 6 have the most number of balls with 2 balls in each.\n\nExample 3:\nInput: lowLimit = 19, highLimit = 28\nOutput: 2\nExplanation:\nBox Number: 1 2 3 4 5 6 7 8 9 10 11 12 ...\nBall Count: 0 1 1 1 1 1 1 1 1 2 0 0 ...\nBox 10 has the most number of balls with 2 balls.\n\nConstraints:\n- 1 <= lowLimit <= highLimit <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogm)\n# Space: O(logm)\n\nimport collections\nimport itertools\n\n\nclass Solution(object):\n def countBalls(self, lowLimit, highLimit):\n \"\"\"\n :type lowLimit: int\n :type highLimit: int\n :rtype: int\n \"\"\"\n count = collections.Counter()\n for i in range(lowLimit, highLimit+1):\n count[sum(itertools.imap(int, str(i)))] += 1\n return max(count.itervalues())\n"}} diff --git a/cp/cp-11115.jsonl b/cp/cp-11115.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..26594331e051feb9b4fc05fe3d44f6046ff139d9 --- /dev/null +++ b/cp/cp-11115.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11115", "name": "LeetCode 1743: Restore The Array From Adjacent 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: Restore the Array From Adjacent Pairs (Difficulty: Medium)\nTags: Array, Hash Table, Depth-First Search\n\nThere is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums.\nYou are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums.\nIt is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order.\nReturn the original array nums. If there are multiple solutions, return any of them.\n\nExample 1:\nInput: adjacentPairs = [[2,1],[3,4],[3,2]]\nOutput: [1,2,3,4]\nExplanation: This array has all its adjacent pairs in adjacentPairs.\nNotice that adjacentPairs[i] may not be in left-to-right order.\n\nExample 2:\nInput: adjacentPairs = [[4,-2],[1,4],[-3,1]]\nOutput: [-2,4,1,-3]\nExplanation: There can be negative numbers.\nAnother solution is [-3,1,4,-2], which would also be accepted.\n\nExample 3:\nInput: adjacentPairs = [[100000,-100000]]\nOutput: [100000,-100000]\n\nConstraints:\n- nums.length == n\n- adjacentPairs.length == n - 1\n- adjacentPairs[i].length == 2\n- 2 <= n <= 10^5\n- -10^5 <= nums[i], ui, vi <= 10^5\n- There exists some nums that has adjacentPairs as its pairs."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def restoreArray(self, adjacentPairs):\n \"\"\"\n :type adjacentPairs: List[List[int]]\n :rtype: List[int]\n \"\"\"\n adj = collections.defaultdict(list)\n for u, v in adjacentPairs: \n adj[u].append(v)\n adj[v].append(u)\n result = next([x, adj[x][0]] for x in adj if len(adj[x]) == 1)\n while len(result) != len(adjacentPairs)+1:\n result.append(adj[result[-1]][adj[result[-1]][0] == result[-2]])\n return result\n"}} diff --git a/cp/cp-11116.jsonl b/cp/cp-11116.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cf9c64901a73a5f3811a8a969171146722b08daa --- /dev/null +++ b/cp/cp-11116.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11116", "name": "LeetCode 1744: Can You Eat Your Favorite Candy On Your Favorite Day"} +{"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 You Eat Your Favorite Candy on Your Favorite Day? (Difficulty: Medium)\nTags: Array, Prefix Sum\n\nYou are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] represents the number of candies of the ith type you have. You are also given a 2D array queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi].\nYou play a game with the following rules:\nConstruct a boolean array answer such that answer.length == queries.length and answer[i] is true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more than dailyCapi candies on any day, and false otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2.\nReturn the constructed array answer.\n\nExample 1:\nInput: candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]]\nOutput: [true,false,true]\nExplanation:\n1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2.\n2- You can eat at most 4 candies each day.\n If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1.\n On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2.\n3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13.\n\nExample 2:\nInput: candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]]\nOutput: [false,true,true,false,false]\n\nConstraints:\n- 1 <= candiesCount.length <= 10^5\n- 1 <= candiesCount[i] <= 10^5\n- 1 <= queries.length <= 10^5\n- queries[i].length == 3\n- 0 <= favoriteTypei < candiesCount.length\n- 0 <= favoriteDayi <= 10^9\n- 1 <= dailyCapi <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def canEat(self, candiesCount, queries):\n \"\"\"\n :type candiesCount: List[int]\n :type queries: List[List[int]]\n :rtype: List[bool]\n \"\"\"\n prefix = [0]*(len(candiesCount)+1)\n for i, c in enumerate(candiesCount):\n prefix[i+1] = prefix[i]+c\n return [prefix[t]//c < d+1 <= prefix[t+1]//1 for t, d, c in queries]\n"}} diff --git a/cp/cp-11117.jsonl b/cp/cp-11117.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..33d957fde7d978b1bcee219d0edf25f9ac659d02 --- /dev/null +++ b/cp/cp-11117.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11117", "name": "LeetCode 1745: Palindrome Partitioning Iv"} +{"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: Palindrome Partitioning IV (Difficulty: Hard)\nTags: String, Dynamic Programming\n\nGiven a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.​​​​​\nA string is said to be palindrome if it the same string when reversed.\n\nExample 1:\nInput: s = \"abcbdd\"\nOutput: true\nExplanation: \"abcbdd\" = \"a\" + \"bcb\" + \"dd\", and all three substrings are palindromes.\n\nExample 2:\nInput: s = \"bcbddxy\"\nOutput: false\nExplanation: s cannot be split into 3 palindromes.\n\nConstraints:\n- 3 <= s.length <= 2000\n- s​​​​​​ consists only of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def checkPartitioning(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\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\n P = manacher(s)\n prefix, suffix = [], []\n for i in range(2, len(P)-2):\n if i-1-P[i] == 0:\n prefix.append(i)\n if i+1+P[i] == len(P)-1:\n suffix.append(i)\n for i in prefix:\n for j in suffix:\n left, right = i+1+P[i], j-1-P[j]\n if left > right:\n continue\n mid = left + (right-left)//2\n if P[mid] >= mid-left:\n return True\n return False\n\n\n# Time: O(n^2)\n# Space: O(n^2)\nclass Solution2(object):\n def checkPartitioning(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\" \n dp = [[False]*len(s) for _ in range(len(s))]\n for i in reversed(range(len(s))):\n for j in range(i, len(s)):\n if s[i] == s[j] and (j-i < 2 or dp[i+1][j-1]):\n dp[i][j] = True\n for i in range(1, len(s)-1):\n if not dp[0][i-1]:\n continue\n for j in range(i+1, len(s)):\n if not dp[j][-1]:\n continue\n if dp[i][j-1]:\n return True\n return False\n"}} diff --git a/cp/cp-11120.jsonl b/cp/cp-11120.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3cc7ce43bc185fe38e3cd78d3aa642025a00bf03 --- /dev/null +++ b/cp/cp-11120.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11120", "name": "LeetCode 1749: Maximum Absolute Sum Of Any Subarray"} +{"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 Absolute Sum of Any Subarray (Difficulty: Medium)\nTags: Array, Dynamic Programming\n\nYou are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr).\nReturn the maximum absolute sum of any (possibly empty) subarray of nums.\nNote that abs(x) is defined as follows:\n\nExample 1:\nInput: nums = [1,-3,2,3,-4]\nOutput: 5\nExplanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.\n\nExample 2:\nInput: nums = [2,-5,1,-4,3,-2]\nOutput: 8\nExplanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.\n\nConstraints:\n- 1 <= nums.length <= 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 maxAbsoluteSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n curr = mx = mn = 0\n for num in nums:\n curr += num\n mx = max(mx, curr)\n mn = min(mn, curr)\n return mx-mn\n"}} diff --git a/cp/cp-11121.jsonl b/cp/cp-11121.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d9d69e2380ff87fd9dc7c33e549ea8454705fbbe --- /dev/null +++ b/cp/cp-11121.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11121", "name": "LeetCode 1750: Minimum Length Of String After Deleting Similar Ends"} +{"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: Minimum Length of String After Deleting Similar Ends (Difficulty: Medium)\nTags: Two Pointers, String\n\nGiven a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:\nReturn the minimum length of s after performing the above operation any number of times (possibly zero times).\n\nExample 1:\nInput: s = \"ca\"\nOutput: 2\nExplanation: You can't remove any characters, so the string stays as is.\n\nExample 2:\nInput: s = \"cabaabac\"\nOutput: 0\nExplanation: An optimal sequence of operations is:\n- Take prefix = \"c\" and suffix = \"c\" and remove them, s = \"abaaba\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"baab\".\n- Take prefix = \"b\" and suffix = \"b\" and remove them, s = \"aa\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"\".\n\nExample 3:\nInput: s = \"aabccabba\"\nOutput: 3\nExplanation: An optimal sequence of operations is:\n- Take prefix = \"aa\" and suffix = \"a\" and remove them, s = \"bccabb\".\n- Take prefix = \"b\" and suffix = \"bb\" and remove them, s = \"cca\".\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s only consists of characters 'a', 'b', and 'c'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minimumLength(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n left, right = 0, len(s)-1\n while left < right:\n if s[left] != s[right]:\n break\n c = s[left]\n while left <= right:\n if s[left] != c:\n break\n left += 1\n while left <= right:\n if s[right] != c:\n break\n right -= 1\n return right-left+1\n"}} diff --git a/cp/cp-11122.jsonl b/cp/cp-11122.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1ecbe7e726244c6b912e49c7696f1c7ab92e0642 --- /dev/null +++ b/cp/cp-11122.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11122", "name": "LeetCode 1751: Maximum Number Of Events That Can Be Attended 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: Maximum Number of Events That Can Be Attended II (Difficulty: Hard)\nTags: Array, Binary Search, Dynamic Programming, Sorting\n\nYou are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend.\nYou can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.\nReturn the maximum sum of values that you can receive by attending events.\n\nExample 1:\nInput: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2\nOutput: 7\nExplanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.\n\nExample 2:\nInput: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2\nOutput: 10\nExplanation: Choose event 2 for a total value of 10.\nNotice that you cannot attend any other event as they overlap, and that you do not have to attend k events.\n\nExample 3:\nInput: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3\nOutput: 9\nExplanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.\n\nConstraints:\n- 1 <= k <= events.length\n- 1 <= k * events.length <= 10^6\n- 1 <= startDayi <= endDayi <= 10^9\n- 1 <= valuei <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn + n * k)\n# Space: O(n * k)\n\nimport bisect\n\n\nclass Solution(object):\n def maxValue(self, events, k):\n \"\"\"\n :type events: List[List[int]]\n :type k: int\n :rtype: int\n \"\"\"\n events.sort(key=lambda x: x[1])\n sorted_ends = [x[1] for x in events]\n dp = [[0]*(k+1) for _ in range(len(events)+1)]\n for i in range(1, len(events)+1):\n prev_i_m_1 = bisect.bisect_left(sorted_ends, events[i-1][0])-1\n for j in range(1, k+1):\n dp[i][j] = max(dp[i-1][j], dp[prev_i_m_1+1][j-1]+events[i-1][2])\n return dp[-1][-1]\n\n\n# Time: O(nlogn + n * k)\n# Space: O(n * k)\nimport bisect\n\n\nclass Solution2(object):\n def maxValue(self, events, k):\n \"\"\"\n :type events: List[List[int]]\n :type k: int\n :rtype: int\n \"\"\"\n events.sort()\n sorted_starts = [x[0] for x in events]\n dp = [[0]*(k+1) for _ in range(len(events)+1)]\n for i in reversed(range(len(events))):\n next_i = bisect.bisect_right(sorted_starts, events[i][1])-1\n for j in range(1, k+1):\n dp[i][j] = max(dp[i+1][j], dp[next_i+1][j-1]+events[i][2])\n return dp[0][-1]\n"}} diff --git a/cp/cp-11123.jsonl b/cp/cp-11123.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..84f418ee990ebe62f92cec5db21668f018beee21 --- /dev/null +++ b/cp/cp-11123.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11123", "name": "LeetCode 1752: Check If Array Is Sorted And Rotated"} +{"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: Check if Array Is Sorted and Rotated (Difficulty: Easy)\nTags: Array\n\nGiven an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.\nThere may be duplicates in the original array.\nNote: An array A rotated by x positions results in an array B of the same length such that B[i] == A[(i+x) % A.length] for every valid index i.\n\nExample 1:\nInput: nums = [3,4,5,1,2]\nOutput: true\nExplanation: [1,2,3,4,5] is the original sorted array.\nYou can rotate the array by x = 3 positions to begin on the element of value 3: [3,4,5,1,2].\n\nExample 2:\nInput: nums = [2,1,3,4]\nOutput: false\nExplanation: There is no sorted array once rotated that can make nums.\n\nExample 3:\nInput: nums = [1,2,3]\nOutput: true\nExplanation: [1,2,3] is the original sorted array.\nYou can rotate the array by x = 0 positions (i.e. no rotation) to make nums.\n\nConstraints:\n- 1 <= nums.length <= 100\n- 1 <= nums[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def check(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n count = 0\n for i in range(len(nums)):\n if nums[i] > nums[(i+1)%len(nums)]:\n count += 1\n if count > 1:\n return False\n return True\n"}} diff --git a/cp/cp-11124.jsonl b/cp/cp-11124.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..df47b293f8f544a5c05abe0d6da1a29081c2695f --- /dev/null +++ b/cp/cp-11124.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11124", "name": "LeetCode 1753: Maximum Score From Removing Stones"} +{"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 Score From Removing Stones (Difficulty: Medium)\nTags: Math, Greedy, Heap (Priority Queue)\n\nYou are playing a solitaire game with three piles of stones of sizes a​​​​​​, b,​​​​​​ and c​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves).\nGiven three integers a​​​​​, b,​​​​​ and c​​​​​, return the maximum score you can get.\n\nExample 1:\nInput: a = 2, b = 4, c = 6\nOutput: 6\nExplanation: The starting state is (2, 4, 6). One optimal set of moves is:\n- Take from 1st and 3rd piles, state is now (1, 4, 5)\n- Take from 1st and 3rd piles, state is now (0, 4, 4)\n- Take from 2nd and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 6 points.\n\nExample 2:\nInput: a = 4, b = 4, c = 6\nOutput: 7\nExplanation: The starting state is (4, 4, 6). One optimal set of moves is:\n- Take from 1st and 2nd piles, state is now (3, 3, 6)\n- Take from 1st and 3rd piles, state is now (2, 3, 5)\n- Take from 1st and 3rd piles, state is now (1, 3, 4)\n- Take from 1st and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 7 points.\n\nExample 3:\nInput: a = 1, b = 8, c = 8\nOutput: 8\nExplanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.\nAfter that, there are fewer than two non-empty piles, so the game ends.\n\nConstraints:\n- 1 <= a, b, c <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def maximumScore(self, a, b, c):\n \"\"\"\n :type a: int\n :type b: int\n :type c: int\n :rtype: int\n \"\"\"\n # assumed c is the max size\n # case1: a+b > c\n # => (a+b-c)//2 + c = (a+b+c)//2 < a+b\n # case2: a+b <= c\n # => a+b <= (a+b+c)//2\n return min((a+b+c)//2, a+b+c - max(a, b, c))\n"}} diff --git a/cp/cp-11125.jsonl b/cp/cp-11125.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1e302b76d7b13994fbaa7bd92f1c93aa06e5c612 --- /dev/null +++ b/cp/cp-11125.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11125", "name": "LeetCode 1754: Largest Merge Of Two Strings"} +{"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: Largest Merge Of Two Strings (Difficulty: Medium)\nTags: Two Pointers, String, Greedy\n\nYou are given two strings word1 and word2. You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options:\nReturn the lexicographically largest merge you can construct.\nA string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, \"abcd\" is lexicographically larger than \"abcc\" because the first position they differ is at the fourth character, and d is greater than c.\n\nExample 1:\nInput: word1 = \"cabaa\", word2 = \"bcaaa\"\nOutput: \"cbcabaaaaa\"\nExplanation: One way to get the lexicographically largest merge is:\n- Take from word1: merge = \"c\", word1 = \"abaa\", word2 = \"bcaaa\"\n- Take from word2: merge = \"cb\", word1 = \"abaa\", word2 = \"caaa\"\n- Take from word2: merge = \"cbc\", word1 = \"abaa\", word2 = \"aaa\"\n- Take from word1: merge = \"cbca\", word1 = \"baa\", word2 = \"aaa\"\n- Take from word1: merge = \"cbcab\", word1 = \"aa\", word2 = \"aaa\"\n- Append the remaining 5 a's from word1 and word2 at the end of merge.\n\nExample 2:\nInput: word1 = \"abcabc\", word2 = \"abdcaba\"\nOutput: \"abdcabcabcaba\"\n\nConstraints:\n- 1 <= word1.length, word2.length <= 3000\n- word1 and word2 consist only of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * m)\n# Space: O(n + m)\n\nimport collections\n\n\nclass Solution(object):\n def largestMerge(self, word1, word2):\n \"\"\"\n :type word1: str\n :type word2: str\n :rtype: str\n \"\"\"\n q1 = collections.deque(word1)\n q2 = collections.deque(word2)\n result = []\n while q1 or q2:\n if q1 > q2:\n result.append(q1.popleft())\n else:\n result.append(q2.popleft())\n return \"\".join(result)\n"}} diff --git a/cp/cp-11126.jsonl b/cp/cp-11126.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..88a6b506eabafb4a303c82980dc6e9a4ababbd41 --- /dev/null +++ b/cp/cp-11126.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11126", "name": "LeetCode 1755: Closest Subsequence Sum"} +{"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: Closest Subsequence Sum (Difficulty: Hard)\nTags: Array, Two Pointers, Dynamic Programming, Bit Manipulation, Sorting, Bitmask\n\nYou are given an integer array nums and an integer goal.\nYou want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal).\nReturn the minimum possible value of abs(sum - goal).\nNote that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.\n\nExample 1:\nInput: nums = [5,-7,3,5], goal = 6\nOutput: 0\nExplanation: Choose the whole array as a subsequence, with a sum of 6.\nThis is equal to the goal, so the absolute difference is 0.\n\nExample 2:\nInput: nums = [7,-9,15,-2], goal = -5\nOutput: 1\nExplanation: Choose the subsequence [7,-9,-2], with a sum of -4.\nThe absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.\n\nExample 3:\nInput: nums = [1,2,3], goal = -7\nOutput: 7\n\nConstraints:\n- 1 <= nums.length <= 40\n- -107 <= nums[i] <= 10^7\n- -10^9 <= goal <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * 2^(n/2))\n# Space: O(2^(n/2))\n\nimport bisect\n\n\nclass Solution(object):\n def minAbsDifference(self, nums, goal):\n \"\"\"\n :type nums: List[int]\n :type goal: int\n :rtype: int\n \"\"\"\n mx, mn = sum(x for x in nums if x > 0), sum(x for x in nums if x < 0)\n if goal > mx:\n return goal-mx\n if goal < mn:\n return mn-goal\n result = abs(goal)\n sums1 = set([0])\n for i in range(len(nums)//2):\n for x in list(sums1):\n if x+nums[i] in sums1:\n continue\n sums1.add(x+nums[i])\n result = min(result, abs(goal-x-nums[i])) # case of right half part is 0\n sorted_sums1 = sorted(sums1) # Time: O((n/2) * 2^(n/2)) = O(n * 2^(n/2)), Space: O(2^(n/2))\n sums2 = set([0])\n for i in range(len(nums)//2, len(nums)):\n for x in list(sums2):\n if x+nums[i] in sums2:\n continue\n sums2.add(x+nums[i])\n ni = bisect.bisect_left(sorted_sums1, goal-x-nums[i]) # Time: O(2^(n/2)) * O(n/2)\n if ni < len(sorted_sums1):\n result = min(result, abs(goal-x-nums[i]-sorted_sums1[ni]))\n if ni > 0:\n result = min(result, abs(goal-x-nums[i]-sorted_sums1[ni-1]))\n if result == 0:\n return result\n return result\n"}} diff --git a/cp/cp-11129.jsonl b/cp/cp-11129.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..da181caa66ed1b52c8d57a3b88f8249b9cc2001d --- /dev/null +++ b/cp/cp-11129.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11129", "name": "LeetCode 1759: Count Number Of Homogenous 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: Count Number of Homogenous Substrings (Difficulty: Medium)\nTags: Math, String\n\nGiven a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.\nA string is homogenous if all the characters of the string are the same.\nA substring is a contiguous sequence of characters within a string.\n\nExample 1:\nInput: s = \"abbcccaa\"\nOutput: 13\nExplanation: The homogenous substrings are listed as below:\n\"a\" appears 3 times.\n\"aa\" appears 1 time.\n\"b\" appears 2 times.\n\"bb\" appears 1 time.\n\"c\" appears 3 times.\n\"cc\" appears 2 times.\n\"ccc\" appears 1 time.\n3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.\n\nExample 2:\nInput: s = \"xy\"\nOutput: 2\nExplanation: The homogenous substrings are \"x\" and \"y\".\n\nExample 3:\nInput: s = \"zzzzz\"\nOutput: 15\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s consists of lowercase letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def countHomogenous(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n result = cnt = 0\n for i in range(len(s)):\n if i and s[i-1] == s[i]:\n cnt += 1\n else:\n cnt = 1\n result = (result+cnt)%MOD\n return result\n"}} diff --git a/cp/cp-11130.jsonl b/cp/cp-11130.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e0fd15a832c4db6aa34517f497a25499dd30e700 --- /dev/null +++ b/cp/cp-11130.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11130", "name": "LeetCode 1760: Minimum Limit Of Balls In A Bag"} +{"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: Minimum Limit of Balls in a Bag (Difficulty: Medium)\nTags: Array, Binary Search\n\nYou are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations.\nYou can perform the following operation at most maxOperations times:\nYour penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.\nReturn the minimum possible penalty after performing the operations.\n\nExample 1:\nInput: nums = [9], maxOperations = 2\nOutput: 3\nExplanation: \n- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].\n- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].\nThe bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.\n\nExample 2:\nInput: nums = [2,4,8,2], maxOperations = 4\nOutput: 2\nExplanation:\n- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].\nThe bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= maxOperations, nums[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogm), m is the max of nums\n# Space: O(1)\n\nclass Solution(object):\n def minimumSize(self, nums, maxOperations):\n \"\"\"\n :type nums: List[int]\n :type maxOperations: int\n :rtype: int\n \"\"\"\n def check(nums, maxOperations, x):\n return sum((num+x-1)//x-1 for num in nums) <= maxOperations\n \n left, right = 1, max(nums)\n while left <= right:\n mid = left + (right-left)//2\n if check(nums, maxOperations, mid):\n right = mid-1\n else:\n left = mid+1\n return left\n"}} diff --git a/cp/cp-11131.jsonl b/cp/cp-11131.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6c44b2a8f3cecac8939f55ed59e9b9e8dfe105c9 --- /dev/null +++ b/cp/cp-11131.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11131", "name": "LeetCode 1761: Minimum Degree Of A Connected Trio In A Graph"} +{"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: Minimum Degree of a Connected Trio in a Graph (Difficulty: Hard)\nTags: Graph, Enumeration\n\nYou are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi.\nA connected trio is a set of three nodes where there is an edge between every pair of them.\nThe degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not.\nReturn the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.\n\nExample 1:\nInput: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]\nOutput: 3\nExplanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above.\n\nExample 2:\nInput: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]\nOutput: 0\nExplanation: There are exactly three trios:\n1) [1,4,3] with degree 0.\n2) [2,5,6] with degree 2.\n3) [5,6,7] with degree 2.\n\nConstraints:\n- 2 <= n <= 400\n- edges[i].length == 2\n- 1 <= edges.length <= n * (n-1) / 2\n- 1 <= ui, vi <= n\n- ui != vi\n- There are no repeated edges."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(n^2)\n\nclass Solution(object):\n def minTrioDegree(self, n, edges):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :rtype: int\n \"\"\"\n adj = [set() for _ in range(n+1)]\n degree = [0]*(n+1)\n for u, v in edges:\n adj[min(u, v)].add(max(u, v))\n degree[u] += 1\n degree[v] += 1\n result = float(\"inf\")\n for u in range(1, n+1):\n for v in adj[u]:\n for w in adj[u]:\n if v < w and w in adj[v]:\n result = min(result, degree[u]+degree[v]+degree[w] - 6)\n return result if result != float(\"inf\") else -1\n"}} diff --git a/cp/cp-11133.jsonl b/cp/cp-11133.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b6fe80cf165faab0af5f660581efda28991b31f7 --- /dev/null +++ b/cp/cp-11133.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11133", "name": "LeetCode 1763: Longest Nice Substring"} +{"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 Nice Substring (Difficulty: Easy)\nTags: Hash Table, String, Divide and Conquer, Bit Manipulation, Sliding Window\n\nA string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, \"abABB\" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, \"abA\" is not because 'b' appears, but 'B' does not.\nGiven a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.\n\nExample 1:\nInput: s = \"YazaAay\"\nOutput: \"aAa\"\nExplanation: \"aAa\" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.\n\"aAa\" is the longest nice substring.\n\nExample 2:\nInput: s = \"Bb\"\nOutput: \"Bb\"\nExplanation: \"Bb\" is a nice string because both 'B' and 'b' appear. The whole string is a substring.\n\nExample 3:\nInput: s = \"c\"\nOutput: \"\"\nExplanation: There are no nice substrings.\n\nConstraints:\n- 1 <= s.length <= 100\n- s consists of uppercase and lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(26 * n) = O(n)\n# Space: O(26 * n) = O(n)\n\nclass Solution(object):\n def longestNiceSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n lookup = set(list(s))\n prev = -1\n result = \"\"\n for i in range(len(s)+1):\n if not (i == len(s) or s[i] not in lookup or s[i].swapcase() not in lookup):\n continue\n if prev == -1 and i == len(s):\n return s\n tmp = self.longestNiceSubstring(s[prev+1:i])\n if len(tmp) > len(result):\n result = tmp\n prev = i\n return result\n"}} diff --git a/cp/cp-11134.jsonl b/cp/cp-11134.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a3734a8d5155b799efc916a9acf129ea90d1d007 --- /dev/null +++ b/cp/cp-11134.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11134", "name": "LeetCode 1764: Form Array By Concatenating Subarrays Of Another 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: Form Array by Concatenating Subarrays of Another Array (Difficulty: Medium)\nTags: Array, Two Pointers, Greedy, String Matching\n\nYou are given a 2D integer array groups of length n. You are also given an integer array nums.\nYou are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups).\nReturn true if you can do this task, and false otherwise.\nNote that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.\n\nExample 1:\nInput: groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]\nOutput: true\nExplanation: You can choose the 0th subarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1st one as [1,-1,0,1,-1,-1,3,-2,0].\nThese subarrays are disjoint as they share no common nums[k] element.\n\nExample 2:\nInput: groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]\nOutput: false\nExplanation: Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups.\n[10,-2] must come before [1,2,3,4].\n\nExample 3:\nInput: groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]\nOutput: false\nExplanation: Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint.\nThey share a common elements nums[4] (0-indexed).\n\nConstraints:\n- groups.length == n\n- 1 <= n <= 103\n- 1 <= groups[i].length, sum(groups[i].length) <= 103\n- 1 <= nums.length <= 103\n- -107 <= groups[i][j], nums[k] <= 10^7"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def canChoose(self, groups, nums):\n \"\"\"\n :type groups: List[List[int]]\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n def getPrefix(pattern):\n prefix = [-1]*len(pattern)\n j = -1\n for i in range(1, len(pattern)):\n while j+1 > 0 and pattern[j+1] != pattern[i]:\n j = prefix[j]\n if pattern[j+1] == pattern[i]:\n j += 1\n prefix[i] = j\n return prefix\n \n def KMP(text, pattern, start):\n prefix = getPrefix(pattern)\n j = -1\n for i in range(start, len(text)):\n while j+1 > 0 and pattern[j+1] != text[i]:\n j = prefix[j]\n if pattern[j+1] == text[i]:\n j += 1\n if j+1 == len(pattern):\n return i-j\n return -1\n\n pos = 0\n for group in groups:\n pos = KMP(nums, group, pos)\n if pos == -1:\n return False\n pos += len(group)\n return True\n\n"}} diff --git a/cp/cp-11135.jsonl b/cp/cp-11135.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a032517df78130418e5fec823ab853e7d487335d --- /dev/null +++ b/cp/cp-11135.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11135", "name": "LeetCode 1765: Map Of Highest Peak"} +{"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 of Highest Peak (Difficulty: Medium)\nTags: Array, Breadth-First Search, Matrix\n\nYou are given an integer matrix isWater of size m x n that represents a map of land and water cells.\nYou must assign each cell a height in a way that follows these rules:\nFind an assignment of heights such that the maximum height in the matrix is maximized.\nReturn an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there are multiple solutions, return any of them.\nNote: This question is the same as 542: https://leetcode.com/problems/01-matrix/\n\nExample 1:\nInput: isWater = [[0,1],[0,0]]\nOutput: [[1,0],[2,1]]\nExplanation: The image shows the assigned heights of each cell.\nThe blue cell is the water cell, and the green cells are the land cells.\n\nExample 2:\nInput: isWater = [[0,0,1],[1,0,0],[0,0,0]]\nOutput: [[1,1,0],[0,1,1],[1,2,2]]\nExplanation: A height of 2 is the maximum possible height of any assignment.\nAny height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.\n\nConstraints:\n- m == isWater.length\n- n == isWater[i].length\n- 1 <= m, n <= 1000\n- isWater[i][j] is 0 or 1.\n- There is at least one water cell."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m * n)\n\nclass Solution(object):\n def highestPeak(self, isWater):\n \"\"\"\n :type isWater: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\n q = []\n for r, row in enumerate(isWater):\n for c, cell in enumerate(row):\n row[c] -= 1\n if not cell:\n continue\n q.append((r, c))\n while q:\n new_q = []\n for r, c in q:\n for dr, dc in directions:\n nr, nc = r+dr, c+dc \n if not (0 <= nr < len(isWater) and\n 0 <= nc < len(isWater[0]) and\n isWater[nr][nc] == -1):\n continue\n isWater[nr][nc] = isWater[r][c]+1\n q.append((nr, nc))\n q = new_q\n return isWater\n\n\n# Time: O(m * n)\n# Space: O(m * n)\nclass Solution2(object):\n def highestPeak(self, isWater):\n \"\"\"\n :type isWater: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\n q, heights = [], [[-1]*len(isWater[0]) for _ in range(len(isWater))]\n for r, row in enumerate(isWater):\n for c, cell in enumerate(row):\n if not cell:\n continue\n heights[r][c] = 0\n q.append((r, c))\n while q:\n new_q = []\n for r, c in q:\n for dr, dc in directions:\n nr, nc = r+dr, c+dc \n if not (0 <= nr < len(isWater) and\n 0 <= nc < len(isWater[0]) and\n heights[nr][nc] == -1):\n continue\n heights[nr][nc] = heights[r][c]+1\n q.append((nr, nc))\n q = new_q\n return heights\n"}} diff --git a/cp/cp-11136.jsonl b/cp/cp-11136.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a567446017e9d285070570c4f412380476c6b7be --- /dev/null +++ b/cp/cp-11136.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11136", "name": "LeetCode 1766: Tree Of Coprimes"} +{"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: Tree of Coprimes (Difficulty: Hard)\nTags: Array, Math, Tree, Depth-First Search, Number Theory\n\nThere is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0.\nTo represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree.\nTwo values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y.\nAn ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself.\nReturn an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor.\n\nExample 1:\nInput: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]\nOutput: [-1,0,0,1]\nExplanation: In the above figure, each node's value is in parentheses.\n- Node 0 has no coprime ancestors.\n- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).\n- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's\n value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.\n- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its\n closest valid ancestor.\n\nExample 2:\nInput: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]\nOutput: [-1,0,-1,0,0,0,-1]\n\nConstraints:\n- nums.length == n\n- 1 <= nums[i] <= 50\n- 1 <= n <= 10^5\n- edges.length == n - 1\n- edges[j].length == 2\n- 0 <= uj, vj < n\n- uj != vj"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(50 * n) = O(n)\n# Space: O(n)\n\nimport collections\nimport fractions\n\n\nclass Solution(object):\n def getCoprimes(self, nums, edges):\n \"\"\"\n :type nums: List[int]\n :type edges: List[List[int]]\n :rtype: List[int]\n \"\"\" \n def iter_dfs(nums, adj):\n result = [-1]*len(nums)\n path = collections.defaultdict(list)\n stk = [(1, (-1, 0, 0))]\n while stk:\n step, params = stk.pop()\n if step == 1:\n prev, node, depth = params\n stk.append((4, (node,)))\n stk.append((3, (prev, node, depth)))\n stk.append((2, (node,)))\n elif step == 2:\n node = params[0]\n max_d = -1\n for x in path.iterkeys():\n if fractions.gcd(nums[node], x) != 1:\n continue\n if path[x][-1][1] > max_d:\n max_d = path[x][-1][1]\n result[node] = path[x][-1][0]\n elif step == 3:\n prev, node, depth = params\n path[nums[node]].append((node, depth))\n for nei in adj[node]:\n if nei == prev:\n continue\n stk.append((1, (node, nei, depth+1)))\n elif step == 4:\n node = params[0]\n path[nums[node]].pop()\n if not path[nums[node]]:\n path.pop(nums[node])\n return result\n\n adj = collections.defaultdict(list)\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n return iter_dfs(nums, adj)\n\n\n# Time: O(50 * n) = O(n)\n# Space: O(n)\nimport collections\nimport fractions\n\n\nclass Solution2(object):\n def getCoprimes(self, nums, edges):\n \"\"\"\n :type nums: List[int]\n :type edges: List[List[int]]\n :rtype: List[int]\n \"\"\" \n def dfs(nums, adj, prev, node, depth, path, result):\n max_d = -1\n for x in path.iterkeys():\n if fractions.gcd(nums[node], x) != 1:\n continue\n if path[x][-1][1] > max_d:\n max_d = path[x][-1][1]\n result[node] = path[x][-1][0]\n path[nums[node]].append((node, depth))\n for nei in adj[node]:\n if nei == prev:\n continue\n dfs(nums, adj, node, nei, depth+1, path, result)\n path[nums[node]].pop()\n if not path[nums[node]]:\n path.pop(nums[node])\n\n adj = collections.defaultdict(list)\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n result = [-1]*len(nums)\n path = collections.defaultdict(list)\n dfs(nums, adj, -1, 0, 0, path, result)\n return result\n"}} diff --git a/cp/cp-11137.jsonl b/cp/cp-11137.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..56c453497ce2b2f1a4860b5e782ed77592632df3 --- /dev/null +++ b/cp/cp-11137.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11137", "name": "LeetCode 1768: Merge Strings Alternately"} +{"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 Strings Alternately (Difficulty: Easy)\nTags: Two Pointers, String\n\nYou are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.\nReturn the merged string.\n\nExample 1:\nInput: word1 = \"abc\", word2 = \"pqr\"\r\nOutput: \"apbqcr\"\r\nExplanation: The merged string will be merged as so:\r\nword1: a b c\r\nword2: p q r\r\nmerged: a p b q c r\n\nExample 2:\nInput: word1 = \"ab\", word2 = \"pqrs\"\r\nOutput: \"apbqrs\"\r\nExplanation: Notice that as word2 is longer, \"rs\" is appended to the end.\r\nword1: a b \r\nword2: p q r s\r\nmerged: a p b q r s\n\nExample 3:\nInput: word1 = \"abcd\", word2 = \"pq\"\r\nOutput: \"apbqcd\"\r\nExplanation: Notice that as word1 is longer, \"cd\" is appended to the end.\r\nword1: a b c d\r\nword2: p q \r\nmerged: a p b q c d\n\nConstraints:\n- 1 <= word1.length, word2.length <= 100\n- word1 and word2 consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n)\n# Space: O(1)\n\nclass Solution(object):\n def mergeAlternately(self, word1, word2):\n \"\"\"\n :type word1: str\n :type word2: str\n :rtype: str\n \"\"\"\n result = []\n i = 0\n while i < len(word1) or i < len(word2):\n if i < len(word1):\n result.append(word1[i])\n if i < len(word2):\n result.append(word2[i])\n i += 1\n return \"\".join(result)\n"}} diff --git a/cp/cp-11138.jsonl b/cp/cp-11138.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..95ba9241f37289a5715523379c96705224eba950 --- /dev/null +++ b/cp/cp-11138.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11138", "name": "LeetCode 1769: Minimum Number Of Operations To Move All Balls To Each Box"} +{"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: Minimum Number of Operations to Move All Balls to Each Box (Difficulty: Medium)\nTags: Array, String, Prefix Sum\n\nYou have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball.\nIn one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.\nReturn an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.\nEach answer[i] is calculated considering the initial state of the boxes.\n\nExample 1:\nInput: boxes = \"110\"\nOutput: [1,1,3]\nExplanation: The answer for each box is as follows:\n1) First box: you will have to move one ball from the second box to the first box in one operation.\n2) Second box: you will have to move one ball from the first box to the second box in one operation.\n3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.\n\nExample 2:\nInput: boxes = \"001011\"\nOutput: [11,8,5,4,3,4]\n\nConstraints:\n- n == boxes.length\n- 1 <= n <= 2000\n- boxes[i] is either '0' or '1'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minOperations(self, boxes):\n \"\"\"\n :type boxes: str\n :rtype: List[int]\n \"\"\"\n result = [0]*len(boxes)\n for direction in (lambda x:x, reversed):\n cnt = accu = 0\n for i in direction(range(len(boxes))):\n result[i] += accu\n if boxes[i] == '1':\n cnt += 1\n accu += cnt\n return result\n"}} diff --git a/cp/cp-11139.jsonl b/cp/cp-11139.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c0e915fd5c7e2070196c1d5c1d706fd5ff7bd18c --- /dev/null +++ b/cp/cp-11139.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11139", "name": "LeetCode 1770: Maximum Score From Performing Multiplication Operations"} +{"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 Score from Performing Multiplication Operations (Difficulty: Hard)\nTags: Array, Dynamic Programming\n\nYou are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, where n >= m.\nYou begin with a score of 0. You want to perform exactly m operations. On the ith operation (0-indexed) you will:\nReturn the maximum score after performing m operations.\n\nExample 1:\nInput: nums = [1,2,3], multipliers = [3,2,1]\nOutput: 14\nExplanation: An optimal solution is as follows:\n- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.\n- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.\n- Choose from the end, [1], adding 1 * 1 = 1 to the score.\nThe total score is 9 + 4 + 1 = 14.\n\nExample 2:\nInput: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]\nOutput: 102\nExplanation: An optimal solution is as follows:\n- Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.\n- Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.\n- Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.\n- Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.\n- Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. \nThe total score is 50 + 15 - 9 + 4 + 42 = 102.\n\nConstraints:\n- n == nums.length\n- m == multipliers.length\n- 1 <= m <= 300\n- m <= n <= 10^5\n- -1000 <= nums[i], multipliers[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m^2)\n# Space: O(m)\n\nclass Solution(object):\n def maximumScore(self, nums, multipliers):\n \"\"\"\n :type nums: List[int]\n :type multipliers: List[int]\n :rtype: int\n \"\"\"\n dp = [0]*(len(multipliers)+1)\n for l, m in enumerate(reversed(multipliers), start=len(nums)-len(multipliers)):\n dp = [max(m*nums[i]+dp[i+1], m*nums[i+l]+dp[i]) for i in range(len(dp)-1)]\n return dp[0]\n"}} diff --git a/cp/cp-11140.jsonl b/cp/cp-11140.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..101c21d3683f7e3f92b30e27d990660a3b01d72c --- /dev/null +++ b/cp/cp-11140.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11140", "name": "LeetCode 1771: Maximize Palindrome Length From 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: Maximize Palindrome Length From Subsequences (Difficulty: Hard)\nTags: String, Dynamic Programming\n\nYou are given two strings, word1 and word2. You want to construct a string in the following manner:\nReturn the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0.\nA subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters.\nA palindrome is a string that reads the same forward as well as backward.\n\nExample 1:\nInput: word1 = \"cacb\", word2 = \"cbba\"\nOutput: 5\nExplanation: Choose \"ab\" from word1 and \"cba\" from word2 to make \"abcba\", which is a palindrome.\n\nExample 2:\nInput: word1 = \"ab\", word2 = \"ab\"\nOutput: 3\nExplanation: Choose \"ab\" from word1 and \"a\" from word2 to make \"aba\", which is a palindrome.\n\nExample 3:\nInput: word1 = \"aa\", word2 = \"bb\"\nOutput: 0\nExplanation: You cannot construct a palindrome from the described method, so return 0.\n\nConstraints:\n- 1 <= word1.length, word2.length <= 1000\n- word1 and word2 consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((m + n)^2)\n# Space: O((m + n)^2)\n\nclass Solution(object):\n def longestPalindrome(self, word1, word2):\n \"\"\"\n :type word1: str\n :type word2: str\n :rtype: int\n \"\"\"\n s = word1+word2\n dp = [[0]*len(s) for _ in range(len(s))]\n result = 0\n for j in range(len(s)):\n dp[j][j] = 1\n for i in reversed(range(j)):\n if s[i] == s[j]:\n dp[i][j] = 2 if i+1 == j else dp[i+1][j-1] + 2\n if i < len(word1) <= j:\n result = max(result, dp[i][j])\n else:\n dp[i][j] = max(dp[i+1][j], dp[i][j-1])\n return result\n\n\n# Time: O((m + n)^2)\n# Space: O((m + n)^2)\nclass Solution2(object):\n def longestPalindrome(self, word1, word2):\n \"\"\"\n :type word1: str\n :type word2: str\n :rtype: int\n \"\"\"\n s = word1+word2\n dp = [[0]*len(s) for _ in range(len(s))]\n for j in range(len(s)):\n dp[j][j] = 1\n for i in reversed(range(j)):\n if s[i] == s[j]:\n dp[i][j] = 2 if i+1 == j else dp[i+1][j-1] + 2\n else:\n dp[i][j] = max(dp[i+1][j], dp[i][j-1])\n return max([dp[i][j] for i in range(len(word1)) for j in range(len(word1), len(s)) if s[i] == s[j]] or [0])\n"}} diff --git a/cp/cp-11142.jsonl b/cp/cp-11142.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a91851c1de05a4a721a5e2034282531784d581d1 --- /dev/null +++ b/cp/cp-11142.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11142", "name": "LeetCode 1773: Count Items Matching A Rule"} +{"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: Count Items Matching a Rule (Difficulty: Easy)\nTags: Array, String\n\nYou are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue.\nThe ith item is said to match the rule if one of the following is true:\nReturn the number of items that match the given rule.\n\nExample 1:\nInput: items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"lenovo\"],[\"phone\",\"gold\",\"iphone\"]], ruleKey = \"color\", ruleValue = \"silver\"\nOutput: 1\nExplanation: There is only one item matching the given rule, which is [\"computer\",\"silver\",\"lenovo\"].\n\nExample 2:\nInput: items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"phone\"],[\"phone\",\"gold\",\"iphone\"]], ruleKey = \"type\", ruleValue = \"phone\"\nOutput: 2\nExplanation: There are only two items matching the given rule, which are [\"phone\",\"blue\",\"pixel\"] and [\"phone\",\"gold\",\"iphone\"]. Note that the item [\"computer\",\"silver\",\"phone\"] does not match.\n\nConstraints:\n- 1 <= items.length <= 10^4\n- 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10\n- ruleKey is equal to either \"type\", \"color\", or \"name\".\n- All strings consist only of lowercase letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def countMatches(self, items, ruleKey, ruleValue):\n \"\"\"\n :type items: List[List[str]]\n :type ruleKey: str\n :type ruleValue: str\n :rtype: int\n \"\"\"\n rule = {\"type\":0, \"color\":1, \"name\":2}\n return sum(item[rule[ruleKey]] == ruleValue for item in items)\n"}} diff --git a/cp/cp-11143.jsonl b/cp/cp-11143.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a0bce1c8ae4c0faf3ac739b917b29bcd92401cfb --- /dev/null +++ b/cp/cp-11143.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11143", "name": "LeetCode 1774: Closest Dessert Cost"} +{"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: Closest Dessert Cost (Difficulty: Medium)\nTags: Array, Dynamic Programming, Backtracking\n\nYou would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert:\nYou are given three inputs:\nYou want to make a dessert with a total cost as close to target as possible.\nReturn the closest possible cost of the dessert to target. If there are multiple, return the lower one.\n\nExample 1:\nInput: baseCosts = [1,7], toppingCosts = [3,4], target = 10\nOutput: 10\nExplanation: Consider the following combination (all 0-indexed):\n- Choose base 1: cost 7\n- Take 1 of topping 0: cost 1 x 3 = 3\n- Take 0 of topping 1: cost 0 x 4 = 0\nTotal: 7 + 3 + 0 = 10.\n\nExample 2:\nInput: baseCosts = [2,3], toppingCosts = [4,5,100], target = 18\nOutput: 17\nExplanation: Consider the following combination (all 0-indexed):\n- Choose base 1: cost 3\n- Take 1 of topping 0: cost 1 x 4 = 4\n- Take 2 of topping 1: cost 2 x 5 = 10\n- Take 0 of topping 2: cost 0 x 100 = 0\nTotal: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.\n\nExample 3:\nInput: baseCosts = [3,10], toppingCosts = [2,5], target = 9\nOutput: 8\nExplanation: It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.\n\nConstraints:\n- n == baseCosts.length\n- m == toppingCosts.length\n- 1 <= n, m <= 10\n- 1 <= baseCosts[i], toppingCosts[i] <= 10^4\n- 1 <= target <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * max(max_base, target + max_topping / 2)) ~= O(m * t)\n# Space: O(max(max_base, target + max_topping / 2)) ~= O(t)\n\nclass Solution(object):\n def closestCost(self, baseCosts, toppingCosts, target):\n \"\"\"\n :type baseCosts: List[int]\n :type toppingCosts: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n max_count = 2\n max_base, max_topping = max(baseCosts), max(toppingCosts)\n dp = [False]*(max(max_base, target+max_topping//2)+1)\n for b in baseCosts:\n dp[b] = True\n for t in toppingCosts:\n for _ in range(max_count):\n for i in reversed(range(len(dp)-t)):\n if dp[i]:\n dp[i+t] = True\n result = float(\"inf\")\n for i in range(1, len(dp)):\n if not dp[i]:\n continue\n if abs(i-target) < abs(result-target):\n result = i\n if i >= target:\n break\n return result\n \n\n# Time: O(n * 3^m)\n# Space: O(m * t)\nclass Solution2(object):\n def closestCost(self, baseCosts, toppingCosts, target):\n \"\"\"\n :type baseCosts: List[int]\n :type toppingCosts: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n max_count = 2\n def backtracking(toppingCosts, i, cost, target, lookup, result):\n if (i, cost) in lookup:\n return\n lookup.add((i, cost))\n if cost >= target or i == len(toppingCosts):\n if (abs(cost-target), cost) < (abs(result[0]-target), result[0]):\n result[0] = cost\n return\n for j in range(max_count+1):\n backtracking(toppingCosts, i+1, cost+j*toppingCosts[i], target, lookup, result)\n\n result = [float(\"inf\")]\n lookup = set()\n for b in baseCosts:\n backtracking(toppingCosts, 0, b, target, lookup, result)\n return result[0]\n\n\n# Time: O(3^m*log(3^m)) + O(n*log(3^m)) = O(m*(3^m + n))\n# Space: O(3^m)\nimport bisect\n\n\nclass Solution3(object):\n def closestCost(self, baseCosts, toppingCosts, target):\n \"\"\"\n :type baseCosts: List[int]\n :type toppingCosts: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n max_count = 2\n combs = set([0])\n for t in toppingCosts:\n combs = set([c+i*t for c in combs for i in range(max_count+1)])\n result, combs = float(\"inf\"), sorted(combs)\n for b in baseCosts:\n idx = bisect.bisect_left(combs, target-b)\n if idx < len(combs):\n result = min(result, b+combs[idx], key=lambda x: (abs(x-target), x))\n if idx > 0:\n result = min(result, b+combs[idx-1], key=lambda x: (abs(x-target), x)) \n return result\n\n\n# Time: O(n * 3^m)\n# Space: O(3^m)\nclass Solution4(object):\n def closestCost(self, baseCosts, toppingCosts, target):\n \"\"\"\n :type baseCosts: List[int]\n :type toppingCosts: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n max_count = 2\n combs = set([0])\n for t in toppingCosts:\n combs = set([c+i*t for c in combs for i in range(max_count+1)])\n result = float(\"inf\")\n for b in baseCosts:\n for c in combs:\n result = min(result, b+c, key=lambda x: (abs(x-target), x)) \n return result\n"}} diff --git a/cp/cp-11144.jsonl b/cp/cp-11144.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..063daa854df0c39e1c5d77bf667fc8910af63740 --- /dev/null +++ b/cp/cp-11144.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11144", "name": "LeetCode 1775: Equal Sum Arrays With Minimum Number Of Operations"} +{"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: Equal Sum Arrays With Minimum Number of Operations (Difficulty: Medium)\nTags: Array, Hash Table, Greedy, Counting\n\nYou are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.\nIn one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.\nReturn the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1​​​​​ if it is not possible to make the sum of the two arrays equal.\n\nExample 1:\nInput: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]\nOutput: 3\nExplanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.\n- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].\n- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].\n- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].\n\nExample 2:\nInput: nums1 = [1,1,1,1,1,1,1], nums2 = [6]\nOutput: -1\nExplanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.\n\nExample 3:\nInput: nums1 = [6,6], nums2 = [1]\nOutput: 3\nExplanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. \n- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].\n- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].\n- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].\n\nConstraints:\n- 1 <= nums1.length, nums2.length <= 10^5\n- 1 <= nums1[i], nums2[i] <= 6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m + n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def minOperations(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: int\n \"\"\"\n if len(nums1)*6 < len(nums2) or len(nums1) > len(nums2)*6:\n return -1\n diff = sum(nums2)-sum(nums1)\n if diff < 0:\n nums1, nums2 = nums2, nums1\n diff = -diff\n count = collections.Counter(6-num for num in nums1)\n count += collections.Counter(num-1 for num in nums2)\n result = 0\n for i in reversed(range(1, 6)):\n if not count[i]:\n continue\n cnt = min(count[i], (diff+i-1)//i)\n result += cnt\n diff -= i*cnt\n if diff <= 0:\n break\n return result\n"}} diff --git a/cp/cp-11145.jsonl b/cp/cp-11145.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..316c54725ef16c206bf08e62bcf18bbe5496bd25 --- /dev/null +++ b/cp/cp-11145.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11145", "name": "LeetCode 1776: Car Fleet 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: Car Fleet II (Difficulty: Hard)\nTags: Array, Math, Stack, Heap (Priority Queue), Monotonic Stack\n\nThere are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents:\nFor simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet.\nReturn an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted.\n\nExample 1:\nInput: cars = [[1,2],[2,1],[4,3],[7,2]]\nOutput: [1.00000,-1.00000,3.00000,-1.00000]\nExplanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.\n\nExample 2:\nInput: cars = [[3,4],[5,4],[6,3],[9,1]]\nOutput: [2.00000,1.00000,1.50000,-1.00000]\n\nConstraints:\n- 1 <= cars.length <= 10^5\n- 1 <= positioni, speedi <= 10^6\n- positioni < positioni+1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def getCollisionTimes(self, cars):\n \"\"\"\n :type cars: List[List[int]]\n :rtype: List[float]\n \"\"\"\n stk = []\n result = [-1.0]*len(cars)\n for i in reversed(range(len(cars))):\n p, s = cars[i]\n while stk and (cars[stk[-1]][1] >= s or \n 0 < result[stk[-1]] <= float(cars[stk[-1]][0]-p)/(s-cars[stk[-1]][1])):\n stk.pop()\n if stk:\n result[i] = float(cars[stk[-1]][0]-p)/(s-cars[stk[-1]][1])\n stk.append(i)\n return result\n"}} diff --git a/cp/cp-11147.jsonl b/cp/cp-11147.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a7472ad7884f468d3e96564bd3d06feea4d3c725 --- /dev/null +++ b/cp/cp-11147.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11147", "name": "LeetCode 1779: Find Nearest Point That Has The Same X Or Y Coordinate"} +{"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 Nearest Point That Has the Same X or Y Coordinate (Difficulty: Easy)\nTags: Array\n\nYou are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location.\nReturn the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1.\nThe Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).\n\nExample 1:\nInput: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]\nOutput: 2\nExplanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.\n\nExample 2:\nInput: x = 3, y = 4, points = [[3,4]]\nOutput: 0\nExplanation: The answer is allowed to be on the same location as your current location.\n\nExample 3:\nInput: x = 3, y = 4, points = [[2,3]]\nOutput: -1\nExplanation: There are no valid points.\n\nConstraints:\n- 1 <= points.length <= 10^4\n- points[i].length == 2\n- 1 <= x, y, ai, bi <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def nearestValidPoint(self, x, y, points):\n \"\"\"\n :type x: int\n :type y: int\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n smallest, idx = float(\"inf\"), -1\n for i, (r, c) in enumerate(points):\n dx, dy = x-r, y-c\n if dx*dy == 0 and abs(dx)+abs(dy) < smallest:\n smallest = abs(dx)+abs(dy)\n idx = i\n return idx\n"}} diff --git a/cp/cp-11149.jsonl b/cp/cp-11149.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d8bd6fd343459355ae27229f9b7c135472e313b6 --- /dev/null +++ b/cp/cp-11149.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11149", "name": "LeetCode 1781: Sum Of Beauty Of All 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: Sum of Beauty of All Substrings (Difficulty: Medium)\nTags: Hash Table, String, Counting\n\nThe beauty of a string is the difference in frequencies between the most frequent and least frequent characters.\nGiven a string s, return the sum of beauty of all of its substrings.\n\nExample 1:\nInput: s = \"aabcb\"\nOutput: 5\nExplanation: The substrings with non-zero beauty are [\"aab\",\"aabc\",\"aabcb\",\"abcb\",\"bcb\"], each with beauty equal to 1.\n\nExample 2:\nInput: s = \"aabcbaa\"\nOutput: 17\n\nConstraints:\n- 1 <= s.length <= 500\n- s consists of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(1)\n\nclass Solution(object):\n def beautySum(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result = 0 \n for i in range(len(s)):\n lookup = [0]*26\n for j in range(i, len(s)):\n lookup[ord(s[j])-ord('a')] += 1\n result += max(lookup) - min(x for x in lookup if x)\n return result\n"}} diff --git a/cp/cp-11150.jsonl b/cp/cp-11150.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0e458b08ea9725f331ac046be64a456fa8ed2898 --- /dev/null +++ b/cp/cp-11150.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11150", "name": "LeetCode 1782: Count Pairs Of Nodes"} +{"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: Count Pairs Of Nodes (Difficulty: Hard)\nTags: Array, Hash Table, Two Pointers, Binary Search, Graph, Sorting, Counting\n\nYou are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries.\nLet incident(a, b) be defined as the number of edges that are connected to either node a or b.\nThe answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the following conditions:\nReturn an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query.\nNote that there can be multiple edges between the same two nodes.\n\nExample 1:\nInput: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]\nOutput: [6,5]\nExplanation: The calculations for incident(a, b) are shown in the table above.\nThe answers for each of the queries are as follows:\n- answers[0] = 6. All the pairs have an incident(a, b) value greater than 2.\n- answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.\n\nExample 2:\nInput: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]\nOutput: [10,10,9,8,6]\n\nConstraints:\n- 2 <= n <= 2 * 10^4\n- 1 <= edges.length <= 10^5\n- 1 <= ui, vi <= n\n- ui != vi\n- 1 <= queries.length <= 20\n- 0 <= queries[j] < edges.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + e + q)\n# Space: O(n + e)\n\nimport collections\nimport itertools\n\n\n# pure counting solution\nclass Solution(object):\n def countPairs(self, n, edges, queries):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type queries: List[int]\n :rtype: List[int]\n \"\"\"\n degree = [0]*(n+1)\n shared = collections.Counter((min(n1, n2), max(n1, n2)) for n1, n2 in edges)\n for u, v in edges:\n degree[u] += 1\n degree[v] += 1\n cnt = [0]*(2*(max(degree[1:])+1))\n count = collections.Counter(degree[1:])\n for i, j in itertools.product(count, count): # Time: O(d^2) = O(e)\n if i < j:\n cnt[i+j] += count[i]*count[j]\n elif i == j:\n cnt[i+j] += count[i]*(count[i]-1)//2\n for (i, j), shared_degree in shared.iteritems():\n cnt[degree[i]+degree[j]] -= 1\n cnt[degree[i]+degree[j]-shared_degree] += 1\n for i in reversed(range(len(cnt)-1)): # accumulate\n cnt[i] += cnt[i+1]\n return [cnt[q+1] if q+1 < len(cnt) else 0 for q in queries]\n\n\n# Time: O(nlogn + q * (n + e))\n# Space: O(n + e)\nimport collections\n\n\n# two pointers solution\nclass Solution2(object):\n def countPairs(self, n, edges, queries):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type queries: List[int]\n :rtype: List[int]\n \"\"\"\n degree = [0]*(n+1)\n shared = collections.Counter((min(n1, n2), max(n1, n2)) for n1, n2 in edges)\n for n1, n2 in edges:\n degree[n1] += 1\n degree[n2] += 1\n sorted_degree = sorted(degree)\n result = []\n for k, q in enumerate(queries):\n left, right = 1, n\n cnt = 0\n while left < right:\n if q < sorted_degree[left]+sorted_degree[right]:\n cnt += right-left\n right -= 1\n else:\n left += 1\n for (i, j), shared_degree in shared.iteritems():\n if degree[i]+degree[j]-shared_degree <= q < degree[i]+degree[j]:\n cnt -= 1\n result.append(cnt)\n return result\n"}} diff --git a/cp/cp-11153.jsonl b/cp/cp-11153.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1b811cceeb055f7bb9396ad99924203eea5eaf03 --- /dev/null +++ b/cp/cp-11153.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11153", "name": "LeetCode 1786: Number Of Restricted Paths From First To Last Node"} +{"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 Restricted Paths From First to Last Node (Difficulty: Medium)\nTags: Dynamic Programming, Graph, Topological Sort, Heap (Priority Queue), Shortest Path\n\nThere is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti.\nA path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1.\nThe distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1.\nReturn the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]\nOutput: 3\nExplanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:\n1) 1 --> 2 --> 5\n2) 1 --> 2 --> 3 --> 5\n3) 1 --> 3 --> 5\n\nExample 2:\nInput: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]\nOutput: 1\nExplanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7.\n\nConstraints:\n- 1 <= n <= 2 * 10^4\n- n - 1 <= edges.length <= 4 * 10^4\n- edges[i].length == 3\n- 1 <= ui, vi <= n\n- ui != vi\n- 1 <= weighti <= 10^5\n- There is at most one edge between any two nodes.\n- There is at least one path between any two nodes."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(|E| * log|V|)\n# Space: O(|E| + |V|)\n\nimport heapq\n\n\nclass Solution(object):\n def countRestrictedPaths(self, n, edges):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n adj = [[] for _ in range(n)]\n for u, v, w in edges:\n adj[u-1].append((v-1, w))\n adj[v-1].append((u-1, w))\n dist = [float(\"inf\")]*n\n dp = [0]*n\n dist[n-1] = 0\n dp[n-1] = 1\n min_heap = [(0, n-1)]\n while min_heap:\n w, u = heapq.heappop(min_heap)\n if w > dist[u]:\n continue\n for v, d in adj[u]:\n if w+d < dist[v]:\n dist[v] = w+d\n heapq.heappush(min_heap, (dist[v], v))\n elif w > dist[v]:\n dp[u] = (dp[u]+dp[v])%MOD\n if u == 0: # early return\n break\n return dp[0]\n"}} diff --git a/cp/cp-11154.jsonl b/cp/cp-11154.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..26655715abb4a2c7c18590833be932400495b841 --- /dev/null +++ b/cp/cp-11154.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11154", "name": "LeetCode 1787: Make The Xor Of All Segments Equal To Zero"} +{"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: Make the XOR of All Segments Equal to Zero (Difficulty: Hard)\nTags: Array, Dynamic Programming, Bit Manipulation\n\nYou are given an array nums​​​ and an integer k​​​​​. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right].\nReturn the minimum number of elements to change in the array such that the XOR of all segments of size k​​​​​​ is equal to zero.\n\nExample 1:\nInput: nums = [1,2,0,3,0], k = 1\nOutput: 3\nExplanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0].\n\nExample 2:\nInput: nums = [3,4,5,2,1,7,3,4,7], k = 3\nOutput: 3\nExplanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7].\n\nExample 3:\nInput: nums = [1,2,4,1,2,5,1,2,6], k = 3\nOutput: 3\nExplanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].\n\nConstraints:\n- 1 <= k <= nums.length <= 2000\n- ​​​​​​0 <= nums[i] < 210"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + k * m), m is the max number of nums\n# Space: O(min(k * m, n))\n\nimport collections\n\n\nclass Solution(object):\n def minChanges(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n def one_are_not_from_nums(nums, cnts):\n mxs = [cnts[i].most_common(1)[0][1] for i in range(k)]\n return len(nums) - (sum(mxs)-min(mxs))\n\n def all_are_from_nums(nums, cnts):\n dp = {0:0}\n for cnt in cnts:\n new_dp = collections.defaultdict(int)\n for x in dp.iterkeys():\n for y in cnt.iterkeys():\n new_dp[x^y] = max(new_dp[x^y], dp[x]+cnt[y])\n dp = new_dp\n return len(nums)-dp[0]\n \n cnts = [collections.Counter(nums[j] for j in range(i, len(nums), k)) for i in range(k)]\n return min(one_are_not_from_nums(nums, cnts), all_are_from_nums(nums, cnts))\n"}} diff --git a/cp/cp-11156.jsonl b/cp/cp-11156.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d7b0a905f41c3dc94173ed3c7596155e09a27fed --- /dev/null +++ b/cp/cp-11156.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11156", "name": "LeetCode 1790: Check If One String Swap Can Make Strings Equal"} +{"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: Check if One String Swap Can Make Strings Equal (Difficulty: Easy)\nTags: Hash Table, String, Counting\n\nYou are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.\nReturn true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.\n\nExample 1:\nInput: s1 = \"bank\", s2 = \"kanb\"\nOutput: true\nExplanation: For example, swap the first character with the last character of s2 to make \"bank\".\n\nExample 2:\nInput: s1 = \"attack\", s2 = \"defend\"\nOutput: false\nExplanation: It is impossible to make them equal with one string swap.\n\nExample 3:\nInput: s1 = \"kelb\", s2 = \"kelb\"\nOutput: true\nExplanation: The two strings are already equal, so no string swap operation is required.\n\nConstraints:\n- 1 <= s1.length, s2.length <= 100\n- s1.length == s2.length\n- s1 and s2 consist of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def areAlmostEqual(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: bool\n \"\"\"\n diff = []\n for a, b in itertools.izip(s1, s2):\n if a == b:\n continue\n if len(diff) == 2:\n return False\n diff.append([a, b] if not diff else [b, a])\n return not diff or (len(diff) == 2 and diff[0] == diff[1])\n"}} diff --git a/cp/cp-11158.jsonl b/cp/cp-11158.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..98de71045c027f06ecbaeb06a981321f35dade6f --- /dev/null +++ b/cp/cp-11158.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11158", "name": "LeetCode 1792: Maximum Average Pass Ratio"} +{"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 Pass Ratio (Difficulty: Medium)\nTags: Array, Greedy, Heap (Priority Queue)\n\nThere is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam.\nYou are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes.\nThe pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes.\nReturn the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.\n\nExample 1:\nInput: classes = [[1,2],[3,5],[2,2]], extraStudents = 2\nOutput: 0.78333\nExplanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.\n\nExample 2:\nInput: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4\nOutput: 0.53485\n\nConstraints:\n- 1 <= classes.length <= 10^5\n- classes[i].length == 2\n- 1 <= passi <= totali <= 10^5\n- 1 <= extraStudents <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + mlogn)\n# Space: O(n)\n\nimport heapq\n\n\nclass Solution(object):\n def maxAverageRatio(self, classes, extraStudents):\n \"\"\"\n :type classes: List[List[int]]\n :type extraStudents: int\n :rtype: float\n \"\"\"\n def profit(a, b):\n return float(a+1)/(b+1)-float(a)/b\n\n max_heap = [(-profit(a, b), a, b) for a, b in classes]\n heapq.heapify(max_heap)\n while extraStudents:\n v, a, b = heapq.heappop(max_heap)\n a, b = a+1, b+1\n heapq.heappush(max_heap, (-profit(a, b), a, b))\n extraStudents -= 1\n return sum(float(a)/b for v, a, b in max_heap)/len(classes)\n"}} diff --git a/cp/cp-11159.jsonl b/cp/cp-11159.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..45f2a82ca40372f204f958375011d3577ade75c2 --- /dev/null +++ b/cp/cp-11159.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11159", "name": "LeetCode 1793: Maximum Score Of A Good Subarray"} +{"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 Score of a Good Subarray (Difficulty: Hard)\nTags: Array, Two Pointers, Binary Search, Stack, Monotonic Stack\n\nYou are given an array of integers nums (0-indexed) and an integer k.\nThe score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.\nReturn the maximum possible score of a good subarray.\n\nExample 1:\nInput: nums = [1,4,3,7,4,5], k = 3\nOutput: 15\nExplanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15.\n\nExample 2:\nInput: nums = [5,5,4,5,4,1,1,1], k = 0\nOutput: 20\nExplanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i] <= 2 * 10^4\n- 0 <= k < nums.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def maximumScore(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n result = curr = nums[k]\n left = right = k\n while left-1 >= 0 or right+1 < len(nums):\n # choosing larger one to expand is always better than or equal to choosing smaller one\n if (nums[left-1] if left-1 >= 0 else 0) <= (nums[right+1] if right+1 < len(nums) else 0):\n right += 1\n else:\n left -= 1\n curr = min(curr, nums[left], nums[right])\n result = max(result, curr*(right-left+1))\n return result\n\n\n# Time: O(nlogn)\n# Space: O(n)\nimport bisect\n\n\nclass Solution2(object):\n def maximumScore(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n def score(nums, k):\n prefix = [nums[k]]*(k+1)\n for i in reversed(range(k)):\n prefix[i] = min(prefix[i+1], nums[i])\n result = right = nums[k]\n for j in range(k+1, len(nums)):\n right = min(right, nums[j])\n i = bisect.bisect_left(prefix, right)\n if i >= 0:\n result = max(result, right*(j-i+1))\n return result\n\n return max(score(nums, k), score(nums[::-1], len(nums)-1-k))\n \n"}} diff --git a/cp/cp-11161.jsonl b/cp/cp-11161.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f2c79d0074bb8f73c8e9fb410121594474903aef --- /dev/null +++ b/cp/cp-11161.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11161", "name": "LeetCode 1796: Second Largest Digit In A 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: Second Largest Digit in a String (Difficulty: Easy)\nTags: Hash Table, String\n\nGiven an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.\nAn alphanumeric string is a string consisting of lowercase English letters and digits.\n\nExample 1:\nInput: s = \"dfa12321afd\"\nOutput: 2\nExplanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.\n\nExample 2:\nInput: s = \"abc1111\"\nOutput: -1\nExplanation: The digits that appear in s are [1]. There is no second largest digit.\n\nConstraints:\n- 1 <= s.length <= 500\n- s consists of only lowercase English letters and digits."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def secondHighest(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n first = second = -1\n for c in s:\n if not c.isdigit():\n continue\n d = int(c)\n if d > first:\n first, second = d, first\n elif first > d > second:\n second = d\n return second\n"}} diff --git a/cp/cp-11162.jsonl b/cp/cp-11162.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f867e063f6503634677a0b39041486c17b5390d6 --- /dev/null +++ b/cp/cp-11162.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11162", "name": "LeetCode 1797: Design Authentication Manager"} +{"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 Authentication Manager (Difficulty: Medium)\nTags: Hash Table, Linked List, Design, Doubly-Linked List\n\nThere is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime. If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime.\nImplement the AuthenticationManager class:\nNote that if a token expires at time t, and another action happens on time t (renew or countUnexpiredTokens), the expiration takes place before the other actions.\n\nExample 1:\nInput\n[\"AuthenticationManager\", \"renew\", \"generate\", \"countUnexpiredTokens\", \"generate\", \"renew\", \"renew\", \"countUnexpiredTokens\"]\n[[5], [\"aaa\", 1], [\"aaa\", 2], [6], [\"bbb\", 7], [\"aaa\", 8], [\"bbb\", 10], [15]]\nOutput\n[null, null, null, 1, null, null, null, 0]\n\nExplanation\nAuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with timeToLive = 5 seconds.\nauthenticationManager.renew(\"aaa\", 1); // No token exists with tokenId \"aaa\" at time 1, so nothing happens.\nauthenticationManager.generate(\"aaa\", 2); // Generates a new token with tokenId \"aaa\" at time 2.\nauthenticationManager.countUnexpiredTokens(6); // The token with tokenId \"aaa\" is the only unexpired one at time 6, so return 1.\nauthenticationManager.generate(\"bbb\", 7); // Generates a new token with tokenId \"bbb\" at time 7.\nauthenticationManager.renew(\"aaa\", 8); // The token with tokenId \"aaa\" expired at time 7, and 8 >= 7, so at time 8 the renew request is ignored, and nothing happens.\nauthenticationManager.renew(\"bbb\", 10); // The token with tokenId \"bbb\" is unexpired at time 10, so the renew request is fulfilled and now the token will expire at time 15.\nauthenticationManager.countUnexpiredTokens(15); // The token with tokenId \"bbb\" expires at time 15, and the token with tokenId \"aaa\" expired at time 7, so currently no token is unexpired, so return 0.\n\nConstraints:\n- 1 <= timeToLive <= 10^8\n- 1 <= currentTime <= 10^8\n- 1 <= tokenId.length <= 5\n- tokenId consists only of lowercase letters.\n- All calls to generate will contain unique values of tokenId.\n- The values of currentTime across all the function calls will be strictly increasing.\n- At most 2000 calls will be made to all functions combined."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(1)\n# generate: O(1), amortized\n# renew: O(1), amortized\n# count: O(1), amortized\n# Space: O(n)\n\nimport collections\n\n\nclass AuthenticationManager(object):\n\n def __init__(self, timeToLive):\n \"\"\"\n :type timeToLive: int\n \"\"\"\n self.__time = timeToLive\n self.__lookup = collections.OrderedDict()\n\n def __evict(self, currentTime):\n while self.__lookup and next(self.__lookup.itervalues()) <= currentTime:\n self.__lookup.popitem(last=False)\n\n def generate(self, tokenId, currentTime):\n \"\"\"\n :type tokenId: str\n :type currentTime: int\n :rtype: None\n \"\"\"\n self.__evict(currentTime)\n self.__lookup[tokenId] = currentTime + self.__time\n\n\n def renew(self, tokenId, currentTime):\n \"\"\"\n :type tokenId: str\n :type currentTime: int\n :rtype: None\n \"\"\"\n self.__evict(currentTime) \n if tokenId not in self.__lookup:\n return\n del self.__lookup[tokenId]\n self.__lookup[tokenId] = currentTime + self.__time\n\n def countUnexpiredTokens(self, currentTime):\n \"\"\"\n :type currentTime: int\n :rtype: int\n \"\"\"\n self.__evict(currentTime)\n return len(self.__lookup)\n"}} diff --git a/cp/cp-11163.jsonl b/cp/cp-11163.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6730d51251e2c6ffe95135b364ebd7923a890d18 --- /dev/null +++ b/cp/cp-11163.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11163", "name": "LeetCode 1798: Maximum Number Of Consecutive Values You Can Make"} +{"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 Number of Consecutive Values You Can Make (Difficulty: Medium)\nTags: Array, Greedy, Sorting\n\nYou are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x.\nReturn the maximum number of consecutive integer values that you can make with your coins starting from and including 0.\nNote that you may have multiple coins of the same value.\n\nExample 1:\nInput: coins = [1,3]\nOutput: 2\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\nYou can make 2 consecutive integer values starting from 0.\n\nExample 2:\nInput: coins = [1,1,1,4]\nOutput: 8\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\n- 2: take [1,1]\n- 3: take [1,1,1]\n- 4: take [4]\n- 5: take [4,1]\n- 6: take [4,1,1]\n- 7: take [4,1,1,1]\nYou can make 8 consecutive integer values starting from 0.\n\nExample 3:\nInput: coins = [1,4,10,3,1]\nOutput: 20\n\nConstraints:\n- coins.length == n\n- 1 <= n <= 4 * 10^4\n- 1 <= coins[i] <= 4 * 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def getMaximumConsecutive(self, coins):\n \"\"\"\n :type coins: List[int]\n :rtype: int\n \"\"\"\n coins.sort()\n result = 1\n for c in coins:\n if c > result:\n break\n result += c\n return result\n"}} diff --git a/cp/cp-11164.jsonl b/cp/cp-11164.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2d056109ece963bd8fb9c620745eca35a7fecba9 --- /dev/null +++ b/cp/cp-11164.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11164", "name": "LeetCode 1799: Maximize Score After N Operations"} +{"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: Maximize Score After N Operations (Difficulty: Hard)\nTags: Array, Math, Dynamic Programming, Backtracking, Bit Manipulation, Number Theory, Bitmask\n\nYou are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array.\nIn the ith operation (1-indexed), you will:\nReturn the maximum score you can receive after performing n operations.\nThe function gcd(x, y) is the greatest common divisor of x and y.\n\nExample 1:\nInput: nums = [1,2]\nOutput: 1\nExplanation: The optimal choice of operations is:\n(1 * gcd(1, 2)) = 1\n\nExample 2:\nInput: nums = [3,4,6,8]\nOutput: 11\nExplanation: The optimal choice of operations is:\n(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11\n\nExample 3:\nInput: nums = [1,2,3,4,5,6]\nOutput: 14\nExplanation: The optimal choice of operations is:\n(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14\n\nConstraints:\n- 1 <= n <= 7\n- nums.length == 2 * n\n- 1 <= nums[i] <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2 * 2^n)\n# Space: O(2^n)\n\nimport itertools\nfrom fractions import gcd\n\n\nclass Solution(object):\n def maxScore(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def popcount(n):\n count = 0\n while n:\n n &= n-1\n count += 1\n return count\n\n def bits(mask):\n result = []\n i = 0\n while mask:\n if mask&1:\n result.append(i)\n i += 1\n mask >>= 1\n return result\n \n dp = [0]*(2**len(nums))\n for mask in range(3, len(dp)):\n cnt = popcount(mask)\n if cnt%2:\n continue\n for i, j in itertools.combinations(bits(mask), 2): # Time: O(n^2)\n dp[mask] = max(dp[mask], cnt//2*gcd(nums[i], nums[j]) + dp[mask^(1<= 0, and -x otherwise.\n\nExample 1:\nInput: n = 4, index = 2, maxSum = 6\nOutput: 2\nExplanation: nums = [1,2,2,1] is one array that satisfies all the conditions.\nThere are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].\n\nExample 2:\nInput: n = 6, index = 1, maxSum = 10\nOutput: 3\n\nConstraints:\n- 1 <= n <= maxSum <= 10^9\n- 0 <= index < n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logm)\n# Space: O(1)\n\nclass Solution(object):\n def maxValue(self, n, index, maxSum):\n \"\"\"\n :type n: int\n :type index: int\n :type maxSum: int\n :rtype: int\n \"\"\"\n def check(n, index, maxSum, x):\n y = max(x-index, 0)\n total = (x+y)*(x-y+1)//2\n y = max(x-((n-1)-index), 0)\n total += (x+y)*(x-y+1)//2\n return total-x <= maxSum\n\n maxSum -= n\n left, right = 0, maxSum\n while left <= right:\n mid = left + (right-left)//2\n if not check(n, index, maxSum, mid):\n right = mid-1\n else:\n left = mid+1\n return 1+right\n"}} diff --git a/cp/cp-11168.jsonl b/cp/cp-11168.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c0488f4db34fd93534795ef69aefec3a638a8444 --- /dev/null +++ b/cp/cp-11168.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11168", "name": "LeetCode 1803: Count Pairs With Xor In A Range"} +{"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: Count Pairs With XOR in a Range (Difficulty: Hard)\nTags: Array, Bit Manipulation, Trie\n\nGiven a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs.\nA nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= high.\n\nExample 1:\nInput: nums = [1,4,2,7], low = 2, high = 6\r\nOutput: 6\r\nExplanation: All nice pairs (i, j) are as follows:\r\n - (0, 1): nums[0] XOR nums[1] = 5 \r\n - (0, 2): nums[0] XOR nums[2] = 3\r\n - (0, 3): nums[0] XOR nums[3] = 6\r\n - (1, 2): nums[1] XOR nums[2] = 6\r\n - (1, 3): nums[1] XOR nums[3] = 3\r\n - (2, 3): nums[2] XOR nums[3] = 5\n\nExample 2:\nInput: nums = [9,8,4,2,1], low = 5, high = 14\r\nOutput: 8\r\nExplanation: All nice pairs (i, j) are as follows:\r\n​​​​​ - (0, 2): nums[0] XOR nums[2] = 13\r\n  - (0, 3): nums[0] XOR nums[3] = 11\r\n  - (0, 4): nums[0] XOR nums[4] = 8\r\n  - (1, 2): nums[1] XOR nums[2] = 12\r\n  - (1, 3): nums[1] XOR nums[3] = 10\r\n  - (1, 4): nums[1] XOR nums[4] = 9\r\n  - (2, 3): nums[2] XOR nums[3] = 6\r\n  - (2, 4): nums[2] XOR nums[4] = 5\n\nConstraints:\n- 1 <= nums.length <= 2 * 10^4\n- 1 <= nums[i] <= 2 * 10^4\n- 1 <= low <= high <= 2 * 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\n# dp solution\nclass Solution(object):\n def countPairs(self, nums, low, high):\n \"\"\"\n :type nums: List[int]\n :type low: int\n :type high: int\n :rtype: int\n \"\"\"\n def count(nums, x):\n result = 0\n dp = collections.Counter(nums)\n while x:\n if x&1:\n result += sum(dp[(x^1)^k]*dp[k] for k in dp.iterkeys())//2 # current limit is xxxxx1*****, count xor pair with xxxxx0***** pattern\n dp = collections.Counter({k>>1: dp[k]+dp[k^1] for k in dp.iterkeys()})\n x >>= 1\n return result\n \n return count(nums, high+1)-count(nums, low)\n\n\n# Time: O(n)\n# Space: O(n)\n# trie solution\nclass Trie(object):\n def __init__(self):\n self.__root = {}\n \n def insert(self, num):\n node = self.__root\n for i in reversed(range(32)):\n curr = (num>>i) & 1\n if curr not in node:\n node[curr] = {\"_count\":0}\n node = node[curr]\n node[\"_count\"] += 1\n \n def query(self, num, limit):\n node, result = self.__root, 0\n for i in reversed(range(32)):\n curr = (num>>i) & 1\n bit = (limit>>i) & 1\n if bit:\n if curr in node:\n result += node[0^curr][\"_count\"] # current limit is xxxxx1*****, count xor pair with xxxxx0***** pattern\n if bit^curr not in node:\n break\n node = node[bit^curr]\n return result\n\n\nclass Solution2(object):\n def countPairs(self, nums, low, high):\n \"\"\"\n :type nums: List[int]\n :type low: int\n :type high: int\n :rtype: int\n \"\"\"\n result = 0\n trie = Trie()\n for x in nums:\n result += trie.query(x, high+1)-trie.query(x, low)\n trie.insert(x)\n return result\n"}} diff --git a/cp/cp-11170.jsonl b/cp/cp-11170.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..61e3e54f7330ea3d91a16bd49bda80f63fe2dda0 --- /dev/null +++ b/cp/cp-11170.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11170", "name": "LeetCode 1805: Number Of Different Integers In A 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: Number of Different Integers in a String (Difficulty: Easy)\nTags: Hash Table, String\n\nYou are given a string word that consists of digits and lowercase English letters.\nYou will replace every non-digit character with a space. For example, \"a123bc34d8ef34\" will become \" 123  34 8  34\". Notice that you are left with some integers that are separated by at least one space: \"123\", \"34\", \"8\", and \"34\".\nReturn the number of different integers after performing the replacement operations on word.\nTwo integers are considered different if their decimal representations without any leading zeros are different.\n\nExample 1:\nInput: word = \"a123bc34d8ef34\"\nOutput: 3\nExplanation: The three different integers are \"123\", \"34\", and \"8\". Notice that \"34\" is only counted once.\n\nExample 2:\nInput: word = \"leet1234code234\"\nOutput: 2\n\nExample 3:\nInput: word = \"a1b01c001\"\nOutput: 1\nExplanation: The three integers \"1\", \"01\", and \"001\" all represent the same integer because\nthe leading zeros are ignored when comparing their decimal values.\n\nConstraints:\n- 1 <= word.length <= 1000\n- word consists of digits and lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def numDifferentIntegers(self, word):\n \"\"\"\n :type word: str\n :rtype: int\n \"\"\"\n result, num = set(), None\n for i in range(len(word)+1):\n c = word[i] if i < len(word) else ' '\n if c.isdigit():\n num = 10*num+int(c) if num is not None else int(c)\n elif num is not None:\n result.add(num)\n num = None\n return len(result)\n"}} diff --git a/cp/cp-11171.jsonl b/cp/cp-11171.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c1e2f252d283a73e4c5b95e6053d6f10032cc723 --- /dev/null +++ b/cp/cp-11171.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11171", "name": "LeetCode 1806: Minimum Number Of Operations To Reinitialize A Permutation"} +{"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: Minimum Number of Operations to Reinitialize a Permutation (Difficulty: Medium)\nTags: Array, Math, Simulation\n\nYou are given an even integer n​​​​​​. You initially have a permutation perm of size n​​ where perm[i] == i​ (0-indexed)​​​​.\nIn one operation, you will create a new array arr, and for each i:\nYou will then assign arr​​​​ to perm.\nReturn the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value.\n\nExample 1:\nInput: n = 2\nOutput: 1\nExplanation: perm = [0,1] initially.\nAfter the 1st operation, perm = [0,1]\nSo it takes only 1 operation.\n\nExample 2:\nInput: n = 4\nOutput: 2\nExplanation: perm = [0,1,2,3] initially.\nAfter the 1st operation, perm = [0,2,1,3]\nAfter the 2nd operation, perm = [0,1,2,3]\nSo it takes only 2 operations.\n\nExample 3:\nInput: n = 6\nOutput: 4\n\nConstraints:\n- 2 <= n <= 1000\n- n​​​​​​ is even."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(sqrt(n))\n# Space: O(sqrt(n))\n\nclass Solution(object):\n def reinitializePermutation(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n # reference: https://cp-algorithms.com/algebra/discrete-log.html\n def discrete_log(a, b, m):\n a %= m\n b %= m\n n = int(m**0.5)+1\n an = pow(a, n, m)\n vals = {}\n curr = b\n for q in range(n+1):\n vals[curr] = q\n curr = curr*a % m\n curr = 1\n for p in range(1, n+1):\n curr = curr*an % m\n if curr in vals:\n return n*p-vals[curr]\n return -1\n\n return 1+discrete_log(2, n//2, n-1) # find min x s.t. 2^x mod (n-1) = n/2, result is x + 1\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def reinitializePermutation(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n == 2:\n return 1\n result, i = 0, 1\n while not result or i != 1:\n i = (i*2)%(n-1)\n result += 1\n return result\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution3(object):\n def reinitializePermutation(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n result, i = 0, 1\n while not result or i != 1: # find cycle length\n i = (i//2 if not i%2 else n//2+(i-1)//2)\n result += 1\n return result\n"}} diff --git a/cp/cp-11172.jsonl b/cp/cp-11172.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..53c0899604e207c891f6d86138e2824ada615812 --- /dev/null +++ b/cp/cp-11172.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11172", "name": "LeetCode 1807: Evaluate The Bracket Pairs Of A 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: Evaluate the Bracket Pairs of a String (Difficulty: Medium)\nTags: Array, Hash Table, String\n\nYou are given a string s that contains some bracket pairs, with each pair containing a non-empty key.\nYou know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei.\nYou are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will:\nEach key will appear at most once in your knowledge. There will not be any nested brackets in s.\nReturn the resulting string after evaluating all of the bracket pairs.\n\nExample 1:\nInput: s = \"(name)is(age)yearsold\", knowledge = [[\"name\",\"bob\"],[\"age\",\"two\"]]\nOutput: \"bobistwoyearsold\"\nExplanation:\nThe key \"name\" has a value of \"bob\", so replace \"(name)\" with \"bob\".\nThe key \"age\" has a value of \"two\", so replace \"(age)\" with \"two\".\n\nExample 2:\nInput: s = \"hi(name)\", knowledge = [[\"a\",\"b\"]]\nOutput: \"hi?\"\nExplanation: As you do not know the value of the key \"name\", replace \"(name)\" with \"?\".\n\nExample 3:\nInput: s = \"(a)(a)(a)aaa\", knowledge = [[\"a\",\"yes\"]]\nOutput: \"yesyesyesaaa\"\nExplanation: The same key can appear multiple times.\nThe key \"a\" has a value of \"yes\", so replace all occurrences of \"(a)\" with \"yes\".\nNotice that the \"a\"s not in a bracket pair are not evaluated.\n\nConstraints:\n- 1 <= s.length <= 10^5\n- 0 <= knowledge.length <= 10^5\n- knowledge[i].length == 2\n- 1 <= keyi.length, valuei.length <= 10\n- s consists of lowercase English letters and round brackets '(' and ')'.\n- Every open bracket '(' in s will have a corresponding close bracket ')'.\n- The key in each bracket pair of s will be non-empty.\n- There will not be any nested bracket pairs in s.\n- keyi and valuei consist of lowercase English letters.\n- Each keyi in knowledge is unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + m)\n# Space: O(n + m)\n\nclass Solution(object):\n def evaluate(self, s, knowledge):\n \"\"\"\n :type s: str\n :type knowledge: List[List[str]]\n :rtype: str\n \"\"\"\n lookup = {k: v for k, v in knowledge}\n result, curr = [], []\n has_pair = False\n for c in s:\n if c == '(':\n has_pair = True\n elif c == ')':\n has_pair = False\n result.append(lookup.get(\"\".join(curr), '?'))\n curr = []\n elif has_pair:\n curr.append(c)\n else:\n result.append(c)\n return \"\".join(result)\n"}} diff --git a/cp/cp-11173.jsonl b/cp/cp-11173.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0b2e8719f5e306f58fceae4a9b77e53fb04b4d87 --- /dev/null +++ b/cp/cp-11173.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11173", "name": "LeetCode 1808: Maximize Number Of Nice Divisors"} +{"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: Maximize Number of Nice Divisors (Difficulty: Hard)\nTags: Math, Recursion, Number Theory\n\nYou are given a positive integer primeFactors. You are asked to construct a positive integer n that satisfies the following conditions:\nReturn the number of nice divisors of n. Since that number can be too large, return it modulo 109 + 7.\nNote that a prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. The prime factors of a number n is a list of prime numbers such that their product equals n.\n\nExample 1:\nInput: primeFactors = 5\r\nOutput: 6\r\nExplanation: 200 is a valid value of n.\r\nIt has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].\r\nThere is not other value of n that has at most 5 prime factors and more nice divisors.\n\nExample 2:\nInput: primeFactors = 8\r\nOutput: 18\n\nConstraints:\n- 1 <= primeFactors <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\n# variant of \"343. integer break\"\nclass Solution(object):\n def maxNiceDivisors(self, primeFactors):\n \"\"\"\n :type primeFactors: int\n :rtype: int\n \"\"\"\n # given a1 + a2 + ... + ak <= n, find max of a1 * a2 * ... * ak \n # => given a1 + a2 + ... + ak = n, find max of a1 * a2 * ... * ak \n # => ai is either 3 or 2, see proof in \"343. integer break\"\n MOD = 10**9 + 7\n if primeFactors <= 3:\n return primeFactors\n if primeFactors % 3 == 0: # 6 => 3*3\n return pow(3, primeFactors//3, MOD)\n if primeFactors % 3 == 1: # 4 => 2*2 \n return (2*2*pow(3, (primeFactors-4)//3, MOD)) % MOD\n return (2*pow(3, (primeFactors-2)//3, MOD)) % MOD # 5 => 2*3\n"}} diff --git a/cp/cp-11176.jsonl b/cp/cp-11176.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4e1dc44999e9444882f3d0bf8625d68fe96a62b1 --- /dev/null +++ b/cp/cp-11176.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11176", "name": "LeetCode 1813: Sentence Similarity 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: Sentence Similarity III (Difficulty: Medium)\nTags: Array, Two Pointers, String\n\nYou are given two strings sentence1 and sentence2, each representing a sentence composed of words. A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of only uppercase and lowercase English characters.\nTwo sentences s1 and s2 are considered similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. Note that the inserted sentence must be separated from existing words by spaces.\nFor example,\nGiven two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false.\n\nExample 1:\nInput: sentence1 = \"My name is Haley\", sentence2 = \"My Haley\"\nOutput: true\nExplanation:\nsentence2 can be turned to sentence1 by inserting \"name is\" between \"My\" and \"Haley\".\n\nExample 2:\nInput: sentence1 = \"of\", sentence2 = \"A lot of words\"\nOutput: false\nExplanation:\nNo single sentence can be inserted inside one of the sentences to make it equal to the other.\n\nExample 3:\nInput: sentence1 = \"Eating right now\", sentence2 = \"Eating\"\nOutput: true\nExplanation:\nsentence2 can be turned to sentence1 by inserting \"right now\" at the end of the sentence.\n\nConstraints:\n- 1 <= sentence1.length, sentence2.length <= 100\n- sentence1 and sentence2 consist of lowercase and uppercase English letters and spaces.\n- The words in sentence1 and sentence2 are separated by a single space."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def areSentencesSimilar(self, sentence1, sentence2):\n \"\"\"\n :type sentence1: str\n :type sentence2: str\n :rtype: bool\n \"\"\"\n if len(sentence1) > len(sentence2):\n sentence1, sentence2 = sentence2, sentence1\n count = 0\n for idx in (lambda x:x, lambda x:-1-x):\n for i in range(len(sentence1)+1):\n c1 = sentence1[idx(i)] if i != len(sentence1) else ' '\n c2 = sentence2[idx(i)] if i != len(sentence2) else ' '\n if c1 != c2:\n break\n if c1 == ' ':\n count += 1\n return count >= sentence1.count(' ')+1\n"}} diff --git a/cp/cp-11177.jsonl b/cp/cp-11177.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd277bcea2c754def2a62d03dff5597f7c7e3e1b --- /dev/null +++ b/cp/cp-11177.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11177", "name": "LeetCode 1814: Count Nice Pairs In An 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: Count Nice Pairs in an Array (Difficulty: Medium)\nTags: Array, Hash Table, Math, Counting\n\nYou are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions:\nReturn the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: nums = [42,11,1,97]\nOutput: 2\nExplanation: The two pairs are:\n - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.\n - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.\n\nExample 2:\nInput: nums = [13,10,35,24,76]\nOutput: 4\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 0 <= nums[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogm), m is max of nums\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def countNicePairs(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n MOD = 10**9 + 7\n\n def rev(x):\n result = 0\n while x:\n x, r = divmod(x, 10)\n result = result*10+r\n return result\n \n result = 0\n lookup = collections.defaultdict(int)\n for num in nums:\n result = (result + lookup[num-rev(num)])%MOD\n lookup[num-rev(num)] += 1\n return result\n"}} diff --git a/cp/cp-11178.jsonl b/cp/cp-11178.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a681ca2487a3f9a17d5e7b8564d6461f72f5948b --- /dev/null +++ b/cp/cp-11178.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11178", "name": "LeetCode 1815: Maximum Number Of Groups Getting Fresh Donuts"} +{"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 Number of Groups Getting Fresh Donuts (Difficulty: Hard)\nTags: Array, Dynamic Programming, Bit Manipulation, Memoization, Bitmask\n\nThere is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize and an integer array groups, where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut.\nWhen a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.\nYou can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.\n\nExample 1:\nInput: batchSize = 3, groups = [1,2,3,4,5,6]\nOutput: 4\nExplanation: You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy.\n\nExample 2:\nInput: batchSize = 4, groups = [1,3,2,5,2,2,1,6]\nOutput: 4\n\nConstraints:\n- 1 <= batchSize <= 9\n- 1 <= groups.length <= 30\n- 1 <= groups[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((b/2) * (n/(b/2)+1)^(b/2))\n# Space: O((n/(b/2)+1)^(b/2))\n\n# greedy + memoization solution\nclass Solution(object):\n def maxHappyGroups(self, batchSize, groups):\n \"\"\"\n :type batchSize: int\n :type groups: List[int]\n :rtype: int\n \"\"\"\n def memoization(batchSize, count, mask, remain, lookup):\n if lookup[mask] == 0:\n a_remain = 0\n if remain in count:\n curr, basis = mask, 1\n for i, c in count.iteritems():\n if i == remain:\n break\n basis *= c+1\n curr //= c+1\n a_remain = curr%(count[remain]+1)\n result = 0\n if a_remain:\n result = max(result, int(remain == 0) + memoization(batchSize, count, mask-basis, 0, lookup))\n else:\n curr, basis = mask, 1\n for i, c in count.iteritems():\n if curr%(c+1):\n result = max(result, int(remain == 0) + memoization(batchSize, count, mask-basis, (remain-i)%batchSize, lookup))\n basis *= c+1\n curr //= c+1\n lookup[mask] = result\n return lookup[mask]\n \n count = [0]*batchSize\n for i in groups:\n count[i%len(count)] += 1\n result = count[0]\n count[0] = 0\n for i in range(1, len(count)//2+1): # optimization\n pair_count = min(count[i], count[len(count)-i]) if 2*i != len(count) else count[i]//2\n result += pair_count\n count[i] -= pair_count\n count[len(count)-i] -= pair_count\n new_count = {i:c for i, c in enumerate(count) if c}\n max_mask = reduce(lambda total, c: total*(c+1), new_count.itervalues(), 1)\n lookup = [0]*max_mask\n return result+memoization(batchSize, new_count, max_mask-1, 0, lookup)\n\n\n# Time: O((b/2) * (n/(b/2)+1)^(b/2))\n# Space: O((n/(b/2)+1)^(b/2))\n# dp solution\nclass Solution2(object):\n def maxHappyGroups(self, batchSize, groups):\n \"\"\"\n :type batchSize: int\n :type groups: List[int]\n :rtype: int\n \"\"\"\n count = [0]*batchSize\n for i in groups:\n count[i%len(count)] += 1\n result = count[0]\n count[0] = 0\n for i in range(1, len(count)//2+1): # optimization\n pair_count = min(count[i], count[len(count)-i]) if 2*i != len(count) else count[i]//2\n result += pair_count\n count[i] -= pair_count\n count[len(count)-i] -= pair_count\n new_count = {i:c for i, c in enumerate(count) if c}\n max_mask = reduce(lambda total, c: total*(c+1), new_count.itervalues(), 1)\n dp = [0]*max_mask\n for mask in range(len(dp)):\n remain = 0\n curr, basis = mask, 1\n for i, c in new_count.iteritems():\n ai = curr%(c+1)\n if ai:\n dp[mask] = max(dp[mask], dp[mask-basis])\n remain = (remain+ai*i)%batchSize\n basis *= c+1\n curr //= c+1\n if mask != len(dp)-1 and remain == 0:\n dp[mask] += 1\n return result+dp[-1]\n"}} diff --git a/cp/cp-11179.jsonl b/cp/cp-11179.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..36860aa0b483824be2c61ad430a8f9a497afa9a9 --- /dev/null +++ b/cp/cp-11179.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11179", "name": "LeetCode 1816: Truncate Sentence"} +{"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: Truncate Sentence (Difficulty: Easy)\nTags: Array, String\n\nA sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).\nYou are given a sentence s​​​​​​ and an integer k​​​​​​. You want to truncate s​​​​​​ such that it contains only the first k​​​​​​ words. Return s​​​​​​ after truncating it.\n\nExample 1:\nInput: s = \"Hello how are you Contestant\", k = 4\nOutput: \"Hello how are you\"\nExplanation:\nThe words in s are [\"Hello\", \"how\" \"are\", \"you\", \"Contestant\"].\nThe first 4 words are [\"Hello\", \"how\", \"are\", \"you\"].\nHence, you should return \"Hello how are you\".\n\nExample 2:\nInput: s = \"What is the solution to this problem\", k = 4\nOutput: \"What is the solution\"\nExplanation:\nThe words in s are [\"What\", \"is\" \"the\", \"solution\", \"to\", \"this\", \"problem\"].\nThe first 4 words are [\"What\", \"is\", \"the\", \"solution\"].\nHence, you should return \"What is the solution\".\n\nExample 3:\nInput: s = \"chopper is not a tanuki\", k = 5\nOutput: \"chopper is not a tanuki\"\n\nConstraints:\n- 1 <= s.length <= 500\n- k is in the range [1, the number of words in s].\n- s consist of only lowercase and uppercase English letters and spaces.\n- The words in s are separated by a single space.\n- There are no leading or trailing spaces."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def truncateSentence(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n for i in range(len(s)):\n if s[i] == ' ':\n k -= 1\n if not k:\n return s[:i]\n return s\n"}} diff --git a/cp/cp-11180.jsonl b/cp/cp-11180.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..68459e5c2cef84df0c59eca338a7767768ca5764 --- /dev/null +++ b/cp/cp-11180.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11180", "name": "LeetCode 1817: Finding The Users Active Minutes"} +{"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: Finding the Users Active Minutes (Difficulty: Medium)\nTags: Array, Hash Table\n\nYou are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei.\nMultiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute.\nThe user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it.\nYou are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] is the number of users whose UAM equals j.\nReturn the array answer as described above.\n\nExample 1:\nInput: logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5\nOutput: [0,2,0,0,0]\nExplanation:\nThe user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).\nThe user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nSince both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.\n\nExample 2:\nInput: logs = [[1,1],[2,2],[2,3]], k = 4\nOutput: [1,1,0,0]\nExplanation:\nThe user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.\nThe user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nThere is one user with a UAM of 1 and one with a UAM of 2.\nHence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.\n\nConstraints:\n- 1 <= logs.length <= 10^4\n- 0 <= IDi <= 10^9\n- 1 <= timei <= 10^5\n- k is in the range [The maximum UAM for a user, 105]."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def findingUsersActiveMinutes(self, logs, k):\n \"\"\"\n :type logs: List[List[int]]\n :type k: int\n :rtype: List[int]\n \"\"\"\n lookup = collections.defaultdict(set)\n for u, t in logs:\n lookup[u].add(t)\n result = [0]*k\n for _, ts in lookup.iteritems():\n result[len(ts)-1] += 1\n return result\n"}} diff --git a/cp/cp-11181.jsonl b/cp/cp-11181.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..feb5991454ff3927e03ed6c0cbc935670720aeb0 --- /dev/null +++ b/cp/cp-11181.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11181", "name": "LeetCode 1818: Minimum Absolute Sum Difference"} +{"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: Minimum Absolute Sum Difference (Difficulty: Medium)\nTags: Array, Binary Search, Sorting, Ordered Set\n\nYou are given two positive integer arrays nums1 and nums2, both of length n.\nThe absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed).\nYou can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.\nReturn the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 109 + 7.\n|x| is defined as:\n\nExample 1:\nInput: nums1 = [1,7,5], nums2 = [2,3,5]\nOutput: 3\nExplanation: There are two possible optimal solutions:\n- Replace the second element with the first: [1,7,5] => [1,1,5], or\n- Replace the second element with the third: [1,7,5] => [1,5,5].\nBoth will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3.\n\nExample 2:\nInput: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]\nOutput: 0\nExplanation: nums1 is equal to nums2 so no replacement is needed. This will result in an \nabsolute sum difference of 0.\n\nExample 3:\nInput: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]\nOutput: 20\nExplanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].\nThis yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20\n\nConstraints:\n- n == nums1.length\n- n == nums2.length\n- 1 <= n <= 10^5\n- 1 <= nums1[i], nums2[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport bisect\n\n\nclass Solution(object):\n def minAbsoluteSumDiff(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n\n sorted_nums1 = sorted(nums1)\n result = max_change = 0\n for i in range(len(nums2)):\n diff = abs(nums1[i]-nums2[i])\n result = (result+diff)%MOD\n if diff < max_change:\n continue\n j = bisect.bisect_left(sorted_nums1, nums2[i])\n if j != len(sorted_nums1):\n max_change = max(max_change, diff-abs(sorted_nums1[j]-nums2[i]))\n if j != 0:\n max_change = max(max_change, diff-abs(sorted_nums1[j-1]-nums2[i]))\n return (result-max_change)%MOD\n"}} diff --git a/cp/cp-11182.jsonl b/cp/cp-11182.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..22000b1a135fd6a42056c7b59af61d398ac333a5 --- /dev/null +++ b/cp/cp-11182.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11182", "name": "LeetCode 1819: Number Of Different Subsequences Gcds"} +{"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 Different Subsequences GCDs (Difficulty: Hard)\nTags: Array, Math, Counting, Number Theory\n\nYou are given an array nums that consists of positive integers.\nThe GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly.\nA subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.\nReturn the number of different GCDs among all non-empty subsequences of nums.\n\nExample 1:\nInput: nums = [6,10,3]\nOutput: 5\nExplanation: The figure shows all the non-empty subsequences and their GCDs.\nThe different GCDs are 6, 10, 3, 2, and 1.\n\nExample 2:\nInput: nums = [5,15,40,5,6]\nOutput: 7\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i] <= 2 * 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + m * (1 + 1/2 + 1/3 + ... + 1/m)) = O(n + mlogm), m is max of nums\n# Space: O(n)\n\nimport fractions\n\n\nclass Solution(object):\n def countDifferentSubsequenceGCDs(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n max_num, nums_set = max(nums), set(nums)\n result = 0\n for i in range(1, max_num+1):\n d = 0\n for x in range(i, max_num+1, i):\n if x not in nums_set:\n continue\n d = fractions.gcd(d, x) # total time: O(log(min(d, x)) = O(logd), where d keeps the same or gets smaller\n if d == i:\n result += 1\n break\n return result\n"}} diff --git a/cp/cp-11184.jsonl b/cp/cp-11184.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a2cbde566f90cafce520a1dee203052c4865d8b0 --- /dev/null +++ b/cp/cp-11184.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11184", "name": "LeetCode 1822: Sign Of The Product Of An 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: Sign of the Product of an Array (Difficulty: Easy)\nTags: Array, Math\n\nImplement a function signFunc(x) that returns:\nYou are given an integer array nums. Let product be the product of all values in the array nums.\nReturn signFunc(product).\n\nExample 1:\nInput: nums = [-1,-2,-3,-4,3,2,1]\nOutput: 1\nExplanation: The product of all values in the array is 144, and signFunc(144) = 1\n\nExample 2:\nInput: nums = [1,5,0,2,-3]\nOutput: 0\nExplanation: The product of all values in the array is 0, and signFunc(0) = 0\n\nExample 3:\nInput: nums = [-1,1,-1,1,-1]\nOutput: -1\nExplanation: The product of all values in the array is -1, and signFunc(-1) = -1\n\nConstraints:\n- 1 <= nums.length <= 1000\n- -100 <= nums[i] <= 100"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def arraySign(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n flag = 0\n for x in nums:\n if not x:\n return 0\n if x < 0:\n flag ^= 1\n return -1 if flag else 1\n"}} diff --git a/cp/cp-11185.jsonl b/cp/cp-11185.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..acc959bc1fa4344159f98f1649ede882fd2dd2fa --- /dev/null +++ b/cp/cp-11185.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11185", "name": "LeetCode 1823: Find The Winner Of The Circular Game"} +{"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 the Winner of the Circular Game (Difficulty: Medium)\nTags: Array, Math, Recursion, Queue, Simulation\n\nThere are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.\nThe rules of the game are as follows:\nGiven the number of friends, n, and an integer k, return the winner of the game.\nFollow up:\nCould you solve this problem in linear time with constant space?\n\nExample 1:\nInput: n = 5, k = 2\nOutput: 3\nExplanation: Here are the steps of the game:\n1) Start at friend 1.\n2) Count 2 friends clockwise, which are friends 1 and 2.\n3) Friend 2 leaves the circle. Next start is friend 3.\n4) Count 2 friends clockwise, which are friends 3 and 4.\n5) Friend 4 leaves the circle. Next start is friend 5.\n6) Count 2 friends clockwise, which are friends 5 and 1.\n7) Friend 1 leaves the circle. Next start is friend 3.\n8) Count 2 friends clockwise, which are friends 3 and 5.\n9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.\n\nExample 2:\nInput: n = 6, k = 5\nOutput: 1\nExplanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.\n\nConstraints:\n- 1 <= k <= n <= 500"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# bottom-up solution\nclass Solution(object):\n def findTheWinner(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n return reduce(lambda idx, n:(idx+k)%(n+1), range(1, n), 0)+1\n\n\n# Time: O(n)\n# Space: O(n)\n# top-down solution\nclass Solution2(object):\n def findTheWinner(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n def f(idx, n, k):\n if n == 1:\n return 0\n return (k+f((idx+k)%n, n-1, k))%n\n \n return f(0, n, k)+1\n"}} diff --git a/cp/cp-11186.jsonl b/cp/cp-11186.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f32c587467b7f26c82b63b7e43f1a967fff51b59 --- /dev/null +++ b/cp/cp-11186.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11186", "name": "LeetCode 1824: Minimum Sideway Jumps"} +{"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: Minimum Sideway Jumps (Difficulty: Medium)\nTags: Array, Dynamic Programming, Greedy\n\nThere is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way.\nYou are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no obstacles at point i. There will be at most one obstacle in the 3 lanes at each point.\nThe frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane.\nReturn the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0.\nNote: There will be no obstacles on points 0 and n.\n\nExample 1:\nInput: obstacles = [0,1,2,3,0]\nOutput: 2 \nExplanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).\nNote that the frog can jump over obstacles only when making side jumps (as shown at point 2).\n\nExample 2:\nInput: obstacles = [0,1,1,3,3,0]\nOutput: 0\nExplanation: There are no obstacles on lane 2. No side jumps are required.\n\nExample 3:\nInput: obstacles = [0,2,1,0,3,0]\nOutput: 2\nExplanation: The optimal solution is shown by the arrows above. There are 2 side jumps.\n\nConstraints:\n- obstacles.length == n + 1\n- 1 <= n <= 5 * 10^5\n- 0 <= obstacles[i] <= 3\n- obstacles[0] == obstacles[n] == 0"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# greedy solution\nclass Solution(object):\n def minSideJumps(self, obstacles):\n \"\"\"\n :type obstacles: List[int]\n :rtype: int\n \"\"\"\n result, lanes = 0, set([2])\n for i in range(len(obstacles)-1):\n lanes.discard(obstacles[i+1])\n if lanes:\n continue\n result += 1\n lanes = set(j for j in range(1, 4) if j not in [obstacles[i], obstacles[i+1]])\n return result\n\n \n# Time: O(n)\n# Space: O(1)\n# dp solution\nclass Solution2(object):\n def minSideJumps(self, obstacles):\n \"\"\"\n :type obstacles: List[int]\n :rtype: int\n \"\"\"\n dp = [1, 0, 1] \n for i in obstacles:\n if i:\n dp[i-1] = float(\"inf\")\n for j in range(3):\n if j+1 != i:\n dp[j] = min(dp[0]+(j != 0), dp[1]+(j != 1), dp[2]+(j != 2))\n return min(dp)\n"}} diff --git a/cp/cp-11187.jsonl b/cp/cp-11187.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b93a1ed971f88fb0a1116b7610e63b5d3687f3ff --- /dev/null +++ b/cp/cp-11187.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11187", "name": "LeetCode 1825: Finding Mk Average"} +{"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: Finding MK Average (Difficulty: Hard)\nTags: Design, Queue, Heap (Priority Queue), Data Stream, Ordered Set\n\nYou are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream.\nThe MKAverage can be calculated using these steps:\nImplement the MKAverage class:\n\nExample 1:\nInput\n[\"MKAverage\", \"addElement\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"addElement\", \"addElement\", \"calculateMKAverage\"]\n[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]\nOutput\n[null, null, null, -1, null, 3, null, null, null, 5]\n\nExplanation\nMKAverage obj = new MKAverage(3, 1); \nobj.addElement(3); // current elements are [3]\nobj.addElement(1); // current elements are [3,1]\nobj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.\nobj.addElement(10); // current elements are [3,1,10]\nobj.calculateMKAverage(); // The last 3 elements are [3,1,10].\n // After removing smallest and largest 1 element the container will be [3].\n // The average of [3] equals 3/1 = 3, return 3\nobj.addElement(5); // current elements are [3,1,10,5]\nobj.addElement(5); // current elements are [3,1,10,5,5]\nobj.addElement(5); // current elements are [3,1,10,5,5,5]\nobj.calculateMKAverage(); // The last 3 elements are [5,5,5].\n // After removing smallest and largest 1 element the container will be [5].\n // The average of [5] equals 5/1 = 5, return 5\n\nConstraints:\n- 3 <= m <= 10^5\n- 1 < k*2 < m\n- 1 <= num <= 10^5\n- At most 105 calls will be made to addElement and calculateMKAverage."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(1)\n# add_element: O(logn)\n# calc_mkaverage: O(1)\n# Space: O(m)\n\nimport collections\nfrom sortedcontainers import SortedList\n\n\nclass MKAverage(object):\n\n def __init__(self, m, k):\n \"\"\"\n :type m: int\n :type k: int\n \"\"\"\n self.__m = m\n self.__k = k\n self.__dq = collections.deque()\n self.__sl = SortedList()\n self.__total = self.__first_k = self.__last_k = 0\n\n def addElement(self, num):\n \"\"\"\n :type num: int\n :rtype: None\n \"\"\"\n if len(self.__dq) == self.__m:\n self.__remove(self.__dq.popleft())\n self.__dq.append(num)\n self.__add(num)\n\n def calculateMKAverage(self):\n \"\"\"\n :rtype: int\n \"\"\"\n if len(self.__sl) < self.__m:\n return -1\n return (self.__total-self.__first_k-self.__last_k)//(self.__m-2*self.__k)\n\n def __add(self, num):\n self.__total += num\n idx = self.__sl.bisect_left(num)\n if idx < self.__k:\n self.__first_k += num\n if len(self.__sl) >= self.__k:\n self.__first_k -= self.__sl[self.__k-1]\n if idx > len(self.__sl)-self.__k:\n self.__last_k += num\n if len(self.__sl) >= self.__k:\n self.__last_k -= self.__sl[-self.__k]\n self.__sl.add(num)\n\n def __remove(self, num):\n self.__total -= num\n idx = self.__sl.index(num)\n if idx < self.__k:\n self.__first_k -= num\n self.__first_k += self.__sl[self.__k]\n elif idx > (len(self.__sl)-1)-self.__k:\n self.__last_k -= num\n self.__last_k += self.__sl[-1-self.__k]\n self.__sl.remove(num)\n"}} diff --git a/cp/cp-11189.jsonl b/cp/cp-11189.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..28685848c5ce413a2ced0dae49d012e34a03030a --- /dev/null +++ b/cp/cp-11189.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11189", "name": "LeetCode 1827: Minimum Operations To Make The Array Increasing"} +{"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: Minimum Operations to Make the Array Increasing (Difficulty: Easy)\nTags: Array, Greedy\n\nYou are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1.\nReturn the minimum number of operations needed to make nums strictly increasing.\nAn array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing.\n\nExample 1:\nInput: nums = [1,1,1]\r\nOutput: 3\r\nExplanation: You can do the following operations:\r\n1) Increment nums[2], so nums becomes [1,1,2].\r\n2) Increment nums[1], so nums becomes [1,2,2].\r\n3) Increment nums[2], so nums becomes [1,2,3].\n\nExample 2:\nInput: nums = [1,5,2,4,1]\r\nOutput: 14\n\nExample 3:\nInput: nums = [8]\r\nOutput: 0\n\nConstraints:\n- 1 <= nums.length <= 5000\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 minOperations(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result = prev = 0\n for curr in nums:\n if prev < curr:\n prev = curr\n continue\n prev += 1\n result += prev-curr \n return result\n"}} diff --git a/cp/cp-11190.jsonl b/cp/cp-11190.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1a95b212736112481334d6fe4926509979ba6ec5 --- /dev/null +++ b/cp/cp-11190.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11190", "name": "LeetCode 1828: Queries On Number Of Points Inside A Circle"} +{"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: Queries on Number of Points Inside a Circle (Difficulty: Medium)\nTags: Array, Math, Geometry\n\nYou are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates.\nYou are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj.\nFor each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside.\nReturn an array answer, where answer[j] is the answer to the jth query.\nFollow up: Could you find the answer for each query in better complexity than O(n)?\n\nExample 1:\nInput: points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]\nOutput: [3,2,2]\nExplanation: The points and circles are shown above.\nqueries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.\n\nExample 2:\nInput: points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]\nOutput: [2,3,2,4]\nExplanation: The points and circles are shown above.\nqueries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.\n\nConstraints:\n- 1 <= points.length <= 500\n- points[i].length == 2\n- 0 <= x​​​​​​i, y​​​​​​i <= 500\n- 1 <= queries.length <= 500\n- queries[j].length == 3\n- 0 <= xj, yj <= 500\n- 1 <= rj <= 500\n- All coordinates are integers."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(q * n)\n# Space: O(1)\n\nclass Solution(object):\n def countPoints(self, points, queries):\n \"\"\"\n :type points: List[List[int]]\n :type queries: List[List[int]]\n :rtype: List[int]\n \"\"\"\n result = []\n for i, j, r in queries:\n result.append(0)\n for x, y in points:\n if (x-i)**2+(y-j)**2 <= r**2:\n result[-1] += 1\n return result\n"}} diff --git a/cp/cp-11191.jsonl b/cp/cp-11191.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6022afdbc53b94b9efadc7a14baad2087ad3d80b --- /dev/null +++ b/cp/cp-11191.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11191", "name": "LeetCode 1829: Maximum Xor For Each Query"} +{"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 XOR for Each Query (Difficulty: Medium)\nTags: Array, Bit Manipulation, Prefix Sum\n\nYou are given a sorted array nums of n non-negative integers and an integer maximumBit. You want to perform the following query n times:\nReturn an array answer, where answer[i] is the answer to the ith query.\n\nExample 1:\nInput: nums = [0,1,1,3], maximumBit = 2\nOutput: [0,3,2,3]\nExplanation: The queries are answered as follows:\n1st query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3.\n2nd query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3.\n3rd query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3.\n4th query: nums = [0], k = 3 since 0 XOR 3 = 3.\n\nExample 2:\nInput: nums = [2,3,4,7], maximumBit = 3\nOutput: [5,2,6,5]\nExplanation: The queries are answered as follows:\n1st query: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7.\n2nd query: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7.\n3rd query: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7.\n4th query: nums = [2], k = 5 since 2 XOR 5 = 7.\n\nExample 3:\nInput: nums = [0,1,2,2,5,7], maximumBit = 3\nOutput: [4,3,6,4,6,7]\n\nConstraints:\n- nums.length == n\n- 1 <= n <= 10^5\n- 1 <= maximumBit <= 20\n- 0 <= nums[i] < 2maximumBit\n- nums​​​ is sorted in ascending order."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def getMaximumXor(self, nums, maximumBit):\n \"\"\"\n :type nums: List[int]\n :type maximumBit: int\n :rtype: List[int]\n \"\"\"\n result = [0]*len(nums)\n mask = 2**maximumBit-1\n for i in range(len(nums)):\n mask ^= nums[i]\n result[-1-i] = mask\n return result\n"}} diff --git a/cp/cp-11192.jsonl b/cp/cp-11192.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fa2fed8f039b8abe14d361672dd3a6f51bd188ca --- /dev/null +++ b/cp/cp-11192.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11192", "name": "LeetCode 1830: Minimum Number Of Operations To Make String Sorted"} +{"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: Minimum Number of Operations to Make String Sorted (Difficulty: Hard)\nTags: Math, String, Combinatorics\n\nYou are given a string s (0-indexed)​​​​​​. You are asked to perform the following operation on s​​​​​​ until you get a sorted string:\nReturn the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 109 + 7.\n\nExample 1:\nInput: s = \"cba\"\nOutput: 5\nExplanation: The simulation goes as follows:\nOperation 1: i=2, j=2. Swap s[1] and s[2] to get s=\"cab\", then reverse the suffix starting at 2. Now, s=\"cab\".\nOperation 2: i=1, j=2. Swap s[0] and s[2] to get s=\"bac\", then reverse the suffix starting at 1. Now, s=\"bca\".\nOperation 3: i=2, j=2. Swap s[1] and s[2] to get s=\"bac\", then reverse the suffix starting at 2. Now, s=\"bac\".\nOperation 4: i=1, j=1. Swap s[0] and s[1] to get s=\"abc\", then reverse the suffix starting at 1. Now, s=\"acb\".\nOperation 5: i=2, j=2. Swap s[1] and s[2] to get s=\"abc\", then reverse the suffix starting at 2. Now, s=\"abc\".\n\nExample 2:\nInput: s = \"aabaa\"\nOutput: 2\nExplanation: The simulation goes as follows:\nOperation 1: i=3, j=4. Swap s[2] and s[4] to get s=\"aaaab\", then reverse the substring starting at 3. Now, s=\"aaaba\".\nOperation 2: i=4, j=4. Swap s[3] and s[4] to get s=\"aaaab\", then reverse the substring starting at 4. Now, s=\"aaaab\".\n\nConstraints:\n- 1 <= s.length <= 3000\n- s​​​​​​ consists only of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(26 * n) = O(n)\n# Space: O(max_n) = O(max_n)\n\ninv = [0, 1]\n\n\nclass Solution(object):\n def makeStringSorted(self, s): # count of prev_permutation\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n def inverse(n, m):\n i = len(inv)\n while len(inv) <= n: # lazy initialization\n inv.append(inv[m%i]*(m-m//i) % m) # https://cp-algorithms.com/algebra/module-inverse.html\n i += 1\n return inv[n]\n \n MOD = 10**9+7\n count, result, comb_total = [0]*26, 0, 1\n for i in reversed(range(len(s))):\n num = ord(s[i])-ord('a') \n count[num] += 1\n comb_total = (comb_total*(len(s)-i))*inverse(count[num], MOD)\n result = (result + (comb_total*sum(count[:num]))*inverse(len(s)-i, MOD)) % MOD\n return result\n"}} diff --git a/cp/cp-11194.jsonl b/cp/cp-11194.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f92d1cf1ab1b97e52e6ee60802943a38531672d8 --- /dev/null +++ b/cp/cp-11194.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11194", "name": "LeetCode 1833: Maximum Ice Cream Bars"} +{"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 Ice Cream Bars (Difficulty: Medium)\nTags: Array, Greedy, Sorting, Counting Sort\n\nIt is a sweltering summer day, and a boy wants to buy some ice cream bars.\nAt the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible.\nNote: The boy can buy the ice cream bars in any order.\nReturn the maximum number of ice cream bars the boy can buy with coins coins.\nYou must solve the problem by counting sort.\n\nExample 1:\nInput: costs = [1,3,2,4,1], coins = 7\nOutput: 4\nExplanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.\n\nExample 2:\nInput: costs = [10,6,8,7,7,8], coins = 5\nOutput: 0\nExplanation: The boy cannot afford any of the ice cream bars.\n\nExample 3:\nInput: costs = [1,6,3,1,2,5], coins = 20\nOutput: 6\nExplanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.\n\nConstraints:\n- costs.length == n\n- 1 <= n <= 10^5\n- 1 <= costs[i] <= 10^5\n- 1 <= coins <= 10^8"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def maxIceCream(self, costs, coins):\n \"\"\"\n :type costs: List[int]\n :type coins: int\n :rtype: int\n \"\"\"\n costs.sort()\n for i, c in enumerate(costs):\n coins -= c\n if coins < 0:\n return i\n return len(costs)\n"}} diff --git a/cp/cp-11195.jsonl b/cp/cp-11195.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2d88bdf1edbfde99fe243f84431d297cced31483 --- /dev/null +++ b/cp/cp-11195.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11195", "name": "LeetCode 1834: Single Threaded Cpu"} +{"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: Single-Threaded CPU (Difficulty: Medium)\nTags: Array, Sorting, Heap (Priority Queue)\n\nYou are given n​​​​​​ tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the i​​​​​​th​​​​ task will be available to process at enqueueTimei and will take processingTimei to finish processing.\nYou have a single-threaded CPU that can process at most one task at a time and will act in the following way:\nReturn the order in which the CPU will process the tasks.\n\nExample 1:\nInput: tasks = [[1,2],[2,4],[3,2],[4,1]]\nOutput: [0,2,3,1]\nExplanation: The events go as follows: \n- At time = 1, task 0 is available to process. Available tasks = {0}.\n- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.\n- At time = 2, task 1 is available to process. Available tasks = {1}.\n- At time = 3, task 2 is available to process. Available tasks = {1, 2}.\n- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.\n- At time = 4, task 3 is available to process. Available tasks = {1, 3}.\n- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.\n- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.\n- At time = 10, the CPU finishes task 1 and becomes idle.\n\nExample 2:\nInput: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]\nOutput: [4,3,2,0,1]\nExplanation: The events go as follows:\n- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.\n- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.\n- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.\n- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.\n- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.\n- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.\n- At time = 40, the CPU finishes task 1 and becomes idle.\n\nConstraints:\n- tasks.length == n\n- 1 <= n <= 10^5\n- 1 <= enqueueTimei, processingTimei <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport heapq\n\n\nclass Solution(object):\n def getOrder(self, tasks):\n \"\"\"\n :type tasks: List[List[int]]\n :rtype: List[int]\n \"\"\"\n idx = range(len(tasks))\n idx.sort(key=lambda x: tasks[x][0])\n result, min_heap = [], []\n i, time = 0, tasks[idx[0]][0]\n while i < len(idx) or min_heap:\n while i < len(idx) and tasks[idx[i]][0] <= time:\n heapq.heappush(min_heap, (tasks[idx[i]][1], idx[i]))\n i += 1\n if not min_heap:\n time = tasks[idx[i]][0]\n continue\n t, j = heapq.heappop(min_heap)\n time += t\n result.append(j)\n return result\n"}} diff --git a/cp/cp-11199.jsonl b/cp/cp-11199.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..88beffb64bb6aa7ffa9fd175a7cd52a3d2cb5562 --- /dev/null +++ b/cp/cp-11199.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11199", "name": "LeetCode 1838: Frequency Of The Most Frequent Element"} +{"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: Frequency of the Most Frequent Element (Difficulty: Medium)\nTags: Array, Binary Search, Greedy, Sliding Window, Sorting, Prefix Sum\n\nThe frequency of an element is the number of times it occurs in an array.\nYou are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.\nReturn the maximum possible frequency of an element after performing at most k operations.\n\nExample 1:\nInput: nums = [1,2,4], k = 5\nOutput: 3\nExplanation: Increment the first element three times and the second element two times to make nums = [4,4,4].\n4 has a frequency of 3.\n\nExample 2:\nInput: nums = [1,4,8,13], k = 5\nOutput: 2\nExplanation: There are multiple optimal solutions:\n- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.\n- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.\n- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.\n\nExample 3:\nInput: nums = [3,9,6], k = 2\nOutput: 1\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i] <= 10^5\n- 1 <= k <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nclass Solution(object):\n def maxFrequency(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n left = 0\n nums.sort()\n for right in range(len(nums)):\n k += nums[right]\n if k < nums[right]*(right-left+1):\n k -= nums[left]\n left += 1\n return right-left+1\n"}} diff --git a/cp/cp-11200.jsonl b/cp/cp-11200.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f21f6696bbc94c0b096bdeed92b2825328a8e01d --- /dev/null +++ b/cp/cp-11200.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11200", "name": "LeetCode 1839: Longest Substring Of All Vowels In Order"} +{"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 Substring Of All Vowels in Order (Difficulty: Medium)\nTags: String, Sliding Window\n\nA string is considered beautiful if it satisfies the following conditions:\nFor example, strings \"aeiou\" and \"aaaaaaeiiiioou\" are considered beautiful, but \"uaeio\", \"aeoiu\", and \"aaaeeeooo\" are not beautiful.\nGiven a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0.\nA substring is a contiguous sequence of characters in a string.\n\nExample 1:\nInput: word = \"aeiaaioaaaaeiiiiouuuooaauuaeiu\"\nOutput: 13\nExplanation: The longest beautiful substring in word is \"aaaaeiiiiouuu\" of length 13.\n\nExample 2:\nInput: word = \"aeeeiiiioooauuuaeiou\"\nOutput: 5\nExplanation: The longest beautiful substring in word is \"aeiou\" of length 5.\n\nExample 3:\nInput: word = \"a\"\nOutput: 0\nExplanation: There is no beautiful substring, so return 0.\n\nConstraints:\n- 1 <= word.length <= 5 * 10^5\n- word consists of characters 'a', 'e', 'i', 'o', and 'u'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def longestBeautifulSubstring(self, word):\n \"\"\"\n :type word: str\n :rtype: int\n \"\"\"\n result = 0\n l = cnt = 1\n for i in range(len(word)-1):\n if word[i] > word[i+1]:\n l = cnt = 1\n else:\n l += 1\n cnt += int(word[i] < word[i+1])\n if cnt == 5:\n result = max(result, l)\n return result\n"}} diff --git a/cp/cp-11201.jsonl b/cp/cp-11201.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..88aca36122187383f7503b3ba59029ff13e7f95c --- /dev/null +++ b/cp/cp-11201.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11201", "name": "LeetCode 1840: Maximum Building Height"} +{"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 Building Height (Difficulty: Hard)\nTags: Array, Math, Sorting\n\nYou want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n.\nHowever, there are city restrictions on the heights of the new buildings:\nAdditionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height less than or equal to maxHeighti.\nIt is guaranteed that each building will appear at most once in restrictions, and building 1 will not be in restrictions.\nReturn the maximum possible height of the tallest building.\n\nExample 1:\nInput: n = 5, restrictions = [[2,1],[4,1]]\nOutput: 2\nExplanation: The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.\n\nExample 2:\nInput: n = 6, restrictions = []\nOutput: 5\nExplanation: The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.\n\nExample 3:\nInput: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]\nOutput: 5\nExplanation: The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.\n\nConstraints:\n- 2 <= n <= 10^9\n- 0 <= restrictions.length <= min(n - 1, 105)\n- 2 <= idi <= n\n- idi is unique.\n- 0 <= maxHeighti <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def maxBuilding(self, n, restrictions):\n \"\"\"\n :type n: int\n :type restrictions: List[List[int]]\n :rtype: int\n \"\"\"\n restrictions.extend([[1, 0], [n, n-1]])\n restrictions.sort()\n for i in reversed(range(len(restrictions)-1)):\n restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1]+(restrictions[i+1][0]-restrictions[i][0]))\n result = 0\n for i in range(1, len(restrictions)):\n restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1]+(restrictions[i][0]-restrictions[i-1][0]))\n left, h1 = restrictions[i-1]\n right, h2 = restrictions[i]\n result = max(result, max(h1, h2)+((right-left)-abs(h1-h2))//2)\n return result\n"}} diff --git a/cp/cp-11204.jsonl b/cp/cp-11204.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a30bf73609027460fe3a1b16d3b077ae033153e7 --- /dev/null +++ b/cp/cp-11204.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11204", "name": "LeetCode 1845: Seat Reservation Manager"} +{"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: Seat Reservation Manager (Difficulty: Medium)\nTags: Design, Heap (Priority Queue)\n\nDesign a system that manages the reservation state of n seats that are numbered from 1 to n.\nImplement the SeatManager class:\n\nExample 1:\nInput\n[\"SeatManager\", \"reserve\", \"reserve\", \"unreserve\", \"reserve\", \"reserve\", \"reserve\", \"reserve\", \"unreserve\"]\n[[5], [], [], [2], [], [], [], [], [5]]\nOutput\n[null, 1, 2, null, 2, 3, 4, 5, null]\n\nExplanation\nSeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.\nseatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.\nseatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].\nseatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.reserve(); // The available seats are [3,4,5], so return the lowest of them, which is 3.\nseatManager.reserve(); // The available seats are [4,5], so return the lowest of them, which is 4.\nseatManager.reserve(); // The only available seat is seat 5, so return 5.\nseatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].\n\nConstraints:\n- 1 <= n <= 10^5\n- 1 <= seatNumber <= n\n- For each call to reserve, it is guaranteed that there will be at least one unreserved seat.\n- For each call to unreserve, it is guaranteed that seatNumber will be reserved.\n- At most 105 calls in total will be made to reserve and unreserve."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(n)\n# reserve: O(logn)\n# unreserve: O(logn)\n# Space: O(n)\n\nimport heapq\n\n\nclass SeatManager(object):\n\n def __init__(self, n):\n \"\"\"\n :type n: int\n \"\"\"\n self.__min_heap = range(1, n+1)\n # heapq.heapify(self.__min_heap) # no need for sorted list\n\n def reserve(self):\n \"\"\"\n :rtype: int\n \"\"\"\n return heapq.heappop(self.__min_heap)\n\n def unreserve(self, seatNumber):\n \"\"\"\n :type seatNumber: int\n :rtype: None\n \"\"\"\n heapq.heappush(self.__min_heap, seatNumber)\n"}} diff --git a/cp/cp-11205.jsonl b/cp/cp-11205.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0c21eac241248b6a941691e4dd6744f5322401d4 --- /dev/null +++ b/cp/cp-11205.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11205", "name": "LeetCode 1846: Maximum Element After Decreasing And Rearranging"} +{"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 Element After Decreasing and Rearranging (Difficulty: Medium)\nTags: Array, Greedy, Sorting\n\nYou are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:\nThere are 2 types of operations that you can perform any number of times:\nReturn the maximum possible value of an element in arr after performing the operations to satisfy the conditions.\n\nExample 1:\nInput: arr = [2,2,1,2,1]\nOutput: 2\nExplanation: \nWe can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1].\nThe largest element in arr is 2.\n\nExample 2:\nInput: arr = [100,1,1000]\nOutput: 3\nExplanation: \nOne possible way to satisfy the conditions is by doing the following:\n1. Rearrange arr so it becomes [1,100,1000].\n2. Decrease the value of the second element to 2.\n3. Decrease the value of the third element to 3.\nNow arr = [1,2,3], which satisfies the conditions.\nThe largest element in arr is 3.\n\nExample 3:\nInput: arr = [1,2,3,4,5]\nOutput: 5\nExplanation: The array already satisfies the conditions, and the largest element is 5.\n\nConstraints:\n- 1 <= arr.length <= 10^5\n- 1 <= arr[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def maximumElementAfterDecrementingAndRearranging(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n arr.sort()\n result = 1\n for i in range(1, len(arr)):\n result = min(result+1, arr[i])\n return result\n"}} diff --git a/cp/cp-11206.jsonl b/cp/cp-11206.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b018748e067cb97e306924498945e71d0616d758 --- /dev/null +++ b/cp/cp-11206.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11206", "name": "LeetCode 1847: Closest Room"} +{"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: Closest Room (Difficulty: Hard)\nTags: Array, Binary Search, Sorting, Ordered Set\n\nThere is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where rooms[i] = [roomIdi, sizei] denotes that there is a room with room number roomIdi and size equal to sizei. Each roomIdi is guaranteed to be unique.\nYou are also given k queries in a 2D array queries where queries[j] = [preferredj, minSizej]. The answer to the jth query is the room number id of a room such that:\nIf there is a tie in the absolute difference, then use the room with the smallest such id. If there is no such room, the answer is -1.\nReturn an array answer of length k where answer[j] contains the answer to the jth query.\n\nExample 1:\nInput: rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]\nOutput: [3,-1,3]\nExplanation: The answers to the queries are as follows:\nQuery = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.\nQuery = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.\nQuery = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.\n\nExample 2:\nInput: rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]\nOutput: [2,1,3]\nExplanation: The answers to the queries are as follows:\nQuery = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.\nQuery = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.\nQuery = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.\n\nConstraints:\n- n == rooms.length\n- 1 <= n <= 10^5\n- k == queries.length\n- 1 <= k <= 10^4\n- 1 <= roomIdi, preferredj <= 10^7\n- 1 <= sizei, minSizej <= 10^7"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn + klogk + klogn)\n# Space: O(n + k)\n\nfrom sortedcontainers import SortedList\n\n\nclass Solution(object):\n def closestRoom(self, rooms, queries):\n \"\"\"\n :type rooms: List[List[int]]\n :type queries: List[List[int]]\n :rtype: List[int]\n \"\"\"\n def find_closest(ids, r):\n result, min_dist = -1, float(\"inf\")\n i = ids.bisect_right(r)\n if i-1 >= 0 and abs(ids[i-1]-r) < min_dist:\n min_dist = abs(ids[i-1]-r)\n result = ids[i-1]\n if i < len(ids) and abs(ids[i]-r) < min_dist:\n min_dist = abs(ids[i]-r)\n result = ids[i]\n return result\n\n rooms.sort(key=lambda x: x[1], reverse=True)\n for i, q in enumerate(queries):\n q.append(i)\n queries.sort(key=lambda x: x[1], reverse=True)\n ids = SortedList()\n i = 0\n result = [-1]*len(queries)\n for r, s, idx in queries:\n while i < len(rooms) and rooms[i][1] >= s:\n ids.add(rooms[i][0])\n i += 1\n result[idx] = find_closest(ids, r)\n return result\n\n \n# Time: O(nlogn + klogk + klogn)\n# Space: O(n + k)\nfrom sortedcontainers import SortedList\n\n\nclass Solution2(object):\n def closestRoom(self, rooms, queries):\n \"\"\"\n :type rooms: List[List[int]]\n :type queries: List[List[int]]\n :rtype: List[int]\n \"\"\"\n def find_closest(ids, r):\n result, min_dist = -1, float(\"inf\")\n i = ids.bisect_right(r)\n if i-1 >= 0 and abs(ids[i-1]-r) < min_dist:\n min_dist = abs(ids[i-1]-r)\n result = ids[i-1]\n if i < len(ids) and abs(ids[i]-r) < min_dist:\n min_dist = abs(ids[i]-r)\n result = ids[i]\n return result\n\n rooms.sort(key=lambda x: x[1])\n for i, q in enumerate(queries):\n q.append(i)\n queries.sort(key=lambda x: x[1])\n ids = SortedList(i for i, _ in rooms) \n i = 0\n result = [-1]*len(queries)\n for r, s, idx in queries:\n while i < len(rooms) and rooms[i][1] < s:\n ids.remove(rooms[i][0])\n i += 1\n result[idx] = find_closest(ids, r)\n return result\n"}} diff --git a/cp/cp-11207.jsonl b/cp/cp-11207.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..92cffda94923e3cba295dc12b84c4fe6df84e2e1 --- /dev/null +++ b/cp/cp-11207.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11207", "name": "LeetCode 1848: Minimum Distance To The Target Element"} +{"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: Minimum Distance to the Target Element (Difficulty: Easy)\nTags: Array\n\nGiven an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x.\nReturn abs(i - start).\nIt is guaranteed that target exists in nums.\n\nExample 1:\nInput: nums = [1,2,3,4,5], target = 5, start = 3\nOutput: 1\nExplanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.\n\nExample 2:\nInput: nums = [1], target = 1, start = 0\nOutput: 0\nExplanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.\n\nExample 3:\nInput: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0\nOutput: 0\nExplanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.\n\nConstraints:\n- 1 <= nums.length <= 1000\n- 1 <= nums[i] <= 10^4\n- 0 <= start < nums.length\n- target is in nums."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def getMinDistance(self, nums, target, start):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :type start: int\n :rtype: int\n \"\"\"\n for i in range(len(nums)):\n if (start-i >= 0 and nums[start-i] == target) or \\\n (start+i < len(nums) and nums[start+i] == target):\n break\n return i\n"}} diff --git a/cp/cp-11208.jsonl b/cp/cp-11208.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..124b6ee14f9ebb9265f65508a69f1a63737e763e --- /dev/null +++ b/cp/cp-11208.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11208", "name": "LeetCode 1849: Splitting A String Into Descending Consecutive Values"} +{"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: Splitting a String Into Descending Consecutive Values (Difficulty: Medium)\nTags: String, Backtracking, Enumeration\n\nYou are given a string s that consists of only digits.\nCheck if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1.\nReturn true if it is possible to split s​​​​​​ as described above, or false otherwise.\nA substring is a contiguous sequence of characters in a string.\n\nExample 1:\nInput: s = \"1234\"\nOutput: false\nExplanation: There is no valid way to split s.\n\nExample 2:\nInput: s = \"050043\"\nOutput: true\nExplanation: s can be split into [\"05\", \"004\", \"3\"] with numerical values [5,4,3].\nThe values are in descending order with adjacent values differing by 1.\n\nExample 3:\nInput: s = \"9080701\"\nOutput: false\nExplanation: There is no valid way to split s.\n\nConstraints:\n- 1 <= s.length <= 20\n- s only consists of digits."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def splitString(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n def backtracking(s, i, num, cnt):\n if i == len(s):\n return cnt >= 2\n new_num = 0\n for j in range(i, len(s)):\n new_num = new_num*10 + int(s[j])\n if new_num >= num >= 0:\n break\n if (num == -1 or num-1 == new_num) and backtracking(s, j+1, new_num, cnt+1):\n return True\n return False\n \n return backtracking(s, 0, -1, 0)\n"}} diff --git a/cp/cp-11209.jsonl b/cp/cp-11209.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9ffa7c2c86efffd1a0293d99e6afc2312e1b34ff --- /dev/null +++ b/cp/cp-11209.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11209", "name": "LeetCode 1850: Minimum Adjacent Swaps To Reach The Kth Smallest 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: Minimum Adjacent Swaps to Reach the Kth Smallest Number (Difficulty: Medium)\nTags: Two Pointers, String, Greedy\n\nYou are given a string num, representing a large integer, and an integer k.\nWe call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones.\nReturn the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer.\nThe tests are generated in such a way that kth smallest wonderful integer exists.\n\nExample 1:\nInput: num = \"5489355142\", k = 4\nOutput: 2\nExplanation: The 4th smallest wonderful number is \"5489355421\". To get this number:\n- Swap index 7 with index 8: \"5489355142\" -> \"5489355412\"\n- Swap index 8 with index 9: \"5489355412\" -> \"5489355421\"\n\nExample 2:\nInput: num = \"11112\", k = 4\nOutput: 4\nExplanation: The 4th smallest wonderful number is \"21111\". To get this number:\n- Swap index 3 with index 4: \"11112\" -> \"11121\"\n- Swap index 2 with index 3: \"11121\" -> \"11211\"\n- Swap index 1 with index 2: \"11211\" -> \"12111\"\n- Swap index 0 with index 1: \"12111\" -> \"21111\"\n\nExample 3:\nInput: num = \"00123\", k = 1\nOutput: 1\nExplanation: The 1st smallest wonderful number is \"00132\". To get this number:\n- Swap index 3 with index 4: \"00123\" -> \"00132\"\n\nConstraints:\n- 2 <= num.length <= 1000\n- 1 <= k <= 1000\n- num only consists of digits."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((k + n) * n)\n# Space: O(n)\n\nclass Solution(object):\n def getMinSwaps(self, num, k):\n \"\"\"\n :type num: str\n :type k: int\n :rtype: int\n \"\"\"\n def next_permutation(nums, begin, end):\n def reverse(nums, begin, end):\n left, right = begin, end-1\n while left < right:\n nums[left], nums[right] = nums[right], nums[left]\n left += 1\n right -= 1\n\n k, l = begin-1, begin\n for i in reversed(range(begin, end-1)):\n if nums[i] < nums[i+1]:\n k = i\n break\n else:\n reverse(nums, begin, end)\n return False\n for i in reversed(range(k+1, end)):\n if nums[i] > nums[k]:\n l = i\n break\n nums[k], nums[l] = nums[l], nums[k]\n reverse(nums, k+1, end)\n return True\n \n new_num = list(num)\n while k:\n next_permutation(new_num, 0, len(new_num))\n k -= 1\n result = 0\n for i in range(len(new_num)):\n if new_num[i] == num[i]:\n continue\n # // greedily move the one with the least cost from new_num to num without missing optimal cost\n for j in range(i+1, len(new_num)):\n if new_num[j] == num[i]:\n break\n result += j-i\n for j in reversed(range(i+1, j+1)):\n new_num[j], new_num[j-1] = new_num[j-1], new_num[j]\n return result\n"}} diff --git a/cp/cp-11210.jsonl b/cp/cp-11210.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ebe0aacf0f6e035a649975d984e3d6b73a0bc87e --- /dev/null +++ b/cp/cp-11210.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11210", "name": "LeetCode 1851: Minimum Interval To Include Each Query"} +{"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: Minimum Interval to Include Each Query (Difficulty: Hard)\nTags: Array, Binary Search, Line Sweep, Sorting, Heap (Priority Queue)\n\nYou are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1.\nYou are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1.\nReturn an array containing the answers to the queries.\n\nExample 1:\nInput: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]\nOutput: [3,3,1,4]\nExplanation: The queries are processed as follows:\n- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.\n- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.\n- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.\n- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.\n\nExample 2:\nInput: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]\nOutput: [2,-1,4,6]\nExplanation: The queries are processed as follows:\n- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.\n- Query = 19: None of the intervals contain 19. The answer is -1.\n- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.\n- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.\n\nConstraints:\n- 1 <= intervals.length <= 10^5\n- 1 <= queries.length <= 10^5\n- intervals[i].length == 2\n- 1 <= lefti <= righti <= 10^7\n- 1 <= queries[j] <= 10^7"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn + klogk + klogn)\n# space: O(n + k)\n\nimport heapq\n\n\nclass Solution(object):\n def minInterval(self, intervals, queries):\n \"\"\"\n :type intervals: List[List[int]]\n :type queries: List[int]\n :rtype: List[int]\n \"\"\"\n intervals.sort()\n queries = [(q, i) for i, q in enumerate(queries)]\n queries.sort()\n min_heap = []\n i = 0\n result =[-1]*len(queries)\n for q, idx in queries:\n while i != len(intervals) and intervals[i][0] <= q:\n heapq.heappush(min_heap, [intervals[i][1]-intervals[i][0]+1, i])\n i += 1\n while min_heap and intervals[min_heap[0][1]][1] < q:\n heapq.heappop(min_heap)\n result[idx] = min_heap[0][0] if min_heap else -1\n return result\n"}} diff --git a/cp/cp-11212.jsonl b/cp/cp-11212.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..30e89a0c73bae801dd2fe22a05f4dddc51bf5c84 --- /dev/null +++ b/cp/cp-11212.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11212", "name": "LeetCode 1854: Maximum Population Year"} +{"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 Population Year (Difficulty: Easy)\nTags: Array, Counting, Prefix Sum\n\nYou are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person.\nThe population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die.\nReturn the earliest year with the maximum population.\n\nExample 1:\nInput: logs = [[1993,1999],[2000,2010]]\nOutput: 1993\nExplanation: The maximum population is 1, and 1993 is the earliest year with this population.\n\nExample 2:\nInput: logs = [[1950,1961],[1960,1971],[1970,1981]]\nOutput: 1960\nExplanation: \nThe maximum population is 2, and it had happened in years 1960 and 1970.\nThe earlier year between them is 1960.\n\nConstraints:\n- 1 <= logs.length <= 100\n- 1950 <= birthi < deathi <= 2050"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maximumPopulation(self, logs):\n \"\"\"\n :type logs: List[List[int]]\n :rtype: int\n \"\"\"\n MIN_YEAR, MAX_YEAR = 1950, 2050\n years = [0]*(MAX_YEAR-MIN_YEAR+1)\n for s, e in logs:\n years[s-MIN_YEAR] += 1\n years[e-MIN_YEAR] -= 1\n result = 0\n for i in range(len(years)):\n if i:\n years[i] += years[i-1]\n if years[i] > years[result]:\n result = i\n return result+MIN_YEAR\n"}} diff --git a/cp/cp-11213.jsonl b/cp/cp-11213.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..497f3961fa52c34af850ae6a34e50a3680fef9e2 --- /dev/null +++ b/cp/cp-11213.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11213", "name": "LeetCode 1855: Maximum Distance Between A Pair Of Values"} +{"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 Between a Pair of Values (Difficulty: Medium)\nTags: Array, Two Pointers, Binary Search\n\nYou are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​.\nA pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i​​​​.\nReturn the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0.\nAn array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length.\n\nExample 1:\nInput: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]\nOutput: 2\nExplanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).\nThe maximum distance is 2 with pair (2,4).\n\nExample 2:\nInput: nums1 = [2,2,2], nums2 = [10,10,1]\nOutput: 1\nExplanation: The valid pairs are (0,0), (0,1), and (1,1).\nThe maximum distance is 1 with pair (0,1).\n\nExample 3:\nInput: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]\nOutput: 2\nExplanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).\nThe maximum distance is 2 with pair (2,4).\n\nConstraints:\n- 1 <= nums1.length, nums2.length <= 10^5\n- 1 <= nums1[i], nums2[j] <= 10^5\n- Both nums1 and nums2 are non-increasing."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + m)\n# Space: O(1)\n\nclass Solution(object):\n def maxDistance(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: int\n \"\"\"\n result = i = j = 0\n while i < len(nums1) and j < len(nums2):\n if nums1[i] > nums2[j]:\n i += 1\n else:\n result = max(result, j-i)\n j += 1\n return result\n"}} diff --git a/cp/cp-11214.jsonl b/cp/cp-11214.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4fa638c70caa5017c00db12c202c158ba7cb7e81 --- /dev/null +++ b/cp/cp-11214.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11214", "name": "LeetCode 1856: Maximum Subarray Min Product"} +{"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 Subarray Min-Product (Difficulty: Medium)\nTags: Array, Stack, Monotonic Stack, Prefix Sum\n\nThe min-product of an array is equal to the minimum value in the array multiplied by the array's sum.\nGiven an array of integers nums, return the maximum min-product of any non-empty subarray of nums. Since the answer may be large, return it modulo 109 + 7.\nNote that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer.\nA subarray is a contiguous part of an array.\n\nExample 1:\nInput: nums = [1,2,3,2]\nOutput: 14\nExplanation: The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2).\n2 * (2+3+2) = 2 * 7 = 14.\n\nExample 2:\nInput: nums = [2,3,3,1,2]\nOutput: 18\nExplanation: The maximum min-product is achieved with the subarray [3,3] (minimum value is 3).\n3 * (3+3) = 3 * 6 = 18.\n\nExample 3:\nInput: nums = [3,1,5,6,4,2]\nOutput: 60\nExplanation: The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4).\n4 * (5+6+4) = 4 * 15 = 60.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i] <= 10^7"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def maxSumMinProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n prefix = [0]*(len(nums)+1)\n for i in range(len(nums)):\n prefix[i+1] = prefix[i]+nums[i]\n stk, result = [-1], 0\n for i in range(len(nums)+1):\n while stk[-1] != -1 and (i == len(nums) or nums[stk[-1]] >= nums[i]):\n result = max(result, nums[stk.pop()]*(prefix[(i-1)+1]-prefix[stk[-1]+1]))\n stk.append(i) \n return result%MOD\n"}} diff --git a/cp/cp-11215.jsonl b/cp/cp-11215.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..96e37f0c4199a2b0a6c9881bd6c82d6b34187b5c --- /dev/null +++ b/cp/cp-11215.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11215", "name": "LeetCode 1857: Largest Color Value In A Directed Graph"} +{"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: Largest Color Value in a Directed Graph (Difficulty: Hard)\nTags: Hash Table, Dynamic Programming, Graph, Topological Sort, Memoization, Counting\n\nThere is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1.\nYou are given a string colors where colors[i] is a lowercase English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj.\nA valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.\nReturn the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.\n\nExample 1:\nInput: colors = \"abaca\", edges = [[0,1],[0,2],[2,3],[3,4]]\nOutput: 3\nExplanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored \"a\" (red in the above image).\n\nExample 2:\nInput: colors = \"a\", edges = [[0,0]]\nOutput: -1\nExplanation: There is a cycle from 0 to 0.\n\nConstraints:\n- n == colors.length\n- m == edges.length\n- 1 <= n <= 10^5\n- 0 <= m <= 10^5\n- colors consists of lowercase English letters.\n- 0 <= aj, bj < n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + m)\n# Space: O(n + m)\n\nclass Solution(object):\n def largestPathValue(self, colors, edges):\n \"\"\"\n :type colors: str\n :type edges: List[List[int]]\n :rtype: int\n \"\"\"\n adj = [[] for _ in range(len(colors))]\n in_degree = [0]*len(colors)\n for u, v in edges:\n adj[u].append(v)\n in_degree[v] += 1\n q = []\n for u in range(len(colors)):\n if not in_degree[u]:\n q.append(u)\n dp = [[0]*26 for _ in range(len(colors))]\n result, cnt = -1, 0\n while q:\n new_q = []\n for u in q:\n cnt += 1\n dp[u][ord(colors[u])-ord('a')] += 1\n result = max(result, dp[u][ord(colors[u])-ord('a')])\n for v in adj[u]:\n for c in range(26):\n dp[v][c] = max(dp[v][c], dp[u][c])\n in_degree[v] -= 1\n if not in_degree[v]:\n new_q.append(v)\n q = new_q\n return result if cnt == len(colors) else -1\n"}} diff --git a/cp/cp-11217.jsonl b/cp/cp-11217.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8747a5b71f6511acd148afb1d7d77f522926fd9d --- /dev/null +++ b/cp/cp-11217.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11217", "name": "LeetCode 1859: Sorting The Sentence"} +{"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: Sorting the Sentence (Difficulty: Easy)\nTags: String, Sorting\n\nA sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.\nA sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.\nGiven a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.\n\nExample 1:\nInput: s = \"is2 sentence4 This1 a3\"\nOutput: \"This is a sentence\"\nExplanation: Sort the words in s to their original positions \"This1 is2 a3 sentence4\", then remove the numbers.\n\nExample 2:\nInput: s = \"Myself2 Me1 I4 and3\"\nOutput: \"Me Myself and I\"\nExplanation: Sort the words in s to their original positions \"Me1 Myself2 and3 I4\", then remove the numbers.\n\nConstraints:\n- 2 <= s.length <= 200\n- s consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9.\n- The number of words in s is between 1 and 9.\n- The words in s are separated by a single space.\n- s contains no leading or trailing spaces."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport itertools\n\n\nclass Solution(object):\n def sortSentence(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n words = s.split()\n for i in range(len(words)):\n while int(words[i][-1])-1 != i:\n words[int(words[i][-1])-1], words[i] = words[i], words[int(words[i][-1])-1]\n return \" \".join(itertools.imap(lambda x: x[:-1], words))\n"}} diff --git a/cp/cp-11218.jsonl b/cp/cp-11218.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8026363715b87f63780e280610b098bea01d3416 --- /dev/null +++ b/cp/cp-11218.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11218", "name": "LeetCode 1860: Incremental Memory Leak"} +{"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: Incremental Memory Leak (Difficulty: Medium)\nTags: Math, Simulation\n\nYou are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second.\nAt the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes.\nReturn an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively.\n\nExample 1:\nInput: memory1 = 2, memory2 = 2\nOutput: [3,1,0]\nExplanation: The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.\n- At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively.\n\nExample 2:\nInput: memory1 = 8, memory2 = 11\nOutput: [6,0,4]\nExplanation: The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.\n- At the 3rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.\n- At the 4th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.\n- At the 5th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.\n- At the 6th second, the program crashes. The sticks have 0 and 4 bits available respectively.\n\nConstraints:\n- 0 <= memory1, memory2 <= 2^31 - 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\n# Same problem from https://codingcompetitions.withgoogle.com/codejam/round/000000000019ffb9/00000000003384ea\nclass Solution(object):\n def memLeak(self, memory1, memory2):\n \"\"\"\n :type memory1: int\n :type memory2: int\n :rtype: List[int]\n \"\"\"\n def s(a, d, n):\n return (2*a + (n-1)*d)*n//2\n\n def f(a, d, x):\n r = int((-(2*a-d)+((2*a-d)**2+8*d*x)**0.5)/(2*d))\n if s(a, d, r) > x: # adjust float accuracy\n r -= 1\n return r\n\n is_swapped = False\n if memory1 < memory2:\n memory1, memory2 = memory2, memory1\n is_swapped = True\n n = f(1, 1, memory1-memory2)\n memory1 -= s(1, 1, n)\n if memory1 == memory2:\n is_swapped = False\n l = f(n+1, 2, memory1)\n r = f(n+2, 2, memory2)\n memory1 -= s(n+1, 2, l)\n memory2 -= s(n+2, 2, r)\n if is_swapped:\n memory1, memory2 = memory2, memory1\n return [n+l+r+1, memory1, memory2]\n"}} diff --git a/cp/cp-11219.jsonl b/cp/cp-11219.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7ec30536bbd263c9e9a19c3fd642d78f656bffb8 --- /dev/null +++ b/cp/cp-11219.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11219", "name": "LeetCode 1861: Rotating The Box"} +{"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: Rotating the Box (Difficulty: Medium)\nTags: Array, Two Pointers, Matrix\n\nYou are given an m x n matrix of characters boxGrid representing a side-view of a box. Each cell of the box is one of the following:\nThe box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions.\nIt is guaranteed that each stone in boxGrid rests on an obstacle, another stone, or the bottom of the box.\nReturn an n x m matrix representing the box after the rotation described above.\n\nExample 1:\nInput: boxGrid = [[\"#\",\".\",\"#\"]]\nOutput: [[\".\"],\n  [\"#\"],\n  [\"#\"]]\n\nExample 2:\nInput: boxGrid = [[\"#\",\".\",\"*\",\".\"],\n  [\"#\",\"#\",\"*\",\".\"]]\nOutput: [[\"#\",\".\"],\n  [\"#\",\"#\"],\n  [\"*\",\"*\"],\n  [\".\",\".\"]]\n\nExample 3:\nInput: boxGrid = [[\"#\",\"#\",\"*\",\".\",\"*\",\".\"],\n  [\"#\",\"#\",\"#\",\"*\",\".\",\".\"],\n  [\"#\",\"#\",\"#\",\".\",\"#\",\".\"]]\nOutput: [[\".\",\"#\",\"#\"],\n  [\".\",\"#\",\"#\"],\n  [\"#\",\"#\",\"*\"],\n  [\"#\",\"*\",\".\"],\n  [\"#\",\".\",\"*\"],\n  [\"#\",\".\",\".\"]]\n\nConstraints:\n- m == boxGrid.length\n- n == boxGrid[i].length\n- 1 <= m, n <= 500\n- boxGrid[i][j] is either '#', '*', or '.'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def rotateTheBox(self, box):\n \"\"\"\n :type box: List[List[str]]\n :rtype: List[List[str]]\n \"\"\"\n result = [['.']*len(box) for _ in range(len(box[0]))]\n for i in range(len(box)):\n k = len(box[0])-1\n for j in reversed(range(len(box[0]))):\n if box[i][j] == '.':\n continue\n if box[i][j] == '*':\n k = j\n result[k][-1-i] = box[i][j]\n k -= 1\n return result\n"}} diff --git a/cp/cp-11220.jsonl b/cp/cp-11220.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8ad9cdab94713279d99aeb611df6d7eade3b5b54 --- /dev/null +++ b/cp/cp-11220.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11220", "name": "LeetCode 1862: Sum Of Floored 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: Sum of Floored Pairs (Difficulty: Hard)\nTags: Array, Math, Binary Search, Prefix Sum\n\nGiven an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 109 + 7.\nThe floor() function returns the integer part of the division.\n\nExample 1:\nInput: nums = [2,5,9]\nOutput: 10\nExplanation:\nfloor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0\nfloor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1\nfloor(5 / 2) = 2\nfloor(9 / 2) = 4\nfloor(9 / 5) = 1\nWe calculate the floor of the division for every pair of indices in the array then sum them up.\n\nExample 2:\nInput: nums = [7,7,7,7,7,7,7]\nOutput: 49\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n/1+n/2+...+n/n) = O(nlogn), n is the max of nums\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def sumOfFlooredPairs(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n prefix, counter = [0]*(max(nums)+1), collections.Counter(nums)\n for num, cnt in counter.iteritems():\n for j in range(num, len(prefix), num):\n prefix[j] += counter[num]\n for i in range(len(prefix)-1):\n prefix[i+1] += prefix[i]\n return reduce(lambda total, num: (total+prefix[num])%MOD, nums, 0)\n"}} diff --git a/cp/cp-11221.jsonl b/cp/cp-11221.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3522851b1e62bf00aaa5e40b617e15e256823789 --- /dev/null +++ b/cp/cp-11221.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11221", "name": "LeetCode 1863: Sum Of All Subset Xor Totals"} +{"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 All Subset XOR Totals (Difficulty: Easy)\nTags: Array, Math, Backtracking, Bit Manipulation, Combinatorics, Enumeration\n\nThe XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.\nGiven an array nums, return the sum of all XOR totals for every subset of nums.\nNote: Subsets with the same elements should be counted multiple times.\nAn array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.\n\nExample 1:\nInput: nums = [1,3]\nOutput: 6\nExplanation: The 4 subsets of [1,3] are:\n- The empty subset has an XOR total of 0.\n- [1] has an XOR total of 1.\n- [3] has an XOR total of 3.\n- [1,3] has an XOR total of 1 XOR 3 = 2.\n0 + 1 + 3 + 2 = 6\n\nExample 2:\nInput: nums = [5,1,6]\nOutput: 28\nExplanation: The 8 subsets of [5,1,6] are:\n- The empty subset has an XOR total of 0.\n- [5] has an XOR total of 5.\n- [1] has an XOR total of 1.\n- [6] has an XOR total of 6.\n- [5,1] has an XOR total of 5 XOR 1 = 4.\n- [5,6] has an XOR total of 5 XOR 6 = 3.\n- [1,6] has an XOR total of 1 XOR 6 = 7.\n- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.\n0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28\n\nExample 3:\nInput: nums = [3,4,5,6,7,8]\nOutput: 480\nExplanation: The sum of all XOR totals for every subset is 480.\n\nConstraints:\n- 1 <= nums.length <= 12\n- 1 <= nums[i] <= 20"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def subsetXORSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # given there are k (k >= 1) nums of which ith bit is 1,\n # the bit contributes to sum is:\n # (nCr(k, 1) + nCr(k, 3) + ...) * (nCr(n - k, 0) + nCr(n - k, 1) + ...) * 2^i\n # = 2^(k-1) * 2^(n-k) = 2^(n-1) * 2^i\n result = 0\n for x in nums:\n result |= x\n return result * 2**(len(nums)-1)\n"}} diff --git a/cp/cp-11222.jsonl b/cp/cp-11222.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f2fdd1f40b8a7baaa6359cfd9dd608674be0ba0e --- /dev/null +++ b/cp/cp-11222.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11222", "name": "LeetCode 1864: Minimum Number Of Swaps To Make The Binary String Alternating"} +{"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: Minimum Number of Swaps to Make the Binary String Alternating (Difficulty: Medium)\nTags: String, Greedy\n\nGiven a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible.\nThe string is called alternating if no two adjacent characters are equal. For example, the strings \"010\" and \"1010\" are alternating, while the string \"0100\" is not.\nAny two characters may be swapped, even if they are not adjacent.\n\nExample 1:\nInput: s = \"111000\"\nOutput: 1\nExplanation: Swap positions 1 and 4: \"111000\" -> \"101010\"\nThe string is now alternating.\n\nExample 2:\nInput: s = \"010\"\nOutput: 0\nExplanation: The string is already alternating, no swaps are needed.\n\nExample 3:\nInput: s = \"1110\"\nOutput: -1\n\nConstraints:\n- 1 <= s.length <= 1000\n- s[i] is either '0' or '1'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minSwaps(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n def cost(s, x): \n diff = 0 \n for c in s:\n diff += int(c) != x\n x ^= 1\n return diff//2\n \n ones = s.count('1')\n zeros = len(s)-ones \n if abs(ones-zeros) > 1:\n return -1\n if ones > zeros:\n return cost(s, 1)\n if ones < zeros:\n return cost(s, 0)\n return min(cost(s, 1), cost(s, 0))\n"}} diff --git a/cp/cp-11223.jsonl b/cp/cp-11223.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ba3df456a7400b7a2255dce12b004632e67895f1 --- /dev/null +++ b/cp/cp-11223.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11223", "name": "LeetCode 1865: Finding Pairs With A Certain Sum"} +{"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: Finding Pairs With a Certain Sum (Difficulty: Medium)\nTags: Array, Hash Table, Design\n\nYou are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types:\nImplement the FindSumPairs class:\n\nExample 1:\nInput\n[\"FindSumPairs\", \"count\", \"add\", \"count\", \"count\", \"add\", \"add\", \"count\"]\n[[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]]\nOutput\n[null, 8, null, 2, 1, null, null, 11]\n\nExplanation\nFindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]);\nfindSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4\nfindSumPairs.add(3, 2); // now nums2 = [1,4,5,4,5,4]\nfindSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5\nfindSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1\nfindSumPairs.add(0, 1); // now nums2 = [2,4,5,4,5,4]\nfindSumPairs.add(1, 1); // now nums2 = [2,5,5,4,5,4]\nfindSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4\n\nConstraints:\n- 1 <= nums1.length <= 1000\n- 1 <= nums2.length <= 10^5\n- 1 <= nums1[i] <= 10^9\n- 1 <= nums2[i] <= 10^5\n- 0 <= index < nums2.length\n- 1 <= val <= 10^5\n- 1 <= tot <= 10^9\n- At most 1000 calls are made to add and count each."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(n1 + n2)\n# add: O(1)\n# count: O(n1)\n# Space: O(n1 + n2)\n\nimport collections\n\n\nclass FindSumPairs(object):\n\n def __init__(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n \"\"\"\n self.__nums2 = nums2\n self.__count1 = collections.Counter(nums1)\n self.__count2 = collections.Counter(nums2)\n\n def add(self, index, val):\n \"\"\"\n :type index: int\n :type val: int\n :rtype: None\n \"\"\"\n self.__count2[self.__nums2[index]] -= 1\n self.__nums2[index] += val\n self.__count2[self.__nums2[index]] += 1\n\n\n def count(self, tot):\n \"\"\"\n :type tot: int\n :rtype: int\n \"\"\"\n return sum(cnt * self.__count2[tot-x] for x, cnt in self.__count1.iteritems())\n"}} diff --git a/cp/cp-11224.jsonl b/cp/cp-11224.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..297780733b1dc7bbc55084c9505678f1542963f6 --- /dev/null +++ b/cp/cp-11224.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11224", "name": "LeetCode 1866: Number Of Ways To Rearrange Sticks With K Sticks Visible"} +{"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 Ways to Rearrange Sticks With K Sticks Visible (Difficulty: Hard)\nTags: Math, Dynamic Programming, Combinatorics\n\nThere are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it.\nGiven n and k, return the number of such arrangements. Since the answer may be large, return it modulo 109 + 7.\n\nExample 1:\nInput: n = 3, k = 2\nOutput: 3\nExplanation: [1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.\nThe visible sticks are underlined.\n\nExample 2:\nInput: n = 5, k = 5\nOutput: 1\nExplanation: [1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.\nThe visible sticks are underlined.\n\nExample 3:\nInput: n = 20, k = 11\nOutput: 647427950\nExplanation: There are 647427950 (mod 109 + 7) ways to rearrange the sticks such that exactly 11 sticks are visible.\n\nConstraints:\n- 1 <= n <= 1000\n- 1 <= k <= n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * k)\n# Space: O(k)\n\nclass Solution(object):\n def rearrangeSticks(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n dp = [[0 for _ in range(k+1)] for _ in range(2)]\n dp[1][1] = 1\n for i in range(2, n+1):\n for j in range(1, min(i, k)+1):\n # choose the tallest as the last one which would be visible: dp[i-1][j-1]\n # choose the non-tallest as the last one which would be hidden: (i-1)*dp[i-1][j]\n dp[i%2][j] = (dp[(i-1)%2][j-1]+(i-1)*dp[(i-1)%2][j]) % MOD \n return dp[n%2][k]\n"}} diff --git a/cp/cp-11226.jsonl b/cp/cp-11226.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1f6f54824f463713babe8cd1eb1818f22f53202d --- /dev/null +++ b/cp/cp-11226.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11226", "name": "LeetCode 1869: Longer Contiguous Segments Of Ones Than Zeros"} +{"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: Longer Contiguous Segments of Ones than Zeros (Difficulty: Easy)\nTags: String\n\nGiven a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise.\nNote that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's.\n\nExample 1:\nInput: s = \"1101\"\nOutput: true\nExplanation:\nThe longest contiguous segment of 1s has length 2: \"1101\"\nThe longest contiguous segment of 0s has length 1: \"1101\"\nThe segment of 1s is longer, so return true.\n\nExample 2:\nInput: s = \"111000\"\nOutput: false\nExplanation:\nThe longest contiguous segment of 1s has length 3: \"111000\"\nThe longest contiguous segment of 0s has length 3: \"111000\"\nThe segment of 1s is not longer, so return false.\n\nExample 3:\nInput: s = \"110100010\"\nOutput: false\nExplanation:\nThe longest contiguous segment of 1s has length 2: \"110100010\"\nThe longest contiguous segment of 0s has length 3: \"110100010\"\nThe segment of 1s is not longer, so return false.\n\nConstraints:\n- 1 <= s.length <= 100\n- s[i] is either '0' or '1'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def checkZeroOnes(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n max_cnt = [0]*2\n cnt = 0\n for i in range(len(s)+1):\n if i == len(s) or (i >= 1 and s[i] != s[i-1]):\n max_cnt[int(s[i-1])] = max(max_cnt[int(s[i-1])], cnt)\n cnt = 0\n cnt += 1\n return max_cnt[0] < max_cnt[1]\n"}} diff --git a/cp/cp-11227.jsonl b/cp/cp-11227.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fba473c9ccee3b1b490dfb7358947779546e22e7 --- /dev/null +++ b/cp/cp-11227.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11227", "name": "LeetCode 1870: Minimum Speed To Arrive On Time"} +{"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: Minimum Speed to Arrive on Time (Difficulty: Medium)\nTags: Array, Binary Search\n\nYou are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride.\nEach train can only depart at an integer hour, so you may need to wait in between each train ride.\nReturn the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time.\nTests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.\n\nExample 1:\nInput: dist = [1,3,2], hour = 6\nOutput: 1\nExplanation: At speed 1:\n- The first train ride takes 1/1 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.\n- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.\n- You will arrive at exactly the 6 hour mark.\n\nExample 2:\nInput: dist = [1,3,2], hour = 2.7\nOutput: 3\nExplanation: At speed 3:\n- The first train ride takes 1/3 = 0.33333 hours.\n- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.\n- You will arrive at the 2.66667 hour mark.\n\nExample 3:\nInput: dist = [1,3,2], hour = 1.9\nOutput: -1\nExplanation: It is impossible because the earliest the third train can depart is at the 2 hour mark.\n\nConstraints:\n- n == dist.length\n- 1 <= n <= 10^5\n- 1 <= dist[i] <= 10^5\n- 1 <= hour <= 10^9\n- There will be at most two digits after the decimal point in hour."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogr), r is the range of speed\n# Space: O(1)\n\nclass Solution(object):\n def minSpeedOnTime(self, dist, hour):\n \"\"\"\n :type dist: List[int]\n :type hour: float\n :rtype: int\n \"\"\"\n def ceil(a, b):\n return (a+b-1)//b\n\n def total_time(dist, x):\n return sum(ceil(dist[i], x) for i in range(len(dist)-1)) + float(dist[-1])/x\n\n def check(dist, hour, x):\n return total_time(dist, x) <= hour\n\n MAX_SPEED = 10**7\n if not check(dist, hour, MAX_SPEED):\n return -1\n left, right = 1, MAX_SPEED\n while left <= right:\n mid = left + (right-left)//2\n if check(dist, hour, mid):\n right = mid-1\n else:\n left = mid+1\n return left\n"}} diff --git a/cp/cp-11228.jsonl b/cp/cp-11228.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0c2939e4bb17948750b27376f93fe26fd4035fe9 --- /dev/null +++ b/cp/cp-11228.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11228", "name": "LeetCode 1871: Jump Game Vii"} +{"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: Jump Game VII (Difficulty: Medium)\nTags: String, Dynamic Programming, Sliding Window, Prefix Sum\n\nYou are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled:\nReturn true if you can reach index s.length - 1 in s, or false otherwise.\n\nExample 1:\nInput: s = \"011010\", minJump = 2, maxJump = 3\nOutput: true\nExplanation:\nIn the first step, move from index 0 to index 3. \nIn the second step, move from index 3 to index 5.\n\nExample 2:\nInput: s = \"01101110\", minJump = 2, maxJump = 3\nOutput: false\n\nConstraints:\n- 2 <= s.length <= 10^5\n- s[i] is either '0' or '1'.\n- s[0] == '0'\n- 1 <= minJump <= maxJump < s.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\n# dp with line sweep solution\nclass Solution(object):\n def canReach(self, s, minJump, maxJump):\n \"\"\"\n :type s: str\n :type minJump: int\n :type maxJump: int\n :rtype: bool\n \"\"\"\n dp = [False]*len(s)\n dp[0] = True\n cnt = 0\n for i in range(1, len(s)):\n if i >= minJump:\n cnt += dp[i-minJump]\n if i > maxJump:\n cnt -= dp[i-maxJump-1]\n dp[i] = cnt > 0 and s[i] == '0'\n return dp[-1]\n\n\n# Time: O(n)\n# Space: O(n)\nimport collections\n\n\n# bfs solution\nclass Solution2(object):\n def canReach(self, s, minJump, maxJump):\n \"\"\"\n :type s: str\n :type minJump: int\n :type maxJump: int\n :rtype: bool\n \"\"\"\n q = collections.deque([0])\n reachable = 0\n while q:\n i = q.popleft()\n for j in range(max(i+minJump, reachable+1), min(i+maxJump+1, len(s))):\n if s[j] != '0':\n continue\n q.append(j)\n reachable = i+maxJump\n return i == len(s)-1\n"}} diff --git a/cp/cp-11229.jsonl b/cp/cp-11229.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9458efbe0054c55a093b8b8a460a5c4d6e596ec0 --- /dev/null +++ b/cp/cp-11229.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11229", "name": "LeetCode 1872: Stone Game Viii"} +{"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: Stone Game VIII (Difficulty: Hard)\nTags: Array, Math, Dynamic Programming, Prefix Sum, Game Theory\n\nAlice and Bob take turns playing a game, with Alice starting first.\nThere are n stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following:\nThe game stops when only one stone is left in the row.\nThe score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference.\nGiven an integer array stones of length n where stones[i] represents the value of the ith stone from the left, return the score difference between Alice and Bob if they both play optimally.\n\nExample 1:\nInput: stones = [-1,2,-3,4,-5]\r\nOutput: 5\r\nExplanation:\r\n- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of\r\n value 2 on the left. stones = [2,-5].\r\n- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on\r\n the left. stones = [-3].\r\nThe difference between their scores is 2 - (-3) = 5.\n\nExample 2:\nInput: stones = [7,-6,5,10,5,-2,-6]\r\nOutput: 13\r\nExplanation:\r\n- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a\r\n stone of value 13 on the left. stones = [13].\r\nThe difference between their scores is 13 - 0 = 13.\n\nExample 3:\nInput: stones = [-10,-12]\r\nOutput: -22\r\nExplanation:\r\n- Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her\r\n score and places a stone of value -22 on the left. stones = [-22].\r\nThe difference between their scores is (-22) - 0 = -22.\n\nConstraints:\n- n == stones.length\n- 2 <= n <= 10^5\n- -10^4 <= stones[i] <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def stoneGameVIII(self, stones):\n \"\"\"\n :type stones: List[int]\n :rtype: int\n \"\"\"\n for i in range(len(stones)-1):\n stones[i+1] += stones[i]\n return reduce(lambda curr, i: max(curr, stones[i]-curr), reversed(range(1, len(stones)-1)), stones[-1])\n"}} diff --git a/cp/cp-11231.jsonl b/cp/cp-11231.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f6f0ee905b26f96ae3488205a7a8b4d04824facc --- /dev/null +++ b/cp/cp-11231.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11231", "name": "LeetCode 1876: Substrings Of Size Three With Distinct Characters"} +{"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: Substrings of Size Three with Distinct Characters (Difficulty: Easy)\nTags: Hash Table, String, Sliding Window, Counting\n\nA string is good if there are no repeated characters.\nGiven a string s​​​​​, return the number of good substrings of length three in s​​​​​​.\nNote that if there are multiple occurrences of the same substring, every occurrence should be counted.\nA substring is a contiguous sequence of characters in a string.\n\nExample 1:\nInput: s = \"xyzzaz\"\nOutput: 1\nExplanation: There are 4 substrings of size 3: \"xyz\", \"yzz\", \"zza\", and \"zaz\". \nThe only good substring of length 3 is \"xyz\".\n\nExample 2:\nInput: s = \"aababcabc\"\nOutput: 4\nExplanation: There are 7 substrings of size 3: \"aab\", \"aba\", \"bab\", \"abc\", \"bca\", \"cab\", and \"abc\".\nThe good substrings are \"abc\", \"bca\", \"cab\", and \"abc\".\n\nConstraints:\n- 1 <= s.length <= 100\n- s​​​​​​ consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def countGoodSubstrings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n K = 3\n\n result = 0\n count = collections.Counter()\n for i in range(len(s)):\n if i >= K:\n count[s[i-K]] -= 1\n if not count[s[i-K]]:\n del count[s[i-K]]\n count[s[i]] += 1\n if len(count) == K:\n result += 1\n return result\n"}} diff --git a/cp/cp-11233.jsonl b/cp/cp-11233.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a4c3455e759b4b4f300d5f14b606a0ebf87e53c5 --- /dev/null +++ b/cp/cp-11233.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11233", "name": "LeetCode 1878: Get Biggest Three Rhombus Sums In A Grid"} +{"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: Get Biggest Three Rhombus Sums in a Grid (Difficulty: Medium)\nTags: Array, Math, Sorting, Heap (Priority Queue), Matrix, Prefix Sum\n\nYou are given an m x n integer matrix grid​​​.\nA rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:\nNote that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.\nReturn the biggest three distinct rhombus sums in the grid in descending order. If there are less than three distinct values, return all of them.\n\nExample 1:\nInput: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]\nOutput: [228,216,211]\nExplanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n- Blue: 20 + 3 + 200 + 5 = 228\n- Red: 200 + 2 + 10 + 4 = 216\n- Green: 5 + 200 + 4 + 2 = 211\n\nExample 2:\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [20,9,8]\nExplanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n- Blue: 4 + 2 + 6 + 8 = 20\n- Red: 9 (area 0 rhombus in the bottom right corner)\n- Green: 8 (area 0 rhombus in the bottom middle)\n\nExample 3:\nInput: grid = [[7,7,7]]\nOutput: [7]\nExplanation: All three possible rhombus sums are the same, so return [7].\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 50\n- 1 <= grid[i][j] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n * min(m, n))\n# Space: O(m * n)\n\nimport heapq\n\n\nclass Solution(object):\n def getBiggestThree(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: List[int]\n \"\"\"\t\n K = 3\n left = [[grid[i][j] for j in range(len(grid[i]))] for i in range(len(grid))]\n right = [[grid[i][j] for j in range(len(grid[i]))] for i in range(len(grid))]\n for i in range(1, len(grid)):\n for j in range(len(grid[0])-1):\n left[i][j] += left[i-1][j+1]\n for i in range(1, len(grid)):\n for j in range(1, len(grid[0])):\n right[i][j] += right[i-1][j-1]\n min_heap = []\n lookup = set()\n for k in range((min(len(grid), len(grid[0]))+1)//2):\n for i in range(k, len(grid)-k):\n for j in range(k, len(grid[0])-k):\n total = (((left[i][j-k]-left[i-k][j])+(right[i][j+k]-right[i-k][j])+grid[i-k][j]) + \n ((left[i+k][j]-left[i][j+k])+(right[i+k][j]-right[i][j-k])-grid[i+k][j])) if k else grid[i][j]\n if total in lookup:\n continue\n lookup.add(total)\n heapq.heappush(min_heap, total)\n if len(min_heap) == K+1: \n lookup.remove(heapq.heappop(min_heap))\n min_heap.sort(reverse=True)\n return min_heap\n"}} diff --git a/cp/cp-11234.jsonl b/cp/cp-11234.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..87c69aa66da505a4c0c102ffda0359cf854c6633 --- /dev/null +++ b/cp/cp-11234.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11234", "name": "LeetCode 1879: Minimum Xor Sum Of Two 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: Minimum XOR Sum of Two Arrays (Difficulty: Hard)\nTags: Array, Dynamic Programming, Bit Manipulation, Bitmask\n\nYou are given two integer arrays nums1 and nums2 of length n.\nThe XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed).\nRearrange the elements of nums2 such that the resulting XOR sum is minimized.\nReturn the XOR sum after the rearrangement.\n\nExample 1:\nInput: nums1 = [1,2], nums2 = [2,3]\nOutput: 2\nExplanation: Rearrange nums2 so that it becomes [3,2].\nThe XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.\n\nExample 2:\nInput: nums1 = [1,0,3], nums2 = [5,3,4]\nOutput: 8\nExplanation: Rearrange nums2 so that it becomes [5,4,3]. \nThe XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.\n\nConstraints:\n- n == nums1.length\n- n == nums2.length\n- 1 <= n <= 14\n- 0 <= nums1[i], nums2[i] <= 10^7"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(n^2)\n\n# weighted bipartite matching solution\nclass Solution(object):\n def minimumXORSum(self, nums1, nums2):\n # Template translated from:\n # https://github.com/kth-competitive-programming/kactl/blob/main/content/graph/WeightedMatching.h\n def hungarian(a): # Time: O(n^2 * m), Space: O(n + m)\n if not a:\n return 0, []\n n, m = len(a)+1, len(a[0])+1\n u, v, p, ans = [0]*n, [0]*m, [0]*m, [0]*(n-1)\n for i in range(1, n):\n p[0] = i\n j0 = 0 # add \"dummy\" worker 0\n dist, pre = [float(\"inf\")]*m, [-1]*m\n done = [False]*(m+1)\n while True: # dijkstra\n done[j0] = True\n i0, j1, delta = p[j0], None, float(\"inf\")\n for j in range(1, m):\n if done[j]:\n continue\n cur = a[i0-1][j-1]-u[i0]-v[j]\n if cur < dist[j]:\n dist[j], pre[j] = cur, j0\n if dist[j] < delta:\n delta, j1 = dist[j], j\n for j in range(m):\n if done[j]:\n u[p[j]] += delta\n v[j] -= delta\n else:\n dist[j] -= delta\n j0 = j1\n if not p[j0]:\n break\n while j0: # update alternating path\n j1 = pre[j0]\n p[j0], j0 = p[j1], j1\n for j in range(1, m):\n if p[j]:\n ans[p[j]-1] = j-1\n return -v[0], ans # min cost\n \n adj = [[0]*len(nums2) for _ in range(len(nums1))]\n for i in range(len(nums1)):\n for j in range(len(nums2)):\n adj[i][j] = nums1[i]^nums2[j]\n return hungarian(adj)[0]\n\n\n# Time: O(n * 2^n)\n# Space: O(2^n)\n# dp solution\nclass Solution2(object):\n def minimumXORSum(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: int\n \"\"\"\n dp = [(float(\"inf\"), float(\"inf\"))]*(2**len(nums2))\n dp[0] = (0, 0)\n for mask in range(len(dp)):\n bit = 1\n for i in range(len(nums2)):\n if (mask&bit) == 0:\n dp[mask|bit] = min(dp[mask|bit], (dp[mask][0]+(nums1[dp[mask][1]]^nums2[i]), dp[mask][1]+1))\n bit <<= 1\n return dp[-1][0]\n"}} diff --git a/cp/cp-11235.jsonl b/cp/cp-11235.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3e0ef851e407dfd92340beeed53a004333e28c62 --- /dev/null +++ b/cp/cp-11235.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11235", "name": "LeetCode 1880: Check If Word Equals Summation Of Two 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: Check if Word Equals Summation of Two Words (Difficulty: Easy)\nTags: String\n\nThe letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.).\nThe numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer.\nYou are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive.\nReturn true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.\n\nExample 1:\nInput: firstWord = \"acb\", secondWord = \"cba\", targetWord = \"cdb\"\nOutput: true\nExplanation:\nThe numerical value of firstWord is \"acb\" -> \"021\" -> 21.\nThe numerical value of secondWord is \"cba\" -> \"210\" -> 210.\nThe numerical value of targetWord is \"cdb\" -> \"231\" -> 231.\nWe return true because 21 + 210 == 231.\n\nExample 2:\nInput: firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aab\"\nOutput: false\nExplanation: \nThe numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aab\" -> \"001\" -> 1.\nWe return false because 0 + 0 != 1.\n\nExample 3:\nInput: firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aaaa\"\nOutput: true\nExplanation: \nThe numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aaaa\" -> \"0000\" -> 0.\nWe return true because 0 + 0 == 0.\n\nConstraints:\n- 1 <= firstWord.length, secondWord.length, targetWord.length <= 8\n- firstWord, secondWord, and targetWord consist of lowercase English letters from 'a' to 'j' inclusive."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def isSumEqual(self, firstWord, secondWord, targetWord):\n \"\"\"\n :type firstWord: str\n :type secondWord: str\n :type targetWord: str\n :rtype: bool\n \"\"\"\n def stoi(s):\n result = 0\n for c in s:\n result = result*10 + ord(c)-ord('a')\n return result\n \n return stoi(firstWord) + stoi(secondWord) == stoi(targetWord)\n"}} diff --git a/cp/cp-11236.jsonl b/cp/cp-11236.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..80edb81bfa5cdd994f5b2f3ce067acc957dbc294 --- /dev/null +++ b/cp/cp-11236.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11236", "name": "LeetCode 1881: Maximum Value After Insertion"} +{"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 Value after Insertion (Difficulty: Medium)\nTags: String, Greedy\n\nYou are given a very large integer n, represented as a string,​​​​​​ and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number.\nYou want to maximize n's numerical value by inserting x anywhere in the decimal representation of n​​​​​​. You cannot insert x to the left of the negative sign.\nReturn a string representing the maximum value of n​​​​​​ after the insertion.\n\nExample 1:\nInput: n = \"99\", x = 9\nOutput: \"999\"\nExplanation: The result is the same regardless of where you insert 9.\n\nExample 2:\nInput: n = \"-13\", x = 2\nOutput: \"-123\"\nExplanation: You can make n one of {-213, -123, -132}, and the largest of those three is -123.\n\nConstraints:\n- 1 <= n.length <= 10^5\n- 1 <= x <= 9\n- The digits in n​​​ are in the range [1, 9].\n- n is a valid representation of an integer.\n- In the case of a negative n,​​​​​​ it will begin with '-'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maxValue(self, n, x):\n \"\"\"\n :type n: str\n :type x: int\n :rtype: str\n \"\"\"\n check = (lambda i: str(x) > n[i]) if n[0] != '-' else (lambda i: str(x) < n[i])\n for i in range(len(n)):\n if check(i):\n break\n else:\n i = len(n)\n return n[:i] + str(x) + n[i:]\n"}} diff --git a/cp/cp-11237.jsonl b/cp/cp-11237.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9d618f2ffeca4eb30f48395208a90b5401515b51 --- /dev/null +++ b/cp/cp-11237.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11237", "name": "LeetCode 1882: Process Tasks Using Servers"} +{"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: Process Tasks Using Servers (Difficulty: Medium)\nTags: Array, Heap (Priority Queue)\n\nYou are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds.\nTasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty.\nAt second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index.\nIf there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above.\nA server that is assigned task j at second t will be free again at second t + tasks[j].\nBuild an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to.\nReturn the array ans​​​​.\n\nExample 1:\nInput: servers = [3,3,2], tasks = [1,2,3,2,1,2]\nOutput: [2,2,0,2,1,2]\nExplanation: Events in chronological order go as follows:\n- At second 0, task 0 is added and processed using server 2 until second 1.\n- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.\n- At second 2, task 2 is added and processed using server 0 until second 5.\n- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.\n- At second 4, task 4 is added and processed using server 1 until second 5.\n- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.\n\nExample 2:\nInput: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]\nOutput: [1,4,1,4,1,3,2]\nExplanation: Events in chronological order go as follows: \n- At second 0, task 0 is added and processed using server 1 until second 2.\n- At second 1, task 1 is added and processed using server 4 until second 2.\n- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. \n- At second 3, task 3 is added and processed using server 4 until second 7.\n- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. \n- At second 5, task 5 is added and processed using server 3 until second 7.\n- At second 6, task 6 is added and processed using server 2 until second 7.\n\nConstraints:\n- servers.length == n\n- tasks.length == m\n- 1 <= n, m <= 2 * 10^5\n- 1 <= servers[i], tasks[j] <= 2 * 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + mlogn)\n# Space: O(n)\n\nimport heapq\n\n\nclass Solution(object):\n def assignTasks(self, servers, tasks):\n \"\"\"\n :type servers: List[int]\n :type tasks: List[int]\n :rtype: List[int]\n \"\"\"\n idle = [(servers[i], i) for i in range(len(servers))]\n working = []\n heapq.heapify(idle)\n result = []\n t = 0\n for i in range(len(tasks)):\n t = max(t, i) if idle else working[0][0]\n while working and working[0][0] <= t:\n _, w, idx = heapq.heappop(working)\n heapq.heappush(idle, (w, idx))\n w, idx = heapq.heappop(idle)\n heapq.heappush(working, (t+tasks[i], w, idx))\n result.append(idx)\n return result\n"}} diff --git a/cp/cp-11238.jsonl b/cp/cp-11238.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fcbbd2a9d48b1545b55b093a7ecdd063bc0037e6 --- /dev/null +++ b/cp/cp-11238.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11238", "name": "LeetCode 1883: Minimum Skips To Arrive At Meeting On Time"} +{"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: Minimum Skips to Arrive at Meeting On Time (Difficulty: Hard)\nTags: Array, Dynamic Programming\n\nYou are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at.\nAfter you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting.\nHowever, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks.\nReturn the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.\n\nExample 1:\nInput: dist = [1,3,2], speed = 4, hoursBefore = 2\nOutput: 1\nExplanation:\nWithout skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.\nYou can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.\nNote that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.\n\nExample 2:\nInput: dist = [7,3,5,5], speed = 2, hoursBefore = 10\nOutput: 2\nExplanation:\nWithout skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.\nYou can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours.\n\nExample 3:\nInput: dist = [7,3,5,5], speed = 1, hoursBefore = 10\nOutput: -1\nExplanation: It is impossible to arrive at the meeting on time even if you skip all the rests.\n\nConstraints:\n- n == dist.length\n- 1 <= n <= 1000\n- 1 <= dist[i] <= 10^5\n- 1 <= speed <= 10^6\n- 1 <= hoursBefore <= 10^7"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def minSkips(self, dist, speed, hoursBefore):\n \"\"\"\n :type dist: List[int]\n :type speed: int\n :type hoursBefore: int\n :rtype: int\n \"\"\"\n def ceil(a, b):\n return (a+b-1)//b\n\n dp = [0]*((len(dist)-1)+1) # dp[i]: (min time by i skips) * speed\n for i, d in enumerate(dist):\n for j in reversed(range(len(dp))):\n dp[j] = ceil(dp[j]+d, speed)*speed if i < len(dist)-1 else dp[j]+d\n if j-1 >= 0:\n dp[j] = min(dp[j], dp[j-1]+d)\n target = hoursBefore*speed\n for i in range(len(dist)):\n if dp[i] <= target:\n return i\n return -1\n"}} diff --git a/cp/cp-11239.jsonl b/cp/cp-11239.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..aa645918922c98fd5076ca2c8be6154a93a248d3 --- /dev/null +++ b/cp/cp-11239.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11239", "name": "LeetCode 1884: Egg Drop With 2 Eggs And N Floors"} +{"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: Egg Drop With 2 Eggs and N Floors (Difficulty: Medium)\nTags: Math, Dynamic Programming\n\nYou are given two identical eggs and you have access to a building with n floors labeled from 1 to n.\nYou know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.\nIn each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.\nReturn the minimum number of moves that you need to determine with certainty what the value of f is.\n\nExample 1:\nInput: n = 2\nOutput: 2\nExplanation: We can drop the first egg from floor 1 and the second egg from floor 2.\nIf the first egg breaks, we know that f = 0.\nIf the second egg breaks but the first egg didn't, we know that f = 1.\nOtherwise, if both eggs survive, we know that f = 2.\n\nExample 2:\nInput: n = 100\nOutput: 14\nExplanation: One optimal strategy is:\n- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.\n- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.\n- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.\nRegardless of the outcome, it takes at most 14 drops to determine f.\n\nConstraints:\n- 1 <= n <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nimport math\n\n\n# see the proof: https://www.geeksforgeeks.org/puzzle-set-35-2-eggs-and-100-floors/\nclass Solution(object):\n def twoEggDrop(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n return int(math.ceil((-1+(1+8*n)**0.5)/2))\n \n\n# Time: O(k * n^2)\n# Space: O(n)\nclass Solution2(object):\n def twoEggDrop(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n K = 2\n dp = [[float(\"inf\") for j in range(n+1)] for _ in range(2)]\n dp[1] = [j for j in range(n+1)]\n for i in range(2, K+1):\n dp[i%2][0] = 0\n for j in range(1, n+1):\n for k in range(1, j+1):\n dp[i%2][j] = min(dp[i%2][j], 1+max(dp[(i-1)%2][k-1], dp[i%2][j-k]))\n return dp[K%2][n]\n"}} diff --git a/cp/cp-11241.jsonl b/cp/cp-11241.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..92e0fb8da91f64482b3614d8e35044f9597e3ad7 --- /dev/null +++ b/cp/cp-11241.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11241", "name": "LeetCode 1886: Determine Whether Matrix Can Be Obtained By Rotation"} +{"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: Determine Whether Matrix Can Be Obtained By Rotation (Difficulty: Easy)\nTags: Array, Matrix\n\nGiven two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise.\n\nExample 1:\nInput: mat = [[0,1],[1,0]], target = [[1,0],[0,1]]\nOutput: true\nExplanation: We can rotate mat 90 degrees clockwise to make mat equal target.\n\nExample 2:\nInput: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]\nOutput: false\nExplanation: It is impossible to make mat equal to target by rotating mat.\n\nExample 3:\nInput: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]\nOutput: true\nExplanation: We can rotate mat 90 degrees clockwise two times to make mat equal target.\n\nConstraints:\n- n == mat.length == target.length\n- n == mat[i].length == target[i].length\n- 1 <= n <= 10\n- mat[i][j] and target[i][j] are either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def findRotation(self, mat, target):\n \"\"\"\n :type mat: List[List[int]]\n :type target: List[List[int]]\n :rtype: bool\n \"\"\"\n checks = [lambda i, j: mat[i][j] == target[i][j],\n lambda i, j: mat[i][j] == target[j][-1-i],\n lambda i, j: mat[i][j] == target[-1-i][-1-j],\n lambda i, j: mat[i][j] == target[-1-j][i]]\n traverse = lambda check: all(check(i, j) for i in range(len(mat)) for j in range(len(mat[0])))\n return any(traverse(check) for check in checks)\n"}} diff --git a/cp/cp-11242.jsonl b/cp/cp-11242.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..89f33a49aded6fdd364aa5383f04317780a87fce --- /dev/null +++ b/cp/cp-11242.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11242", "name": "LeetCode 1887: Reduction Operations To Make The Array Elements Equal"} +{"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: Reduction Operations to Make the Array Elements Equal (Difficulty: Medium)\nTags: Array, Sorting\n\nGiven an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps:\nReturn the number of operations to make all elements in nums equal.\n\nExample 1:\nInput: nums = [5,1,3]\nOutput: 3\nExplanation: It takes 3 operations to make all elements in nums equal:\n1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].\n2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].\n3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].\n\nExample 2:\nInput: nums = [1,1,1]\nOutput: 0\nExplanation: All elements in nums are already equal.\n\nExample 3:\nInput: nums = [1,1,2,2,3]\nOutput: 4\nExplanation: It takes 4 operations to make all elements in nums equal:\n1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].\n2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].\n3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].\n4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].\n\nConstraints:\n- 1 <= nums.length <= 5 * 10^4\n- 1 <= nums[i] <= 5 * 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def reductionOperations(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums.sort()\n result = curr = 0\n for i in range(1, len(nums)): \n if nums[i-1] < nums[i]:\n curr += 1\n result += curr\n return result\n"}} diff --git a/cp/cp-11243.jsonl b/cp/cp-11243.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ab39525aa1984fcc3a3bcfe79535af24e4410c56 --- /dev/null +++ b/cp/cp-11243.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11243", "name": "LeetCode 1888: Minimum Number Of Flips To Make The Binary String Alternating"} +{"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: Minimum Number of Flips to Make the Binary String Alternating (Difficulty: Medium)\nTags: String, Dynamic Programming, Sliding Window\n\nYou are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:\nReturn the minimum number of type-2 operations you need to perform such that s becomes alternating.\nThe string is called alternating if no two adjacent characters are equal.\n\nExample 1:\nInput: s = \"111000\"\nOutput: 2\nExplanation: Use the first operation two times to make s = \"100011\".\nThen, use the second operation on the third and sixth elements to make s = \"101010\".\n\nExample 2:\nInput: s = \"010\"\nOutput: 0\nExplanation: The string is already alternating.\n\nExample 3:\nInput: s = \"1110\"\nOutput: 1\nExplanation: Use the second operation on the second element to make s = \"1010\".\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s[i] is either '0' or '1'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minFlips(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result = float(\"inf\")\n cnt1 = cnt2 = 0\n for i in range(2*len(s)-1 if len(s)%2 else len(s)):\n if i >= len(s):\n cnt1 -= int(s[i%len(s)])^((i-len(s))%2)^0\n cnt2 -= int(s[i%len(s)])^((i-len(s))%2)^1\n cnt1 += int(s[i%len(s)])^(i%2)^0\n cnt2 += int(s[i%len(s)])^(i%2)^1\n if i >= len(s)-1:\n result = min(result, cnt1, cnt2)\n return result\n"}} diff --git a/cp/cp-11244.jsonl b/cp/cp-11244.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7adf2ecef4c4462864aa443e2c9841c3de1b320c --- /dev/null +++ b/cp/cp-11244.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11244", "name": "LeetCode 1889: Minimum Space Wasted From Packaging"} +{"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: Minimum Space Wasted From Packaging (Difficulty: Hard)\nTags: Array, Binary Search, Sorting, Prefix Sum\n\nYou have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box.\nThe package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces.\nYou want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes.\nReturn the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 109 + 7.\n\nExample 1:\nInput: packages = [2,3,5], boxes = [[4,8],[2,8]]\nOutput: 6\nExplanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.\nThe total waste is (4-2) + (4-3) + (8-5) = 6.\n\nExample 2:\nInput: packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]\nOutput: -1\nExplanation: There is no box that the package of size 5 can fit in.\n\nExample 3:\nInput: packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]\nOutput: 9\nExplanation: It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.\nThe total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.\n\nConstraints:\n- n == packages.length\n- m == boxes.length\n- 1 <= n <= 10^5\n- 1 <= m <= 10^5\n- 1 <= packages[i] <= 10^5\n- 1 <= boxes[j].length <= 10^5\n- 1 <= boxes[j][k] <= 10^5\n- sum(boxes[j].length) <= 10^5\n- The elements in boxes[j] are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(mlogm + nlogn + mlogn)\n# Space: O(1)\n\nimport bisect\n\n\nclass Solution(object):\n def minWastedSpace(self, packages, boxes):\n \"\"\"\n :type packages: List[int]\n :type boxes: List[List[int]]\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n INF = float(\"inf\")\n\n packages.sort()\n result = INF\n for box in boxes:\n box.sort()\n if box[-1] < packages[-1]:\n continue\n curr = left = 0\n for b in box:\n right = bisect.bisect_right(packages, b, left)\n curr += b * (right-left)\n left = right\n result = min(result, curr)\n return (result-sum(packages))%MOD if result != INF else -1\n"}} diff --git a/cp/cp-11246.jsonl b/cp/cp-11246.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8dd09637548b49675aa1cd498455b3ea254efa0d --- /dev/null +++ b/cp/cp-11246.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11246", "name": "LeetCode 1893: Check If All The Integers In A Range Are Covered"} +{"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: Check if All the Integers in a Range Are Covered (Difficulty: Easy)\nTags: Array, Hash Table, Prefix Sum\n\nYou are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi.\nReturn true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise.\nAn integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi.\n\nExample 1:\nInput: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5\nOutput: true\nExplanation: Every integer between 2 and 5 is covered:\n- 2 is covered by the first range.\n- 3 and 4 are covered by the second range.\n- 5 is covered by the third range.\n\nExample 2:\nInput: ranges = [[1,10],[10,20]], left = 21, right = 21\nOutput: false\nExplanation: 21 is not covered by any range.\n\nConstraints:\n- 1 <= ranges.length <= 50\n- 1 <= starti <= endi <= 50\n- 1 <= left <= right <= 50"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + r)\n# Space: O(r)\n\n# if r is small, this is better\nclass Solution(object):\n def isCovered(self, ranges, left, right):\n \"\"\"\n :type ranges: List[List[int]]\n :type left: int\n :type right: int\n :rtype: bool\n \"\"\"\n RANGE_SIZE = 50\n\n interval = [0]*(RANGE_SIZE+1)\n for l, r in ranges:\n interval[l-1] += 1\n interval[(r-1)+1] -= 1\n cnt = 0\n for i in range((right-1)+1):\n cnt += interval[i]\n if i >= left-1 and not cnt:\n return False\n return True\n\n\n# Time: O(nlogn)\n# Space: O(1)\n# if r is big, this is better\nclass Solution2(object):\n def isCovered(self, ranges, left, right):\n \"\"\"\n :type ranges: List[List[int]]\n :type left: int\n :type right: int\n :rtype: bool\n \"\"\"\n ranges.sort()\n for l, r in ranges:\n if l <= left <= r:\n left = r+1\n return left > right\n\n\n# Time: O(n * r)\n# Space: O(1)\nclass Solution3(object):\n def isCovered(self, ranges, left, right):\n \"\"\"\n :type ranges: List[List[int]]\n :type left: int\n :type right: int\n :rtype: bool\n \"\"\"\n return all(any(l <= i <= r for l, r in ranges) for i in range(left, right+1))\n"}} diff --git a/cp/cp-11247.jsonl b/cp/cp-11247.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..10755bdd2cba28531a69c12e1346b4cb7d8e5e03 --- /dev/null +++ b/cp/cp-11247.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11247", "name": "LeetCode 1894: Find The Student That Will Replace The Chalk"} +{"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 the Student that Will Replace the Chalk (Difficulty: Medium)\nTags: Array, Binary Search, Simulation, Prefix Sum\n\nThere are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again.\nYou are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then the student number i will be asked to replace the chalk.\nReturn the index of the student that will replace the chalk pieces.\n\nExample 1:\nInput: chalk = [5,1,5], k = 22\nOutput: 0\nExplanation: The students go in turns as follows:\n- Student number 0 uses 5 chalk, so k = 17.\n- Student number 1 uses 1 chalk, so k = 16.\n- Student number 2 uses 5 chalk, so k = 11.\n- Student number 0 uses 5 chalk, so k = 6.\n- Student number 1 uses 1 chalk, so k = 5.\n- Student number 2 uses 5 chalk, so k = 0.\nStudent number 0 does not have enough chalk, so they will have to replace it.\n\nExample 2:\nInput: chalk = [3,4,1,2], k = 25\nOutput: 1\nExplanation: The students go in turns as follows:\n- Student number 0 uses 3 chalk so k = 22.\n- Student number 1 uses 4 chalk so k = 18.\n- Student number 2 uses 1 chalk so k = 17.\n- Student number 3 uses 2 chalk so k = 15.\n- Student number 0 uses 3 chalk so k = 12.\n- Student number 1 uses 4 chalk so k = 8.\n- Student number 2 uses 1 chalk so k = 7.\n- Student number 3 uses 2 chalk so k = 5.\n- Student number 0 uses 3 chalk so k = 2.\nStudent number 1 does not have enough chalk, so they will have to replace it.\n\nConstraints:\n- chalk.length == n\n- 1 <= n <= 10^5\n- 1 <= chalk[i] <= 10^5\n- 1 <= k <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def chalkReplacer(self, chalk, k):\n \"\"\"\n :type chalk: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n k %= sum(chalk)\n for i, x in enumerate(chalk):\n if k < x:\n return i\n k -= x\n return -1\n"}} diff --git a/cp/cp-11248.jsonl b/cp/cp-11248.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5aca12e1535948f309cadfa41e556a6eb5dbc6c3 --- /dev/null +++ b/cp/cp-11248.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11248", "name": "LeetCode 1895: Largest Magic Square"} +{"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: Largest Magic Square (Difficulty: Medium)\nTags: Array, Matrix, Prefix Sum\n\nA k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square.\nGiven an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid.\n\nExample 1:\nInput: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]\nOutput: 3\nExplanation: The largest magic square has a size of 3.\nEvery row sum, column sum, and diagonal sum of this magic square is equal to 12.\n- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12\n- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12\n- Diagonal sums: 5+4+3 = 6+4+2 = 12\n\nExample 2:\nInput: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]\nOutput: 2\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 50\n- 1 <= grid[i][j] <= 10^6"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(max(m, n) * min(m, n)^3)\n# Space: O(m + n)\n\nclass Solution(object):\n def largestMagicSquare(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n def get_sum(prefix, a, b):\n return prefix[b+1]-prefix[a]\n\n def check(grid, prefix_row, prefix_col, l, i, j):\n diag, anti_diag = 0, 0\n for d in range(l):\n diag += grid[i+d][j+d]\n anti_diag += grid[i+d][j+l-1-d]\n if diag != anti_diag:\n return False\n for ni in range(i, i+l):\n if diag != get_sum(prefix_row[ni], j, j+l-1):\n return False\n for nj in range(j, j+l):\n if diag != get_sum(prefix_col[nj], i, i+l-1):\n return False \n return True\n\n prefix_row = [[0]*(len(grid[0])+1) for _ in range(len(grid))]\n prefix_col = [[0]*(len(grid)+1) for _ in range(len(grid[0]))]\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n prefix_row[i][j+1] = prefix_row[i][j] + grid[i][j]\n prefix_col[j][i+1] = prefix_col[j][i] + grid[i][j]\n for l in reversed(range(1, min(len(grid), len(grid[0]))+1)):\n for i in range(len(grid)-(l-1)):\n for j in range(len(grid[0])-(l-1)):\n if check(grid, prefix_row, prefix_col, l, i, j):\n return l\n return 1\n"}} diff --git a/cp/cp-11249.jsonl b/cp/cp-11249.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7e28c18f59521d3fb515d7f61597517268388f57 --- /dev/null +++ b/cp/cp-11249.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11249", "name": "LeetCode 1896: Minimum Cost To Change The Final Value Of Expression"} +{"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: Minimum Cost to Change the Final Value of Expression (Difficulty: Hard)\nTags: Math, String, Dynamic Programming, Stack\n\nYou are given a valid boolean expression as a string expression consisting of the characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'.\nReturn the minimum cost to change the final value of the expression.\nThe cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows:\nNote: '&' does not take precedence over '|' in the order of calculation. Evaluate parentheses first, then in left-to-right order.\n\nExample 1:\nInput: expression = \"1&(0|1)\"\nOutput: 1\nExplanation: We can turn \"1&(0|1)\" into \"1&(0&1)\" by changing the '|' to a '&' using 1 operation.\nThe new expression evaluates to 0.\n\nExample 2:\nInput: expression = \"(0&0)&(0&0&0)\"\nOutput: 3\nExplanation: We can turn \"(0&0)&(0&0&0)\" into \"(0|1)|(0&0&0)\" using 3 operations.\nThe new expression evaluates to 1.\n\nExample 3:\nInput: expression = \"(0|(1|0&1))\"\nOutput: 1\nExplanation: We can turn \"(0|(1|0&1))\" into \"(0|(0|0&1))\" using 1 operation.\nThe new expression evaluates to 0.\n\nConstraints:\n- 1 <= expression.length <= 10^5\n- expression only contains '1','0','&','|','(', and ')'\n- All parentheses are properly matched.\n- There will be no empty parentheses (i.e: \"()\" is not a substring of expression)."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def minOperationsToFlip(self, expression):\n \"\"\"\n :type expression: str\n :rtype: int\n \"\"\"\n def compute(operands, operators):\n right, left = operands.pop(), operands.pop()\n operands.append(ops[operators.pop()](left, right))\n\n ops = {'&':lambda x, y: [min(x[0], y[0]), min(x[1]+y[1], min(x[1], y[1])+1)],\n '|':lambda x, y: [min(x[0]+y[0], min(x[0], y[0])+1), min(x[1], y[1])]}\n precedence = {'&':0, '|':0}\n operands, operators = [], []\n for c in expression:\n if c.isdigit():\n operands.append([int(c != '0'), int(c != '1')])\n elif c == '(':\n operators.append(c)\n elif c == ')':\n while operators[-1] != '(':\n compute(operands, operators)\n operators.pop()\n elif c in precedence:\n while operators and operators[-1] in precedence and \\\n precedence[operators[-1]] >= precedence[c]:\n compute(operands, operators)\n operators.append(c)\n while operators:\n compute(operands, operators)\n return max(operands[-1])\n\n\n# Time: O(n)\n# Space: O(n)\nclass Solution2(object):\n def minOperationsToFlip(self, expression):\n \"\"\"\n :type expression: str\n :rtype: int\n \"\"\"\n stk = [[None]*3]\n for c in expression: \n if c == '(': \n stk.append([None]*3)\n elif c in {')', '0', '1'}:\n if c == ')':\n dp0, dp1, _ = stk.pop()\n else:\n dp0, dp1 = int(c != '0'), int(c != '1')\n if stk[-1][2] == '&':\n stk[-1] = [min(stk[-1][0], dp0),\n min(stk[-1][1]+dp1, min(stk[-1][1], dp1)+1),\n None]\n elif stk[-1][2] == '|':\n stk[-1] = [min(stk[-1][0]+dp0, min(stk[-1][0], dp0)+1),\n min(stk[-1][1], dp1),\n None]\n else: # operand\n stk[-1] = [dp0, dp1, None]\n else:\n stk[-1][2] = c\n return max(stk[0][0], stk[0][1])\n"}} diff --git a/cp/cp-11250.jsonl b/cp/cp-11250.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a12e916563ecb24078b9c703aac7fc8cba2619df --- /dev/null +++ b/cp/cp-11250.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11250", "name": "LeetCode 1897: Redistribute Characters To Make All Strings Equal"} +{"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: Redistribute Characters to Make All Strings Equal (Difficulty: Easy)\nTags: Hash Table, String, Counting\n\nYou are given an array of strings words (0-indexed).\nIn one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j].\nReturn true if you can make every string in words equal using any number of operations, and false otherwise.\n\nExample 1:\nInput: words = [\"abc\",\"aabc\",\"bc\"]\nOutput: true\nExplanation: Move the first 'a' in words[1] to the front of words[2],\nto make words[1] = \"abc\" and words[2] = \"abc\".\nAll the strings are now equal to \"abc\", so return true.\n\nExample 2:\nInput: words = [\"ab\",\"a\"]\nOutput: false\nExplanation: It is impossible to make all the strings equal using the operation.\n\nConstraints:\n- 1 <= words.length <= 100\n- 1 <= words[i].length <= 100\n- words[i] consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def makeEqual(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: bool\n \"\"\"\n cnt = collections.defaultdict(int)\n for w in words:\n for c in w:\n cnt[c] += 1\n return all(v%len(words) == 0 for v in cnt.itervalues())\n"}} diff --git a/cp/cp-11251.jsonl b/cp/cp-11251.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3cc61b5b415ff6f7816e02cd3d2bbc70566e3d03 --- /dev/null +++ b/cp/cp-11251.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11251", "name": "LeetCode 1898: Maximum Number Of Removable Characters"} +{"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 Number of Removable Characters (Difficulty: Medium)\nTags: Array, Two Pointers, String, Binary Search\n\nYou are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed).\nYou want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence.\nReturn the maximum k you can choose such that p is still a subsequence of s after the removals.\nA subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.\n\nExample 1:\nInput: s = \"abcacb\", p = \"ab\", removable = [3,1,0]\nOutput: 2\nExplanation: After removing the characters at indices 3 and 1, \"abcacb\" becomes \"accb\".\n\"ab\" is a subsequence of \"accb\".\nIf we remove the characters at indices 3, 1, and 0, \"abcacb\" becomes \"ccb\", and \"ab\" is no longer a subsequence.\nHence, the maximum k is 2.\n\nExample 2:\nInput: s = \"abcbddddd\", p = \"abcd\", removable = [3,2,1,4,5,6]\nOutput: 1\nExplanation: After removing the character at index 3, \"abcbddddd\" becomes \"abcddddd\".\n\"abcd\" is a subsequence of \"abcddddd\".\n\nExample 3:\nInput: s = \"abcab\", p = \"abc\", removable = [0,1,2,3,4]\nOutput: 0\nExplanation: If you remove the first index in the array removable, \"abc\" is no longer a subsequence.\n\nConstraints:\n- 1 <= p.length <= s.length <= 10^5\n- 0 <= removable.length < s.length\n- 0 <= removable[i] < s.length\n- p is a subsequence of s.\n- s and p both consist of lowercase English letters.\n- The elements in removable are distinct."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(rlogn)\n# Space: O(r)\n\n# if r = O(1), this is better\nclass Solution(object):\n def maximumRemovals(self, s, p, removable):\n \"\"\"\n :type s: str\n :type p: str\n :type removable: List[int]\n :rtype: int\n \"\"\"\n def check(s, p, removable, x):\n lookup = set(removable[i] for i in range(x))\n j = 0\n for i in range(len(s)):\n if i in lookup or s[i] != p[j]:\n continue\n j += 1\n if j == len(p):\n return True\n return False\n\n left, right = 0, len(removable)\n while left <= right:\n mid = left + (right-left)//2\n if not check(s, p, removable, mid):\n right = mid-1\n else:\n left = mid+1\n return right\n\n\n# Time: O(rlogn)\n# Space: O(n)\n# if r = O(n), this is better\nclass Solution2(object):\n def maximumRemovals(self, s, p, removable):\n \"\"\"\n :type s: str\n :type p: str\n :type removable: List[int]\n :rtype: int\n \"\"\"\n def check(s, p, lookup, x):\n j = 0\n for i in range(len(s)):\n if lookup[i] <= x or s[i] != p[j]:\n continue\n j += 1\n if j == len(p):\n return True\n return False\n\n lookup = [float(\"inf\")]*len(s)\n for i, r in enumerate(removable):\n lookup[r] = i+1\n left, right = 0, len(removable)\n while left <= right:\n mid = left + (right-left)//2\n if not check(s, p, lookup, mid):\n right = mid-1\n else:\n left = mid+1\n return right\n"}} diff --git a/cp/cp-11252.jsonl b/cp/cp-11252.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9504dcb5b5b1f8a2423ff1fdf53da85d05d967a7 --- /dev/null +++ b/cp/cp-11252.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11252", "name": "LeetCode 1899: Merge Triplets To Form Target Triplet"} +{"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 Triplets to Form Target Triplet (Difficulty: Medium)\nTags: Array, Greedy\n\nA triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain.\nTo obtain target, you may apply the following operation on triplets any number of times (possibly zero):\nReturn true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.\n\nExample 1:\nInput: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]\nOutput: true\nExplanation: Perform the following operations:\n- Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]]\nThe target triplet [2,7,5] is now an element of triplets.\n\nExample 2:\nInput: triplets = [[3,4,5],[4,5,6]], target = [3,2,5]\nOutput: false\nExplanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets.\n\nExample 3:\nInput: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5]\nOutput: true\nExplanation: Perform the following operations:\n- Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]].\n- Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]].\nThe target triplet [5,5,5] is now an element of triplets.\n\nConstraints:\n- 1 <= triplets.length <= 10^5\n- triplets[i].length == target.length == 3\n- 1 <= ai, bi, ci, x, y, z <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def mergeTriplets(self, triplets, target):\n \"\"\"\n :type triplets: List[List[int]]\n :type target: List[int]\n :rtype: bool\n \"\"\"\n result = [0]*3\n for t in triplets:\n if all(t[i] <= target[i] for i in range(3)):\n result = [max(result[i], t[i]) for i in range(3)]\n return result == target\n"}} diff --git a/cp/cp-11253.jsonl b/cp/cp-11253.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4a945d99559dac15fdee8f83634a69bb13c3170e --- /dev/null +++ b/cp/cp-11253.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11253", "name": "LeetCode 1900: The Earliest And Latest Rounds Where Players Compete"} +{"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: The Earliest and Latest Rounds Where Players Compete (Difficulty: Hard)\nTags: Dynamic Programming, Memoization\n\nThere is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.).\nThe tournament consists of multiple rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round.\nAfter each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order).\nThe players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round.\nGiven the integers n, firstPlayer, and secondPlayer, return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively.\n\nExample 1:\nInput: n = 11, firstPlayer = 2, secondPlayer = 4\nOutput: [3,4]\nExplanation:\nOne possible scenario which leads to the earliest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 2, 3, 4, 5, 6, 11\nThird round: 2, 3, 4\nOne possible scenario which leads to the latest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 1, 2, 3, 4, 5, 6\nThird round: 1, 2, 4\nFourth round: 2, 4\n\nExample 2:\nInput: n = 5, firstPlayer = 1, secondPlayer = 5\nOutput: [1,1]\nExplanation: The players numbered 1 and 5 compete in the first round.\nThere is no way to make them compete in any other round.\n\nConstraints:\n- 2 <= n <= 28\n- 1 <= firstPlayer < secondPlayer <= n"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2) states * O(n^2) per state = O(n^4)\n# Space: O(n^2 + (n/2)^2 + (n/4)^2 + ... ) = O(n^2)\n\nclass Solution(object):\n def earliestAndLatest(self, n, firstPlayer, secondPlayer):\n \"\"\"\n :type n: int\n :type firstPlayer: int\n :type secondPlayer: int\n :rtype: List[int]\n \"\"\"\n def memoization(t, l, r, lookup):\n # t: total number of players,\n # l: number of players left to the nearest top2 player,\n # r: number of players right to the nearest top2 player\n if (t, l, r) not in lookup:\n if l == r:\n return (1, 1)\n if l > r: # make sure l <= r\n l, r, = r, l\n result = [float(\"inf\"), 0]\n for i in range(l+1):\n l_win_cnt, l_lose_cnt, nt, pair_cnt = i+1, l-i, (t+1)//2, t//2\n min_j = max(l_lose_cnt, r-(pair_cnt-l_lose_cnt)) # j >= l_lose_cnt and j >= r-(pair_cnt-l_lose_cnt)\n max_j = min(r-l_win_cnt, (nt-l_win_cnt)-1) # j <= r-l_win_cnt and j <= (nt-l_win_cnt)-1\n for j in range(min_j, max_j+1):\n tmp = memoization(nt, i, j, lookup)\n result = min(result[0], tmp[0]+1), max(result[1], tmp[1]+1)\n lookup[t, l, r] = result\n return lookup[t, l, r]\n \n return memoization(n, firstPlayer-1, n-secondPlayer, {})\n"}} diff --git a/cp/cp-11254.jsonl b/cp/cp-11254.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a5373f4ab25bed6c9bd1b88386b1a29f7d75ea9b --- /dev/null +++ b/cp/cp-11254.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11254", "name": "LeetCode 1901: Find A Peak Element 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: Find a Peak Element II (Difficulty: Medium)\nTags: Array, Binary Search, Matrix\n\nA peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom.\nGiven a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j].\nYou may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell.\nYou must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.\n\nExample 1:\nInput: mat = [[1,4],[3,2]]\nOutput: [0,1]\nExplanation: Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers.\n\nExample 2:\nInput: mat = [[10,20,15],[21,30,14],[7,16,32]]\nOutput: [1,1]\nExplanation: Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.\n\nConstraints:\n- m == mat.length\n- n == mat[i].length\n- 1 <= m, n <= 500\n- 1 <= mat[i][j] <= 10^5\n- No two adjacent cells are equal."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(min(n, m) * log(max(n, m)))\n# Space: O(1)\n\nclass Solution(object):\n def findPeakGrid(self, mat):\n \"\"\"\n :type mat: List[List[int]]\n :rtype: List[int]\n \"\"\"\n def get_vec(mat, i):\n return mat[i] if len(mat) > len(mat[0]) else (mat[j][i] for j in range(len(mat)))\n\n def check(mat, x):\n return max(get_vec(mat, x)) > max(get_vec(mat, x+1))\n\n left, right = 0, (max(len(mat), len(mat[0]))-1)-1\n while left <= right:\n mid = left + (right-left)//2\n if check(mat, mid):\n right = mid-1\n else:\n left = mid+1\n mav_val = max(get_vec(mat, left))\n result = [left, next(i for i, x in enumerate(get_vec(mat, left)) if x == mav_val)]\n return result if len(mat) > len(mat[0]) else result[::-1]\n"}} diff --git a/cp/cp-11257.jsonl b/cp/cp-11257.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..08f4ceb8b893b4c9aebcc5e430b3ef4ee87a0a43 --- /dev/null +++ b/cp/cp-11257.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11257", "name": "LeetCode 1904: The Number Of Full Rounds You Have Played"} +{"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: The Number of Full Rounds You Have Played (Difficulty: Medium)\nTags: Math, String\n\nYou are participating in an online chess tournament. There is a chess round that starts every 15 minutes. The first round of the day starts at 00:00, and after every 15 minutes, a new round starts.\nYou are given two strings loginTime and logoutTime where:\nIf logoutTime is earlier than loginTime, this means you have played from loginTime to midnight and from midnight to logoutTime.\nReturn the number of full chess rounds you have played in the tournament.\nNote: All the given times follow the 24-hour clock. That means the first round of the day starts at 00:00 and the last round of the day starts at 23:45.\n\nExample 1:\nInput: loginTime = \"09:31\", logoutTime = \"10:14\"\nOutput: 1\nExplanation: You played one full round from 09:45 to 10:00.\nYou did not play the full round from 09:30 to 09:45 because you logged in at 09:31 after it began.\nYou did not play the full round from 10:00 to 10:15 because you logged out at 10:14 before it ended.\n\nExample 2:\nInput: loginTime = \"21:30\", logoutTime = \"03:00\"\nOutput: 22\nExplanation: You played 10 full rounds from 21:30 to 00:00 and 12 full rounds from 00:00 to 03:00.\n10 + 12 = 22.\n\nConstraints:\n- loginTime and logoutTime are in the format hh:mm.\n- 00 <= hh <= 23\n- 00 <= mm <= 59\n- loginTime and logoutTime are not equal."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nclass Solution(object):\n def numberOfRounds(self, startTime, finishTime):\n \"\"\"\n :type startTime: str\n :type finishTime: str\n :rtype: int\n \"\"\"\n h1, m1 = map(int, startTime.split(\":\"))\n h2, m2 = map(int, finishTime.split(\":\"))\n start = h1*60+m1\n finish = h2*60+m2\n if start > finish:\n finish += 1440\n return max(finish//15-(start+15-1)//15, 0)\n\n\n# Time: O(1)\n# Space: O(1)\nclass Solution2(object):\n def numberOfRounds(self, startTime, finishTime):\n \"\"\"\n :type startTime: str\n :type finishTime: str\n :rtype: int\n \"\"\"\n h1, m1 = map(int, startTime.split(\":\"))\n h2, m2 = map(int, finishTime.split(\":\"))\n if m1 > m2:\n h2 -= 1\n m2 += 60\n return max((h2-h1)%24*4 + m2//15 - (m1+15-1)//15, 0)\n"}} diff --git a/cp/cp-11258.jsonl b/cp/cp-11258.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f05c4ca69a460c584da75f079ee7cbe551f1dc8b --- /dev/null +++ b/cp/cp-11258.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11258", "name": "LeetCode 1905: Count Sub Islands"} +{"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: Count Sub Islands (Difficulty: Medium)\nTags: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix\n\nYou are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.\nAn island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.\nReturn the number of islands in grid2 that are considered sub-islands.\n\nExample 1:\nInput: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]\nOutput: 3\nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.\n\nExample 2:\nInput: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]\nOutput: 2 \nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.\n\nConstraints:\n- m == grid1.length == grid2.length\n- n == grid1[i].length == grid2[i].length\n- 1 <= m, n <= 500\n- grid1[i][j] and grid2[i][j] are either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def countSubIslands(self, grid1, grid2):\n \"\"\"\n :type grid1: List[List[int]]\n :type grid2: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n def dfs(grid1, grid2, i, j):\n if not (0 <= i < len(grid2) and\n 0 <= j < len(grid2[0]) and\n grid2[i][j] == 1):\n return 1\n grid2[i][j] = 0\n result = grid1[i][j]\n for di, dj in directions:\n result &= dfs(grid1, grid2, i+di, j+dj)\n return result\n \n return sum(dfs(grid1, grid2, i, j) for i in range(len(grid2)) for j in range(len(grid2[0])) if grid2[i][j])\n"}} diff --git a/cp/cp-11259.jsonl b/cp/cp-11259.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9ad26521783915245fd56e39aa3d5ffb977e9ade --- /dev/null +++ b/cp/cp-11259.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11259", "name": "LeetCode 1906: Minimum Absolute Difference Queries"} +{"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: Minimum Absolute Difference Queries (Difficulty: Medium)\nTags: Array, Hash Table\n\nThe minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1.\nYou are given an integer array nums and the array queries where queries[i] = [li, ri]. For each query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive).\nReturn an array ans where ans[i] is the answer to the ith query.\nA subarray is a contiguous sequence of elements in an array.\nThe value of |x| is defined as:\n\nExample 1:\nInput: nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]\nOutput: [2,1,4,1]\nExplanation: The queries are processed as follows:\n- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.\n- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.\n- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.\n- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.\n\nExample 2:\nInput: nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]\nOutput: [-1,1,1,3]\nExplanation: The queries are processed as follows:\n- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the\n elements are the same.\n- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1.\n- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1.\n- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.\n\nConstraints:\n- 2 <= nums.length <= 10^5\n- 1 <= nums[i] <= 100\n- 1 <= queries.length <= 2 * 10^4\n- 0 <= li < ri < nums.length"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(r * (n + q)), r is the max of nums\n# Space: O(r * n)\n\nclass Solution(object):\n def minDifference(self, nums, queries):\n \"\"\"\n :type nums: List[int]\n :type queries: List[List[int]]\n :rtype: List[int]\n \"\"\"\n INF = float(\"inf\")\n prefix = [[0]*(max(nums)+1)]\n for num in nums:\n prefix.append(prefix[-1][:])\n prefix[-1][num] += 1\n result = []\n for l, r in queries:\n min_diff, prev = INF, -1\n for num in range(len(prefix[0])):\n if not (prefix[l][num] < prefix[r+1][num]):\n continue\n if prev != -1:\n min_diff = min(min_diff, num-prev)\n prev = num\n result.append(min_diff if min_diff != INF else -1)\n return result\n\n\n# Time: O(r + n + q * r * logn), r is the max of nums\n# Space: O(r + n)\nimport bisect\n\n\nclass Solution2(object):\n def minDifference(self, nums, queries):\n \"\"\"\n :type nums: List[int]\n :type queries: List[List[int]]\n :rtype: List[int]\n \"\"\"\n INF = float(\"inf\")\n idxs = [[] for _ in range(max(nums)+1)]\n for i, num in enumerate(nums):\n idxs[num].append(i)\n result = []\n for l, r in queries:\n min_diff, prev = INF, -1\n for num in range(len(idxs)):\n i = bisect.bisect_left(idxs[num], l)\n if not (i < len(idxs[num]) and idxs[num][i] <= r):\n continue\n if prev != -1:\n min_diff = min(min_diff, num-prev)\n prev = num\n result.append(min_diff if min_diff != INF else -1)\n return result\n"}} diff --git a/cp/cp-11261.jsonl b/cp/cp-11261.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..180ec4043b3e7d0349f43d00902bb9bc5db2bd34 --- /dev/null +++ b/cp/cp-11261.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11261", "name": "LeetCode 1909: Remove One Element To Make The Array Strictly Increasing"} +{"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: Remove One Element to Make the Array Strictly Increasing (Difficulty: Easy)\nTags: Array\n\nGiven a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true.\nThe array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).\n\nExample 1:\nInput: nums = [1,2,10,5,7]\nOutput: true\nExplanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7].\n[1,2,5,7] is strictly increasing, so return true.\n\nExample 2:\nInput: nums = [2,3,1,2]\nOutput: false\nExplanation:\n[3,1,2] is the result of removing the element at index 0.\n[2,1,2] is the result of removing the element at index 1.\n[2,3,2] is the result of removing the element at index 2.\n[2,3,1] is the result of removing the element at index 3.\nNo resulting array is strictly increasing, so return false.\n\nExample 3:\nInput: nums = [1,1,1]\nOutput: false\nExplanation: The result of removing any element is [1,1].\n[1,1] is not strictly increasing, so return false.\n\nConstraints:\n- 2 <= nums.length <= 1000\n- 1 <= nums[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def canBeIncreasing(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n deleted = False\n for i in range(1, len(nums)):\n if nums[i] > nums[i-1]:\n continue\n if deleted:\n return False\n deleted = True\n if i >= 2 and nums[i-2] > nums[i]: # delete nums[i] or nums[i-1]\n nums[i] = nums[i-1]\n return True\n"}} diff --git a/cp/cp-11262.jsonl b/cp/cp-11262.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4ea365297d9202edf5ebc6801d2fed4ea7905f0e --- /dev/null +++ b/cp/cp-11262.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11262", "name": "LeetCode 1910: Remove All Occurrences Of A Substring"} +{"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: Remove All Occurrences of a Substring (Difficulty: Medium)\nTags: String, Stack, Simulation\n\nGiven two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:\nReturn s after removing all occurrences of part.\nA substring is a contiguous sequence of characters in a string.\n\nExample 1:\nInput: s = \"daabcbaabcbc\", part = \"abc\"\nOutput: \"dab\"\nExplanation: The following operations are done:\n- s = \"daabcbaabcbc\", remove \"abc\" starting at index 2, so s = \"dabaabcbc\".\n- s = \"dabaabcbc\", remove \"abc\" starting at index 4, so s = \"dababc\".\n- s = \"dababc\", remove \"abc\" starting at index 3, so s = \"dab\".\nNow s has no occurrences of \"abc\".\n\nExample 2:\nInput: s = \"axxxxyyyyb\", part = \"xy\"\nOutput: \"ab\"\nExplanation: The following operations are done:\n- s = \"axxxxyyyyb\", remove \"xy\" starting at index 4 so s = \"axxxyyyb\".\n- s = \"axxxyyyb\", remove \"xy\" starting at index 3 so s = \"axxyyb\".\n- s = \"axxyyb\", remove \"xy\" starting at index 2 so s = \"axyb\".\n- s = \"axyb\", remove \"xy\" starting at index 1 so s = \"ab\".\nNow s has no occurrences of \"xy\".\n\nConstraints:\n- 1 <= s.length <= 1000\n- 1 <= part.length <= 1000\n- s​​​​​​ and part consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + m)\n# Space: O(n + m)\n\n# kmp solution\nclass Solution(object):\n def removeOccurrences(self, s, part):\n \"\"\"\n :type s: str\n :type part: str\n :rtype: str\n \"\"\"\n def getPrefix(pattern):\n prefix = [-1]*len(pattern)\n j = -1\n for i in range(1, len(pattern)):\n while j != -1 and pattern[j+1] != pattern[i]:\n j = prefix[j]\n if pattern[j+1] == pattern[i]:\n j += 1\n prefix[i] = j\n return prefix\n \n prefix = getPrefix(part)\n result, lookup = [], []\n i = -1\n for c in s:\n while i != -1 and part[i+1] != c:\n i = prefix[i]\n if part[i+1] == c:\n i += 1\n result.append(c)\n lookup.append(i)\n if i == len(part)-1:\n result[len(result)-len(part):] = []\n lookup[len(lookup)-len(part):] = []\n i = lookup[-1] if lookup else -1\n return \"\".join(result)\n"}} diff --git a/cp/cp-11264.jsonl b/cp/cp-11264.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eb337ed86116f02f5736895e739503dd84d94d38 --- /dev/null +++ b/cp/cp-11264.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11264", "name": "LeetCode 1912: Design Movie Rental 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: Design Movie Rental System (Difficulty: Hard)\nTags: Array, Hash Table, Design, Heap (Priority Queue), Ordered Set\n\nYou have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.\nEach movie is given as a 2D integer array entries where entries[i] = [shopi, moviei, pricei] indicates that there is a copy of movie moviei at shop shopi with a rental price of pricei. Each shop carries at most one copy of a movie moviei.\nThe system should support the following functions:\nImplement the MovieRentingSystem class:\nNote: The test cases will be generated such that rent will only be called if the shop has an unrented copy of the movie, and drop will only be called if the shop had previously rented out the movie.\n\nExample 1:\nInput\n[\"MovieRentingSystem\", \"search\", \"rent\", \"rent\", \"report\", \"drop\", \"search\"]\n[[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]]\nOutput\n[null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]]\n\nExplanation\nMovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]);\nmovieRentingSystem.search(1); // return [1, 0, 2], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.\nmovieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3].\nmovieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1].\nmovieRentingSystem.report(); // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.\nmovieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2].\nmovieRentingSystem.search(2); // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.\n\nConstraints:\n- 1 <= n <= 3 * 10^5\n- 1 <= entries.length <= 10^5\n- 0 <= shopi < n\n- 1 <= moviei, pricei <= 10^4\n- Each shop carries at most one copy of a movie moviei.\n- At most 105 calls in total will be made to search, rent, drop and report."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(nlogn)\n# search: O(logn)\n# rent: O(logn)\n# drop: O(logn)\n# report: O(logn)\n# Space: O(n)\n\nimport collections\nfrom sortedcontainers import SortedList\n\n\nclass MovieRentingSystem(object):\n\n def __init__(self, n, entries):\n \"\"\"\n :type n: int\n :type entries: List[List[int]]\n \"\"\"\n self.__movie_to_ordered_price_shop = collections.defaultdict(SortedList) \n self.__shop_movie_to_price = {}\n self.__rented_ordered_price_shop_movie = SortedList()\n for s, m, p in entries:\n self.__movie_to_ordered_price_shop[m].add((p, s))\n self.__shop_movie_to_price[s, m] = p\n\n def search(self, movie):\n \"\"\"\n :type movie: int\n :rtype: List[int]\n \"\"\"\n return [s for _, s in self.__movie_to_ordered_price_shop[movie][:5]]\n\n def rent(self, shop, movie):\n \"\"\"\n :type shop: int\n :type movie: int\n :rtype: None\n \"\"\"\n price = self.__shop_movie_to_price[shop, movie]\n self.__movie_to_ordered_price_shop[movie].remove((price, shop))\n self.__rented_ordered_price_shop_movie.add((price, shop, movie))\n\n def drop(self, shop, movie):\n \"\"\"\n :type shop: int\n :type movie: int\n :rtype: None\n \"\"\"\n price = self.__shop_movie_to_price[shop, movie]\n self.__movie_to_ordered_price_shop[movie].add((price, shop))\n self.__rented_ordered_price_shop_movie.remove((price, shop, movie))\n\n def report(self):\n \"\"\"\n :rtype: List[List[int]]\n \"\"\"\n return [[s, m] for _, s, m in self.__rented_ordered_price_shop_movie[:5]]\n"}} diff --git a/cp/cp-11265.jsonl b/cp/cp-11265.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a9836664a2b3899e3c385e6f1eb97326c1d867d5 --- /dev/null +++ b/cp/cp-11265.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11265", "name": "LeetCode 1913: Maximum Product Difference Between Two 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: Maximum Product Difference Between Two Pairs (Difficulty: Easy)\nTags: Array, Sorting\n\nThe product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).\nGiven an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.\nReturn the maximum such product difference.\n\nExample 1:\nInput: nums = [5,6,2,7,4]\r\nOutput: 34\r\nExplanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).\r\nThe product difference is (6 * 7) - (2 * 4) = 34.\n\nExample 2:\nInput: nums = [4,2,5,9,7,4,8]\r\nOutput: 64\r\nExplanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).\r\nThe product difference is (9 * 8) - (2 * 4) = 64.\n\nConstraints:\n- 4 <= 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 maxProductDifference(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n largest, smallest = [0]*2, [float(\"inf\")]*2\n for x in nums:\n if x >= largest[0]:\n largest[:] = [x, largest[0]]\n elif x > largest[1]:\n largest[1] =x\n if x <= smallest[0]:\n smallest[:] = [x, smallest[0]]\n elif x < smallest[1]:\n smallest[1] = x\n return largest[0]*largest[1] - smallest[0]*smallest[1]\n"}} diff --git a/cp/cp-11266.jsonl b/cp/cp-11266.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4809bf1b73f34290353613a5263a39e640ffd7e7 --- /dev/null +++ b/cp/cp-11266.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11266", "name": "LeetCode 1914: Cyclically Rotating A Grid"} +{"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: Cyclically Rotating a Grid (Difficulty: Medium)\nTags: Array, Matrix, Simulation\n\nYou are given an m x n integer matrix grid​​​, where m and n are both even integers, and an integer k.\nThe matrix is composed of several layers, which is shown in the below image, where each color is its own layer:\nA cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below:\nReturn the matrix after applying k cyclic rotations to it.\n\nExample 1:\nInput: grid = [[40,10],[30,20]], k = 1\r\nOutput: [[10,20],[40,30]]\r\nExplanation: The figures above represent the grid at every state.\n\nExample 2:\nInput: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2\r\nOutput: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]\r\nExplanation: The figures above represent the grid at every state.\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 2 <= m, n <= 50\n- Both m and n are even integers.\n- 1 <= grid[i][j] <= 5000\n- 1 <= k <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nimport fractions\n\n\n# inplace rotation\nclass Solution(object):\n def rotateGrid(self, grid, k):\n \"\"\"\n :type grid: List[List[int]]\n :type k: int\n :rtype: List[List[int]]\n \"\"\"\n def get_index(m, n, l):\n if l < m-1:\n return l, 0\n if l < (m-1)+(n-1):\n return m-1, l-(m-1)\n if l < (m-1)+(n-1)+(m-1):\n return (m-1)-(l-((m-1)+(n-1))), n-1\n return 0, (n-1)-(l-((m-1)+(n-1)+(m-1)))\n\n m, n = len(grid), len(grid[0])\n for i in range(min(m, n)//2):\n total = 2*((m-1)+(n-1))\n nk = k%total\n num_cycles = fractions.gcd(total, nk)\n cycle_len = total//num_cycles\n for offset in range(num_cycles):\n r, c = get_index(m, n, offset)\n for j in range(1, cycle_len):\n nr, nc = get_index(m, n, (offset+j*nk)%total)\n grid[i+nr][i+nc], grid[i+r][i+c] = grid[i+r][i+c], grid[i+nr][i+nc]\n m, n = m-2, n-2\n return grid\n\n\n# Time: O(m * n)\n# Space: O(1)\n# inplace rotation\nclass Solution2(object):\n def rotateGrid(self, grid, k):\n \"\"\"\n :type grid: List[List[int]]\n :type k: int\n :rtype: List[List[int]]\n \"\"\"\n def get_index(m, n, l):\n if l < m-1:\n return l, 0\n if l < (m-1)+(n-1):\n return m-1, l-(m-1)\n if l < (m-1)+(n-1)+(m-1):\n return (m-1)-(l-((m-1)+(n-1))), n-1\n return 0, (n-1)-(l-((m-1)+(n-1)+(m-1)))\n\n def reverse(grid, m, n, i, left, right):\n while left < right:\n lr, lc = get_index(m, n, left)\n rr, rc = get_index(m, n, right)\n grid[i+lr][i+lc], grid[i+rr][i+rc] = grid[i+rr][i+rc], grid[i+lr][i+lc]\n left += 1\n right -= 1\n\n m, n = len(grid), len(grid[0])\n for i in range(min(m, n)//2):\n total = 2*((m-1)+(n-1))\n nk = k%total\n reverse(grid, m, n, i, 0, total-1)\n reverse(grid, m, n, i, 0, nk-1)\n reverse(grid, m, n, i, nk, total-1)\n m, n = m-2, n-2\n return grid\n"}} diff --git a/cp/cp-11267.jsonl b/cp/cp-11267.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bc7d0d02911e18c48282df090d01acd3b6a14ef0 --- /dev/null +++ b/cp/cp-11267.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11267", "name": "LeetCode 1915: Number Of Wonderful 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: Number of Wonderful Substrings (Difficulty: Medium)\nTags: Hash Table, String, Bit Manipulation, Prefix Sum\n\nA wonderful string is a string where at most one letter appears an odd number of times.\nGiven a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately.\nA substring is a contiguous sequence of characters in a string.\n\nExample 1:\nInput: word = \"aba\"\r\nOutput: 4\r\nExplanation: The four wonderful substrings are underlined below:\r\n- \"aba\" -> \"a\"\r\n- \"aba\" -> \"b\"\r\n- \"aba\" -> \"a\"\r\n- \"aba\" -> \"aba\"\n\nExample 2:\nInput: word = \"aabb\"\r\nOutput: 9\r\nExplanation: The nine wonderful substrings are underlined below:\r\n- \"aabb\" -> \"a\"\r\n- \"aabb\" -> \"aa\"\r\n- \"aabb\" -> \"aab\"\r\n- \"aabb\" -> \"aabb\"\r\n- \"aabb\" -> \"a\"\r\n- \"aabb\" -> \"abb\"\r\n- \"aabb\" -> \"b\"\r\n- \"aabb\" -> \"bb\"\r\n- \"aabb\" -> \"b\"\n\nExample 3:\nInput: word = \"he\"\r\nOutput: 2\r\nExplanation: The two wonderful substrings are underlined below:\r\n- \"he\" -> \"h\"\r\n- \"he\" -> \"e\"\n\nConstraints:\n- 1 <= word.length <= 10^5\n- word consists of lowercase English letters from 'a' to 'j'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(2^10)\n\nclass Solution(object):\n def wonderfulSubstrings(self, word):\n \"\"\"\n :type word: str\n :rtype: int\n \"\"\"\n ALPHABET_SIZE = 10\n count = [0]*(2**ALPHABET_SIZE)\n count[0] = 1\n result = curr = 0\n for c in word:\n curr ^= 1<<(ord(c)-ord('a'))\n result += count[curr]\n result += sum(count[curr^(1<= 0 and curr != i:\n nums[prev], nums[curr] = ~nums[curr], ~nums[prev] if prev == i else nums[prev]\n prev, curr = curr, ~nums[prev]\n for i in range(len(nums)):\n if nums[i] < 0:\n nums[i] = ~nums[i]\n return nums\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def buildArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n return [nums[x] for x in nums]\n"}} diff --git a/cp/cp-11271.jsonl b/cp/cp-11271.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..514bc49871435fe6078b73b8554de17ca8400da9 --- /dev/null +++ b/cp/cp-11271.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11271", "name": "LeetCode 1921: Eliminate Maximum Number Of Monsters"} +{"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: Eliminate Maximum Number of Monsters (Difficulty: Medium)\nTags: Array, Greedy, Sorting\n\nYou are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city.\nThe monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute.\nYou have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge. The weapon is fully charged at the very start.\nYou lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon.\nReturn the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.\n\nExample 1:\nInput: dist = [1,3,4], speed = [1,1,1]\nOutput: 3\nExplanation:\nIn the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.\nAfter a minute, the distances of the monsters are [X,X,2]. You eliminate the third monster.\nAll 3 monsters can be eliminated.\n\nExample 2:\nInput: dist = [1,1,2,3], speed = [1,1,1,1]\nOutput: 1\nExplanation:\nIn the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,1,2], so you lose.\nYou can only eliminate 1 monster.\n\nExample 3:\nInput: dist = [3,2,4], speed = [5,3,2]\nOutput: 1\nExplanation:\nIn the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,2], so you lose.\nYou can only eliminate 1 monster.\n\nConstraints:\n- n == dist.length == speed.length\n- 1 <= n <= 10^5\n- 1 <= dist[i], speed[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def eliminateMaximum(self, dist, speed):\n \"\"\"\n :type dist: List[int]\n :type speed: List[int]\n :rtype: int\n \"\"\"\n for i in range(len(dist)):\n dist[i] = (dist[i]-1)//speed[i]\n dist.sort()\n result = 0\n for i in range(len(dist)):\n if result > dist[i]:\n break\n result += 1\n return result\n"}} diff --git a/cp/cp-11272.jsonl b/cp/cp-11272.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..87432e3985ecf77ffe9a3ac1226a822a8d5bab8a --- /dev/null +++ b/cp/cp-11272.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11272", "name": "LeetCode 1922: Count Good 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: Count Good Numbers (Difficulty: Medium)\nTags: Math, Recursion\n\nA digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7).\nGiven an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7.\nA digit string is a string consisting of digits 0 through 9 that may contain leading zeros.\n\nExample 1:\nInput: n = 1\nOutput: 5\nExplanation: The good numbers of length 1 are \"0\", \"2\", \"4\", \"6\", \"8\".\n\nExample 2:\nInput: n = 4\nOutput: 400\n\nExample 3:\nInput: n = 50\nOutput: 564908303\n\nConstraints:\n- 1 <= n <= 10^15"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(logn)\n# Space: O(1)\n\nclass Solution(object):\n def countGoodNumbers(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n def powmod(a, b, mod):\n a %= mod\n result = 1\n while b:\n if b&1:\n result = (result*a)%mod\n a = (a*a)%mod\n b >>= 1\n return result\n\n MOD = 10**9 + 7\n return powmod(5, (n+1)//2%(MOD-1), MOD)*powmod(4, n//2%(MOD-1), MOD) % MOD\n\n\n# Time: O(logn)\n# Space: O(1)\nclass Solution2(object):\n def countGoodNumbers(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n MOD = 10**9 + 7\n return pow(5, (n+1)//2%(MOD-1), MOD)*pow(4, n//2%(MOD-1), MOD) % MOD\n"}} diff --git a/cp/cp-11273.jsonl b/cp/cp-11273.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2dba599818a5a921db423f629bcb03e4f8b74794 --- /dev/null +++ b/cp/cp-11273.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11273", "name": "LeetCode 1923: Longest Common Subpath"} +{"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 Common Subpath (Difficulty: Hard)\nTags: Array, Binary Search, Rolling Hash, Suffix Array, Hash Function\n\nThere is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities.\nThere are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively.\nGiven an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the ith friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all.\nA subpath of a path is a contiguous sequence of cities within that path.\n\nExample 1:\nInput: n = 5, paths = [[0,1,2,3,4],\n [2,3,4],\n [4,0,1,2,3]]\nOutput: 2\nExplanation: The longest common subpath is [2,3].\n\nExample 2:\nInput: n = 3, paths = [[0],[1],[2]]\nOutput: 0\nExplanation: There is no common subpath shared by the three paths.\n\nExample 3:\nInput: n = 5, paths = [[0,1,2,3,4],\n [4,3,2,1,0]]\nOutput: 1\nExplanation: The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1.\n\nConstraints:\n- 1 <= n <= 10^5\n- m == paths.length\n- 2 <= m <= 10^5\n- sum(paths[i].length) <= 10^5\n- 0 <= paths[i][j] < n\n- The same city is not listed multiple times consecutively in paths[i]."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * nlogn)\n# Space: O(n)\n\nclass Solution(object):\n def longestCommonSubpath(self, n, paths):\n \"\"\"\n :type n: int\n :type paths: List[List[int]]\n :rtype: int\n \"\"\"\n def RabinKarp(arr, x): # double hashing\n hashes = tuple([reduce(lambda h,x: (h*p+x)%MOD, (arr[i] for i in range(x)), 0) for p in P])\n powers = [pow(p, x, MOD) for p in P]\n lookup = {hashes}\n for i in range(x, len(arr)):\n hashes = tuple([(hashes[j]*P[j] - arr[i-x]*powers[j] + arr[i])%MOD for j in range(len(P))]) # in smaller datasets, tuple from list is much faster than tuple from generator, see https://stackoverflow.com/questions/16940293/why-is-there-no-tuple-comprehension-in-python\n lookup.add(hashes)\n return lookup\n \n def check(paths, x):\n intersect = RabinKarp(paths[0], x)\n for i in range(1, len(paths)):\n intersect = set.intersection(intersect, RabinKarp(paths[i], x))\n if not intersect:\n return False\n return True\n\n MOD, P = 10**9+7, (113, 109) # MOD could be the min prime of 7-digit number (10**6+3), P could be (2, 3)\n left, right = 1, min(len(p) for p in paths)\n while left <= right:\n mid = left + (right-left)//2\n if not check(paths, mid):\n right = mid-1\n else:\n left = mid+1\n return right\n\n\n# Time: O(m * nlogn)\n# Space: O(n)\nclass Solution2(object):\n def longestCommonSubpath(self, n, paths):\n \"\"\"\n :type n: int\n :type paths: List[List[int]]\n :rtype: int\n \"\"\"\n def RabinKarp(arr, x):\n h = reduce(lambda h,x: (h*P+x)%MOD, (arr[i] for i in range(x)), 0)\n power = pow(P, x, MOD)\n lookup = {h}\n for i in range(x, len(arr)):\n h = (h*P - arr[i-x]*power + arr[i])%MOD\n lookup.add(h)\n return lookup\n \n def check(paths, x):\n intersect = RabinKarp(paths[0], x)\n for i in range(1, len(paths)):\n intersect = set.intersection(intersect, RabinKarp(paths[i], x))\n if not intersect:\n return False\n return True\n\n MOD, P = 10**11+19, max(x for p in paths for x in p)+1 # MOD is the min prime of 12-digit number\n left, right = 1, min(len(p) for p in paths)\n while left <= right:\n mid = left + (right-left)//2\n if not check(paths, mid):\n right = mid-1\n else:\n left = mid+1\n return right\n"}} diff --git a/cp/cp-11275.jsonl b/cp/cp-11275.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3534c5048456fed39fde75be5d4e4704616dfa5f --- /dev/null +++ b/cp/cp-11275.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11275", "name": "LeetCode 1925: Count Square Sum Triples"} +{"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: Count Square Sum Triples (Difficulty: Easy)\nTags: Math, Enumeration\n\nA square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.\nGiven an integer n, return the number of square triples such that 1 <= a, b, c <= n.\n\nExample 1:\nInput: n = 5\nOutput: 2\nExplanation: The square triples are (3,4,5) and (4,3,5).\n\nExample 2:\nInput: n = 10\nOutput: 4\nExplanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).\n\nConstraints:\n- 1 <= n <= 250"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n def countTriples(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n lookup = set()\n for i in range(1, n+1):\n lookup.add(i**2)\n result = 0\n for i in range(1, n+1):\n for j in range(1, n+1):\n result += int(i**2+j**2 in lookup)\n return result\n"}} diff --git a/cp/cp-11276.jsonl b/cp/cp-11276.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e44e9800d46bc927804cfacdaccbcd6bf0f7888d --- /dev/null +++ b/cp/cp-11276.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11276", "name": "LeetCode 1926: Nearest Exit From Entrance In Maze"} +{"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: Nearest Exit from Entrance in Maze (Difficulty: Medium)\nTags: Array, Breadth-First Search, Matrix\n\nYou are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.\nIn one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.\nReturn the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.\n\nExample 1:\nInput: maze = [[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]], entrance = [1,2]\nOutput: 1\nExplanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away.\n\nExample 2:\nInput: maze = [[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]], entrance = [1,0]\nOutput: 2\nExplanation: There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away.\n\nExample 3:\nInput: maze = [[\".\",\"+\"]], entrance = [0,0]\nOutput: -1\nExplanation: There are no exits in this maze.\n\nConstraints:\n- maze.length == m\n- maze[i].length == n\n- 1 <= m, n <= 100\n- maze[i][j] is either '.' or '+'.\n- entrance.length == 2\n- 0 <= entrancerow < m\n- 0 <= entrancecol < n\n- entrance will always be an empty cell."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(m + n)\n\n# bi-bfs solution\nclass Solution(object):\n def nearestExit(self, maze, entrance):\n \"\"\"\n :type maze: List[List[str]]\n :type entrance: List[int]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n visited = ' '\n entrance = tuple(entrance)\n left = set([entrance])\n right = set([(r, 0) for r in range(len(maze)-1) if maze[r][0] == '.' and (r, 0) != entrance] +\n [(len(maze)-1, c) for c in range(len(maze[0])-1) if maze[len(maze)-1][c] == '.' and (len(maze)-1, c) != entrance] +\n [(r, len(maze[0])-1) for r in reversed(range(1, len(maze))) if maze[r][len(maze[0])-1] == '.' and (r, len(maze[0])-1) != entrance] +\n [(0, c) for c in reversed(range(1, len(maze[0]))) if maze[0][c] == '.' and (0, c) != entrance])\n steps = 0\n while left:\n for (r, c) in left:\n maze[r][c] = visited\n new_left = set()\n for (r, c) in left:\n if (r, c) in right: \n return steps\n for dr, dc in directions:\n nr, nc = r+dr, c+dc\n if not (0 <= nr < len(maze) and\n 0 <= nc < len(maze[0]) and\n maze[nr][nc] == '.'):\n continue\n new_left.add((nr, nc))\n left = new_left\n steps += 1\n if len(left) > len(right): \n left, right = right, left\n return -1\n\n\n# Time: O(m * n)\n# Space: O(m + n)\n# bfs solution\nclass Solution2(object):\n def nearestExit(self, maze, entrance):\n \"\"\"\n :type maze: List[List[str]]\n :type entrance: List[int]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n visited = ' '\n entrance = tuple(entrance)\n maze[entrance[0]][entrance[1]] = visited\n q = [(entrance, 0)]\n while q:\n new_q = []\n for (r, c), step in q:\n if (r, c) != entrance and \\\n (r in (0, len(maze)-1) or c in (0, len(maze[0])-1)):\n return step\n for dr, dc in directions:\n nr, nc = r+dr, c+dc\n if not (0 <= nr < len(maze) and\n 0 <= nc < len(maze[0]) and\n maze[nr][nc] == '.'):\n continue\n maze[nr][nc] = visited\n q.append(((nr, nc), step+1))\n q = new_q\n return -1\n"}} diff --git a/cp/cp-11277.jsonl b/cp/cp-11277.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d3165f4f8a59719869ecbec9bacfb849fda1c002 --- /dev/null +++ b/cp/cp-11277.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11277", "name": "LeetCode 1927: Sum Game"} +{"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 Game (Difficulty: Medium)\nTags: Math, String, Greedy, Game Theory\n\nAlice and Bob take turns playing a game, with Alice starting first.\nYou are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num:\nThe game ends when there are no more '?' characters in num.\nFor Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal.\nAssuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.\n\nExample 1:\nInput: num = \"5023\"\nOutput: false\nExplanation: There are no moves to be made.\nThe sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.\n\nExample 2:\nInput: num = \"25??\"\nOutput: true\nExplanation: Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.\n\nExample 3:\nInput: num = \"?3295???\"\nOutput: false\nExplanation: It can be proven that Bob will always win. One possible outcome is:\n- Alice replaces the first '?' with '9'. num = \"93295???\".\n- Bob replaces one of the '?' in the right half with '9'. num = \"932959??\".\n- Alice replaces one of the '?' in the right half with '2'. num = \"9329592?\".\n- Bob replaces the last '?' in the right half with '7'. num = \"93295927\".\nBob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.\n\nConstraints:\n- 2 <= num.length <= 10^5\n- num.length is even.\n- num consists of only digits and '?'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def sumGame(self, num):\n \"\"\"\n :type num: str\n :rtype: bool\n \"\"\"\n # (1) if both halfs have '?',\n # alice will optimally choose 9 or 0 from one half to maximize or minimize the diff of both half sums,\n # and bob will optimally choose the same number from the other half to minimize or maximize the diff of both half sums.\n # in the end, it turns that only one half has '?' and the diff of both half sums is still the same as original\n # (2) if smaller half has no '?', then alice wins\n # (3) if smaller half has '?'\n # (3.1) if cnt of '?' is odd, alice can choose the last number to make the diff of both half sums != 0, then alice wins\n # (3.2) if cnt of '?' is even\n # (3.2.1) if larger-smaller = cnt/2 * 9, bob can always make a pair of sum 9 no matter what alice chooses, then bob wins\n # (3.2.2) if larger-smaller > cnt/2 * 9, alice can always choose 0 no matter what bob chooses, then alice wins\n # (3.2.3) if larger-smaller < cnt/2 * 9, alice can always choose 9 no matter what bob chooses, then alice wins\n cnt = total = 0\n for i in range(len(num)):\n if num[i] == '?':\n cnt += (-1 if i < len(num)//2 else 1)\n else:\n total += (int(num[i]) if i < len(num)//2 else -int(num[i]))\n return True if cnt%2 else total != cnt//2*9\n"}} diff --git a/cp/cp-11278.jsonl b/cp/cp-11278.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f45b4f995377948044d00e6eba18ea4b75d4b2ad --- /dev/null +++ b/cp/cp-11278.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11278", "name": "LeetCode 1928: Minimum Cost To Reach Destination In Time"} +{"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: Minimum Cost to Reach Destination in Time (Difficulty: Hard)\nTags: Array, Dynamic Programming, Graph\n\nThere is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself.\nEach time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j.\nIn the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities).\nGiven maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes.\n\nExample 1:\nInput: maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput: 11\nExplanation: The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.\n\nExample 2:\nInput: maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput: 48\nExplanation: The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.\nYou cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.\n\nExample 3:\nInput: maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput: -1\nExplanation: There is no way to reach city 5 from city 0 within 25 minutes.\n\nConstraints:\n- 1 <= maxTime <= 1000\n- n == passingFees.length\n- 2 <= n <= 1000\n- n - 1 <= edges.length <= 1000\n- 0 <= xi, yi <= n - 1\n- 1 <= timei <= 1000\n- 1 <= passingFees[j] <= 1000\n- The graph may contain multiple edges between two nodes.\n- The graph does not contain self loops."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|),\n# if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|)\n# Space: O(|E| + |V|) = O(|E|)\n\nimport collections\nimport heapq\n\n\n# Dijkstra's algorithm\nclass Solution(object):\n def minCost(self, maxTime, edges, passingFees):\n \"\"\"\n :type maxTime: int\n :type edges: List[List[int]]\n :type passingFees: List[int]\n :rtype: int\n \"\"\" \n adj = [[] for i in range(len(passingFees))]\n for u, v, w in edges:\n adj[u].append((v, w))\n adj[v].append((u, w))\n best = collections.defaultdict(lambda:float(\"inf\"))\n best[0] = 0\n min_heap = [(passingFees[0], 0, 0)]\n while min_heap:\n result, u, w = heapq.heappop(min_heap)\n if w > maxTime: # state with best[u] < w can't be filtered, which may have less cost\n continue\n if u == len(passingFees)-1:\n return result\n for v, nw in adj[u]:\n if w+nw < best[v]: # from less cost to more cost, only need to check state with less time\n best[v] = w+nw\n heapq.heappush(min_heap, (result+passingFees[v], v, w+nw))\n return -1\n"}} diff --git a/cp/cp-11279.jsonl b/cp/cp-11279.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8c405ad0ae1b4bd345b2643659880a19cbee003b --- /dev/null +++ b/cp/cp-11279.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11279", "name": "LeetCode 1929: Concatenation Of 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: Concatenation of Array (Difficulty: Easy)\nTags: Array, Simulation\n\nGiven an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).\nSpecifically, ans is the concatenation of two nums arrays.\nReturn the array ans.\n\nExample 1:\nInput: nums = [1,2,1]\nOutput: [1,2,1,1,2,1]\nExplanation: The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]\n- ans = [1,2,1,1,2,1]\n\nExample 2:\nInput: nums = [1,3,2,1]\nOutput: [1,3,2,1,1,3,2,1]\nExplanation: The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]\n- ans = [1,3,2,1,1,3,2,1]\n\nConstraints:\n- n == nums.length\n- 1 <= n <= 1000\n- 1 <= nums[i] <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def getConcatenation(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n nums.extend(nums)\n return nums\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def getConcatenation(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n return nums+nums\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution3(object):\n def getConcatenation(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n return nums*2\n"}} diff --git a/cp/cp-11280.jsonl b/cp/cp-11280.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fe3c93765be977b0b7a20130c28af2eb721fe99d --- /dev/null +++ b/cp/cp-11280.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11280", "name": "LeetCode 1930: Unique Length 3 Palindromic 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: Unique Length-3 Palindromic Subsequences (Difficulty: Medium)\nTags: Hash Table, String, Bit Manipulation, Prefix Sum\n\nGiven a string s, return the number of unique palindromes of length three that are a subsequence of s.\nNote that even if there are multiple ways to obtain the same subsequence, it is still only counted once.\nA palindrome is a string that reads the same forwards and backwards.\nA subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.\n\nExample 1:\nInput: s = \"aabca\"\nOutput: 3\nExplanation: The 3 palindromic subsequences of length 3 are:\n- \"aba\" (subsequence of \"aabca\")\n- \"aaa\" (subsequence of \"aabca\")\n- \"aca\" (subsequence of \"aabca\")\n\nExample 2:\nInput: s = \"adc\"\nOutput: 0\nExplanation: There are no palindromic subsequences of length 3 in \"adc\".\n\nExample 3:\nInput: s = \"bbcbaba\"\nOutput: 4\nExplanation: The 4 palindromic subsequences of length 3 are:\n- \"bbb\" (subsequence of \"bbcbaba\")\n- \"bcb\" (subsequence of \"bbcbaba\")\n- \"bab\" (subsequence of \"bbcbaba\")\n- \"aba\" (subsequence of \"bbcbaba\")\n\nConstraints:\n- 3 <= s.length <= 10^5\n- s consists of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def countPalindromicSubsequence(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n first, last = [len(s)]*26, [-1]*26\n for i, c in enumerate(s):\n first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)\n last[ord(c)-ord('a')] = max(last[ord(c)-ord('a')], i)\n return sum(len(set(s[i] for i in range(first[c]+1, last[c]))) for c in range(26))\n"}} diff --git a/cp/cp-11281.jsonl b/cp/cp-11281.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4e08d688c7c6b9c7e7a47893d4e11b721fcfb3ae --- /dev/null +++ b/cp/cp-11281.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11281", "name": "LeetCode 1931: Painting A Grid With Three Different Colors"} +{"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: Painting a Grid With Three Different Colors (Difficulty: Hard)\nTags: Dynamic Programming\n\nYou are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.\nReturn the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7.\n\nExample 1:\nInput: m = 1, n = 1\nOutput: 3\nExplanation: The three possible colorings are shown in the image above.\n\nExample 2:\nInput: m = 1, n = 2\nOutput: 6\nExplanation: The six possible colorings are shown in the image above.\n\nExample 3:\nInput: m = 5, n = 5\nOutput: 580986\n\nConstraints:\n- 1 <= m <= 5\n- 1 <= n <= 1000"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * 2^m + 3^m + 2^(3 * m) * logn) = O(2^(3 * m) * logn)\n# Space: O(2^(2 * m))\n\nimport collections\nimport itertools\n\n\n# better complexity for small m, super large n\n# matrix exponentiation solution\nclass Solution(object):\n def colorTheGrid(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n def backtracking(mask1, mask2, basis, result): # Time: O(2^m), Space: O(2^m)\n if not basis:\n result.append(mask2)\n return\n for i in range(3):\n if (mask1 == -1 or mask1//basis%3 != i) and (mask2 == -1 or mask2//(basis*3)%3 != i):\n backtracking(mask1, mask2+i*basis if mask2 != -1 else i*basis, basis//3, result)\n\n def matrix_mult(A, B):\n ZB = zip(*B)\n return [[sum(a*b % MOD for a, b in itertools.izip(row, col)) % MOD for col in ZB] for row in A]\n \n def matrix_expo(A, K):\n result = [[int(i == j) for j in range(len(A))] for i in range(len(A))]\n while K:\n if K % 2:\n result = matrix_mult(result, A)\n A = matrix_mult(A, A)\n K /= 2\n return result\n\n def normalize(basis, mask):\n norm = {}\n result = 0\n while basis:\n x = mask//basis%3\n if x not in norm:\n norm[x] = len(norm)\n result += norm[x]*basis\n basis //= 3\n return result\n\n if m > n:\n m, n = n, m\n basis = 3**(m-1)\n masks = []\n backtracking(-1, -1, basis, masks) # Time: O(2^m), Space: O(2^m)\n assert(len(masks) == 3 * 2**(m-1))\n lookup = {mask:normalize(basis, mask) for mask in masks} # Time: O(m * 2^m)\n normalized_mask_cnt = collections.Counter(lookup[mask] for mask in masks)\n assert(len(normalized_mask_cnt) == 3*2**(m-1) // 3 // (2 if m >= 2 else 1)) # divided by 3 * 2 is since the first two colors are normalized to speed up performance\n adj = collections.defaultdict(list)\n for mask in normalized_mask_cnt.iterkeys(): # O(3^m) leaves which are all in depth m => Time: O(3^m), Space: O(3^m)\n backtracking(mask, -1, basis, adj[mask])\n normalized_adj = collections.defaultdict(lambda:collections.defaultdict(int))\n for mask1, masks2 in adj.iteritems():\n for mask2 in masks2:\n normalized_adj[mask1][lookup[mask2]] = (normalized_adj[mask1][lookup[mask2]]+1)%MOD\n # divided by 3 * 2 is since the first two colors in upper row are normalized to speed up performance,\n # since first two colors in lower row which has at most 3 choices could be also normalized, lower bound is upper bound divided by at most 3\n assert(2*3**m // 3 // 2 // 3 <= sum(len(v) for v in normalized_adj.itervalues()) <= 2*3**m // 3 // 2)\n return reduce(lambda x,y: (x+y)%MOD,\n matrix_mult([normalized_mask_cnt.values()],\n matrix_expo([[normalized_adj[mask1][mask2]\n for mask2 in normalized_mask_cnt.iterkeys()] \n for mask1 in normalized_mask_cnt.iterkeys()], n-1))[0],\n 0) # Time: O((2^m)^3 * logn), Space: O((2^m)^2)\n\n\n# Time: O(n * 3^m)\n# Space: O(3^m)\nimport collections\n\n\n# better complexity for small m, large n\nclass Solution2(object):\n def colorTheGrid(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n def find_masks(m, basis): # Time: 3 + 3*2 + 3*2*2 + ... + 3*2^(m-1) = 3 * (2^m - 1) = O(2^m), Space: O(2^m)\n masks = [0]\n for c in range(m):\n new_masks = []\n for mask in masks:\n choices = {0, 1, 2}\n if c > 0:\n choices.discard(mask//basis) # get left grid\n for x in choices:\n new_masks.append((x*basis)+(mask//3)) # encoding mask\n masks = new_masks\n return masks\n\n def find_adj(m, basis, dp):\n # Time: 3*2^(m-1) * (1 + 2 + 2 * (3/2) + 2 * (3/2)^2 + ... + 2 * (3/2)^(m-2)) =\n # 3*2^(m-1) * (1+2*((3/2)^(m-1)-1)/((3/2)-1)) =\n # 3*2^(m-1) * (1+4*((3/2)^(m-1)-1)) =\n # 3*2^(m-1) * (4*(3/2)^(m-1)-3) =\n # 4*3^m-9*2^(m-1) =\n # O(3^m),\n # Space: O(3^m)\n adj = collections.defaultdict(list)\n for mask in dp.iterkeys(): # O(2^m)\n adj[mask].append(mask)\n for c in range(m):\n assert(sum(len(v) for v in adj.itervalues()) == (3**c * 2**(m-(c-1)) if c >= 1 else 3 * 2**(m-1)) // 3 // (2 if m >= 2 else 1)) # divided by 3 * 2 is since the first two colors are normalized to speed up performance\n new_adj = collections.defaultdict(list)\n for mask1, mask2s in adj.iteritems():\n for mask in mask2s:\n choices = {0, 1, 2}\n choices.discard(mask%3) # get up grid\n if c > 0:\n choices.discard(mask//basis) # get left grid\n for x in choices:\n new_adj[mask1].append((x*basis)+(mask//3)) # encoding mask\n adj = new_adj\n assert(sum(3**c * 2**(m-(c-1)) if c >= 1 else 3 * 2**(m-1) for c in range(m)) == 4*3**m-9*2**(m-1))\n return adj\n \n def normalize(basis, mask):\n norm = {}\n result = 0\n while basis:\n x = mask//basis%3\n if x not in norm:\n norm[x] = len(norm)\n result += norm[x]*basis\n basis //= 3\n return result\n\n if m > n:\n m, n = n, m\n basis = 3**(m-1)\n masks = find_masks(m, basis) # alternative of backtracking, Time: O(2^m), Space: O(2^m)\n assert(len(masks) == 3 * 2**(m-1))\n lookup = {mask:normalize(basis, mask) for mask in masks} # Time: O(m * 2^m)\n dp = collections.Counter(lookup[mask] for mask in masks) # normalize colors to speed up performance\n adj = find_adj(m, basis, dp) # alternative of backtracking, Time: O(3^m), Space: O(3^m)\n # proof:\n # 'o' uses the same color with its bottom-left one, \n # 'x' uses the remaining color different from its left one and bottom-left one,\n # k is the cnt of 'o', \n # [3, 1(o), 1(x), 1(o), ..., 1(o), 1(x)] => nCr(m-1, k) * 3 * 2 * 2^k for k in range(m) = 3 * 2 * (2+1)^(m-1) = 2*3^m combinations\n # [2, 2, 1, 2, ..., 2, 1]\n # another proof:\n # given previous pair of colors, each pair of '?' has 3 choices of colors\n # [3, ?, ?, ..., ?] => 3 * 2 * 3^(m-1) = 2*3^m combinations\n # | | |\n # 3 3 3\n # | | |\n # [2, ?, ?, ..., ?]\n normalized_adj = collections.defaultdict(lambda:collections.defaultdict(int))\n for mask1, mask2s in adj.iteritems():\n for mask2 in mask2s:\n normalized_adj[lookup[mask1]][lookup[mask2]] = (normalized_adj[lookup[mask1]][lookup[mask2]]+1)%MOD\n # divided by 3 * 2 is since the first two colors in upper row are normalized to speed up performance,\n # since first two colors in lower row which has at most 3 choices could be also normalized, lower bound is upper bound divided by at most 3\n assert(2*3**m // 3 // 2 // 3 <= sum(len(v) for v in normalized_adj.itervalues()) <= 2*3**m // 3 // 2)\n for _ in range(n-1): # Time: O(n * 3^m), Space: O(2^m)\n assert(len(dp) == 3*2**(m-1) // 3 // (2 if m >= 2 else 1)) # divided by 3 * 2 is since the first two colors are normalized to speed up performance\n new_dp = collections.Counter()\n for mask, v in dp.iteritems():\n for new_mask, cnt in normalized_adj[mask].iteritems():\n new_dp[lookup[new_mask]] = (new_dp[lookup[new_mask]] + v*cnt) % MOD\n dp = new_dp\n return reduce(lambda x,y: (x+y)%MOD, dp.itervalues(), 0) # Time: O(2^m)\n\n\n# Time: (m * n grids) * (O(3*3*2^(m-2)) possible states per grid) = O(n * m * 2^m)\n# Space: O(3*3*2^(m-2)) = O(2^m)\nimport collections\n\n\n# better complexity for large m, large n\nclass Solution3(object):\n def colorTheGrid(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n def normalize(basis, mask, lookup): # compute and cache, at most O(3*2^(m-3)) time and space\n if mask not in lookup[basis]:\n norm = {}\n result, b = 0, basis\n while b:\n x = mask//b%3\n if x not in norm:\n norm[x] = len(norm)\n result += norm[x]*b\n b //= 3\n lookup[basis][mask] = result\n return lookup[basis][mask]\n\n if m > n:\n m, n = n, m\n basis = b = 3**(m-1)\n lookup = collections.defaultdict(dict)\n dp = collections.Counter({0: 1})\n for idx in range(m*n):\n r, c = divmod(idx, m)\n # sliding window with size m doesn't cross rows:\n # [3, 2, ..., 2] => 3*2^(m-1) combinations\n assert(r != 0 or c != 0 or len(dp) == 1)\n assert(r != 0 or c == 0 or len(dp) == 3*2**(c-1) // 3 // (2 if c >= 2 else 1)) # divided by 3 * 2 is since the first two colors are normalized to speed up performance\n assert(r == 0 or c != 0 or len(dp) == 3*2**(m-1) // 3 // (2 if m >= 2 else 1)) # divided by 3 * 2 is since the first two colors are normalized to speed up performance\n # sliding window with size m crosses rows:\n # [*, ..., *, *, 3, 2, ..., 2] => 3*3 * 2^(m-2) combinations\n # [2, ..., 2, 3, *, *, ..., *]\n assert(r == 0 or c == 0 or len(dp) == (1 if m == 1 else 2 if m == 2 else 3*3 * 2**(m-2) // 3 // 2)) # divided by 3 * 2 for m >= 3 is since the first two colors of window are normalized to speed up performance\n new_dp = collections.Counter()\n for mask, v in dp.iteritems():\n choices = {0, 1, 2}\n if r > 0:\n choices.discard(mask%3) # get up grid\n if c > 0:\n choices.discard(mask//basis) # get left grid\n for x in choices:\n new_mask = normalize(basis//b, ((x*basis)+(mask//3))//b, lookup)*b # encoding mask\n new_dp[new_mask] = (new_dp[new_mask]+v)%MOD\n if b > 1:\n b //= 3\n dp = new_dp\n return reduce(lambda x,y: (x+y)%MOD, dp.itervalues(), 0) # Time: O(2^m)\n"}} diff --git a/cp/cp-11282.jsonl b/cp/cp-11282.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..84e3bb45bcde939b365f4c415d2c15bf691f9b40 --- /dev/null +++ b/cp/cp-11282.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11282", "name": "LeetCode 1932: Merge Bsts To Create Single 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: Merge BSTs to Create Single BST (Difficulty: Hard)\nTags: Hash Table, Binary Search, Tree, Depth-First Search, Binary Tree\n\nYou are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value. In one operation, you can:\nReturn the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST.\nA BST (binary search tree) is a binary tree where each node satisfies the following property:\nA leaf is a node that has no children.\n\nExample 1:\nInput: trees = [[2,1],[3,2,5],[5,4]]\nOutput: [3,2,5,1,null,4]\nExplanation:\nIn the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].\nDelete trees[0], so trees = [[3,2,5,1],[5,4]].\n\nIn the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[3,2,5,1,null,4]].\n\nThe resulting tree, shown above, is a valid BST, so return its root.\n\nExample 2:\nInput: trees = [[5,3,8],[3,2,6]]\nOutput: []\nExplanation:\nPick i=0 and j=1 and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[5,3,8,2,6]].\n\nThe resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.\n\nExample 3:\nInput: trees = [[5,4],[3]]\nOutput: []\nExplanation: It is impossible to perform any operations.\n\nConstraints:\n- n == trees.length\n- 1 <= n <= 5 * 10^4\n- The number of nodes in each tree is in the range [1, 3].\n- Each node in the input may have children but no grandchildren.\n- No two roots of trees have the same value.\n- All the trees in the input are valid BSTs.\n- 1 <= TreeNode.val <= 5 * 10^4."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, val=0, left=None, right=None):\n pass\n\n\nclass Solution(object):\n def canMerge(self, trees):\n \"\"\"\n :type trees: List[TreeNode]\n :rtype: TreeNode\n \"\"\"\n def find_leaves_and_roots(trees, leaf_vals_set, val_to_root):\n for root in trees:\n val_to_root[root.val] = root\n q = [root]\n while q:\n new_q = []\n for node in q:\n if node.left is None and node.right is None:\n if node is not root:\n leaf_vals_set.add(node.val)\n continue\n if node.left:\n new_q.append(node.left)\n if node.right:\n new_q.append(node.right)\n q = new_q\n\n def find_root(trees, left_vals_set, val_to_root):\n root = None\n for node in trees:\n if node.val in leaf_vals_set:\n continue\n if root: # multiple roots\n return None\n root = node\n return root\n\n def merge_bsts(root, left_vals_set, val_to_root):\n if not root:\n return None\n del val_to_root[root.val]\n q = [(root, float(\"-inf\"), float(\"inf\"))]\n while q:\n new_q = []\n for node, left, right in q:\n if not (left < node.val < right):\n return None\n if node.left:\n if node.left.val in leaf_vals_set and node.left.val in val_to_root:\n node.left = val_to_root[node.left.val]\n del val_to_root[node.left.val]\n new_q.append((node.left, left, node.val))\n if node.right:\n if node.right.val in leaf_vals_set and node.right.val in val_to_root:\n node.right = val_to_root[node.right.val]\n del val_to_root[node.right.val]\n new_q.append((node.right, node.val, right))\n q = new_q\n return root if not val_to_root else None\n\n leaf_vals_set, val_to_root = set(), {}\n find_leaves_and_roots(trees, leaf_vals_set, val_to_root) \n root = find_root(trees, leaf_vals_set, val_to_root)\n return merge_bsts(root, leaf_vals_set, val_to_root)\n"}} diff --git a/cp/cp-11284.jsonl b/cp/cp-11284.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5d3908dcba388799c890ba0798fd5d3f50d73aea --- /dev/null +++ b/cp/cp-11284.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11284", "name": "LeetCode 1935: Maximum Number Of Words You Can Type"} +{"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 Number of Words You Can Type (Difficulty: Easy)\nTags: Hash Table, String\n\nThere is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.\nGiven a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard.\n\nExample 1:\nInput: text = \"hello world\", brokenLetters = \"ad\"\nOutput: 1\nExplanation: We cannot type \"world\" because the 'd' key is broken.\n\nExample 2:\nInput: text = \"leet code\", brokenLetters = \"lt\"\nOutput: 1\nExplanation: We cannot type \"leet\" because the 'l' and 't' keys are broken.\n\nExample 3:\nInput: text = \"leet code\", brokenLetters = \"e\"\nOutput: 0\nExplanation: We cannot type either word because the 'e' key is broken.\n\nConstraints:\n- 1 <= text.length <= 10^4\n- 0 <= brokenLetters.length <= 26\n- text consists of words separated by a single space without any leading or trailing spaces.\n- Each word only consists of lowercase English letters.\n- brokenLetters consists of distinct lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def canBeTypedWords(self, text, brokenLetters):\n \"\"\"\n :type text: str\n :type brokenLetters: str\n :rtype: int\n \"\"\"\n lookup = set(brokenLetters)\n result, broken = 0, False\n for c in text:\n if c == ' ':\n result += int(broken == False)\n broken = False\n elif c in lookup:\n broken = True\n return result + int(broken == False)\n"}} diff --git a/cp/cp-11285.jsonl b/cp/cp-11285.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..018cc4111e0d2c8d01f6a9c192f5d1a2413e6a3a --- /dev/null +++ b/cp/cp-11285.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11285", "name": "LeetCode 1936: Add Minimum Number Of Rungs"} +{"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 Minimum Number of Rungs (Difficulty: Medium)\nTags: Array, Greedy\n\nYou are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung.\nYou are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there.\nReturn the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung.\n\nExample 1:\nInput: rungs = [1,3,5,10], dist = 2\nOutput: 2\nExplanation:\nYou currently cannot reach the last rung.\nAdd rungs at heights 7 and 8 to climb this ladder. \nThe ladder will now have rungs at [1,3,5,7,8,10].\n\nExample 2:\nInput: rungs = [3,6,8,10], dist = 3\nOutput: 0\nExplanation:\nThis ladder can be climbed without adding additional rungs.\n\nExample 3:\nInput: rungs = [3,4,6,7], dist = 2\nOutput: 1\nExplanation:\nYou currently cannot reach the first rung from the ground.\nAdd a rung at height 1 to climb this ladder.\nThe ladder will now have rungs at [1,3,4,6,7].\n\nConstraints:\n- 1 <= rungs.length <= 10^5\n- 1 <= rungs[i] <= 10^9\n- 1 <= dist <= 10^9\n- rungs is strictly increasing."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def addRungs(self, rungs, dist):\n \"\"\"\n :type rungs: List[int]\n :type dist: int\n :rtype: int\n \"\"\"\n def ceil_divide(a, b):\n return (a+(b-1))//b\n\n result = prev = 0\n for curr in rungs:\n result += ceil_divide(curr-prev, dist)-1\n prev = curr\n return result\n"}} diff --git a/cp/cp-11286.jsonl b/cp/cp-11286.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7e76f4ea033627b8c755ac3c2ed6baf43bcf594c --- /dev/null +++ b/cp/cp-11286.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11286", "name": "LeetCode 1937: Maximum Number Of Points With Cost"} +{"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 Number of Points with Cost (Difficulty: Medium)\nTags: Array, Dynamic Programming, Matrix\n\nYou are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.\nTo gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.\nHowever, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.\nReturn the maximum number of points you can achieve.\nabs(x) is defined as:\n\nExample 1:\nInput: points = [[1,2,3],[1,5,1],[3,1,1]]\nOutput: 9\nExplanation:\nThe blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).\nYou add 3 + 5 + 3 = 11 to your score.\nHowever, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.\nYour final score is 11 - 2 = 9.\n\nExample 2:\nInput: points = [[1,5],[2,3],[4,2]]\nOutput: 11\nExplanation:\nThe blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).\nYou add 5 + 3 + 4 = 12 to your score.\nHowever, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.\nYour final score is 12 - 1 = 11.\n\nConstraints:\n- m == points.length\n- n == points[r].length\n- 1 <= m, n <= 10^5\n- 1 <= m * n <= 10^5\n- 0 <= points[r][c] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(n)\n\nclass Solution(object):\n def maxPoints(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n dp = points[0]\n for i in range(1, len(points)):\n prefix = [0]*len(points[i])\n prefix[0] = dp[0]\n for j in range(1, len(points[i])):\n prefix[j] = max(prefix[j-1], dp[j]+j)\n suffix = [0]*len(points[i])\n suffix[-1] = dp[-1]-(len(points[i])-1)\n for j in reversed(range(len(points[i])-1)):\n suffix[j] = max(suffix[j+1], dp[j]-j)\n new_dp = [0]*len(points[i])\n for j in range(len(points[i])):\n new_dp[j] = max(prefix[j]-j, suffix[j]+j)+points[i][j]\n dp = new_dp\n return max(dp)\n"}} diff --git a/cp/cp-11287.jsonl b/cp/cp-11287.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a748b0d094dbd847f788d8822df9ad00e8426751 --- /dev/null +++ b/cp/cp-11287.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11287", "name": "LeetCode 1938: Maximum Genetic Difference Query"} +{"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 Genetic Difference Query (Difficulty: Hard)\nTags: Array, Hash Table, Bit Manipulation, Depth-First Search, Trie\n\nThere is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node's number denotes its unique genetic value (i.e. the genetic value of node x is x). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array parents, where parents[i] is the parent for node i. If node x is the root of the tree, then parents[x] == -1.\nYou are also given the array queries where queries[i] = [nodei, vali]. For each query i, find the maximum genetic difference between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi.\nReturn an array ans where ans[i] is the answer to the ith query.\n\nExample 1:\nInput: parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]]\nOutput: [2,3,7]\nExplanation: The queries are processed as follows:\n- [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2.\n- [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3.\n- [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.\n\nExample 2:\nInput: parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]]\nOutput: [6,14,7]\nExplanation: The queries are processed as follows:\n- [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6.\n- [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14.\n- [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.\n\nConstraints:\n- 2 <= parents.length <= 10^5\n- 0 <= parents[i] <= parents.length - 1 for every node i that is not the root.\n- parents[root] == -1\n- 1 <= queries.length <= 3 * 10^4\n- 0 <= nodei <= parents.length - 1\n- 0 <= vali <= 2 * 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogk + mlogk), k is max(max(vals), n-1)\n# Space: O(n + logk)\n\nimport collections\n\n\nclass Trie(object):\n def __init__(self, bit_count):\n self.__root = {}\n self.__bit_count = bit_count\n \n def insert(self, num, v):\n node = self.__root\n for i in reversed(range(self.__bit_count)):\n curr = (num>>i) & 1\n new_node = node.setdefault(curr, collections.defaultdict(int))\n new_node[\"_cnt\"] += v\n if not new_node[\"_cnt\"]:\n del node[curr]\n break\n node = new_node\n \n def query(self, num):\n node, result = self.__root, 0\n for i in reversed(range(self.__bit_count)):\n curr = (num>>i) & 1\n if 1^curr in node:\n node = node[1^curr]\n result |= 1<>i) & 1\n new_node = node.setdefault(curr, collections.defaultdict(int))\n new_node[\"_cnt\"] += v\n if not new_node[\"_cnt\"]:\n del node[curr]\n break\n node = new_node\n \n def query(self, num):\n node, result = self.__root, 0\n for i in reversed(range(self.__bit_count)):\n curr = (num>>i) & 1\n if 1^curr in node:\n node = node[1^curr]\n result |= 1< max(heights[i+1], heights[i+2], ..., heights[j-1]).\nReturn an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.\n\nExample 1:\nInput: heights = [10,6,8,5,11,9]\nOutput: [3,1,2,1,1,0]\nExplanation:\nPerson 0 can see person 1, 2, and 4.\nPerson 1 can see person 2.\nPerson 2 can see person 3 and 4.\nPerson 3 can see person 4.\nPerson 4 can see person 5.\nPerson 5 can see no one since nobody is to the right of them.\n\nExample 2:\nInput: heights = [5,1,2,3,10]\nOutput: [4,1,1,1,0]\n\nConstraints:\n- n == heights.length\n- 1 <= n <= 10^5\n- 1 <= heights[i] <= 10^5\n- All the values of heights are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def canSeePersonsCount(self, heights):\n \"\"\"\n :type heights: List[int]\n :rtype: List[int]\n \"\"\"\n result = [0]*len(heights)\n stk = []\n for i, h in enumerate(heights):\n while stk and heights[stk[-1]] < h:\n result[stk.pop()] += 1\n if stk:\n result[stk[-1]] += 1\n if stk and heights[stk[-1]] == h:\n stk.pop()\n stk.append(i)\n return result\n\n\n# Time: O(n)\n# Space: O(n)\nclass Solution2(object):\n def canSeePersonsCount(self, heights):\n \"\"\"\n :type heights: List[int]\n :rtype: List[int]\n \"\"\"\n result = [0]*len(heights)\n stk = []\n for i in reversed(range(len(heights))):\n cnt = 0\n while stk and heights[stk[-1]] < heights[i]:\n stk.pop()\n cnt += 1\n result[i] = cnt+1 if stk else cnt\n if stk and heights[stk[-1]] == heights[i]:\n stk.pop()\n stk.append(i)\n return result\n"}} diff --git a/cp/cp-11293.jsonl b/cp/cp-11293.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..57f2d2a1c70284ed76ab21282a6b5c83917c7f60 --- /dev/null +++ b/cp/cp-11293.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11293", "name": "LeetCode 1945: Sum Of Digits Of String After Convert"} +{"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 Digits of String After Convert (Difficulty: Easy)\nTags: String, Simulation\n\nYou are given a string s consisting of lowercase English letters, and an integer k. Your task is to convert the string into an integer by a special process, and then transform it by summing its digits repeatedly k times. More specifically, perform the following steps:\nFor example, if s = \"zbax\" and k = 2, then the resulting integer would be 8 by the following operations:\nReturn the resulting integer after performing the operations described above.\n\nExample 1:\nInput: s = \"iiii\", k = 1\nOutput: 36\nExplanation:\nThe operations are as follows: - Convert: \"iiii\" ➝ \"(9)(9)(9)(9)\" ➝ \"9999\" ➝ 9999 - Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36 Thus the resulting integer is 36.\n\nExample 2:\nInput: s = \"leetcode\", k = 2\nOutput: 6\nExplanation:\nThe operations are as follows: - Convert: \"leetcode\" ➝ \"(12)(5)(5)(20)(3)(15)(4)(5)\" ➝ \"12552031545\" ➝ 12552031545 - Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33 - Transform #2: 33 ➝ 3 + 3 ➝ 6 Thus the resulting integer is 6.\n\nExample 3:\nInput: s = \"zbax\", k = 2\nOutput: 8\n\nConstraints:\n- 1 <= s.length <= 100\n- 1 <= k <= 10\n- s consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + logn + log(logn) + ...) = O(n)\n# Space: O(1)\n\nclass Solution(object):\n def getLucky(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: int\n \"\"\"\n total = reduce(lambda total, x: total+sum(divmod((ord(x)-ord('a')+1), 10)), s, 0)\n while k > 1 and total > 9:\n new_total = 0\n while total:\n total, x = divmod(total, 10)\n new_total += x\n total = new_total\n k -= 1\n return total\n"}} diff --git a/cp/cp-11294.jsonl b/cp/cp-11294.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..18ac2a6e01e0822701a9dde1d86ad00ac9b15d6a --- /dev/null +++ b/cp/cp-11294.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11294", "name": "LeetCode 1946: Largest Number After Mutating Substring"} +{"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: Largest Number After Mutating Substring (Difficulty: Medium)\nTags: Array, String, Greedy\n\nYou are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d].\nYou may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]).\nReturn a string representing the largest possible integer after mutating (or choosing not to) a single substring of num.\nA substring is a contiguous sequence of characters within the string.\n\nExample 1:\nInput: num = \"132\", change = [9,8,5,0,3,6,4,2,6,8]\nOutput: \"832\"\nExplanation: Replace the substring \"1\":\n- 1 maps to change[1] = 8.\nThus, \"132\" becomes \"832\".\n\"832\" is the largest number that can be created, so return it.\n\nExample 2:\nInput: num = \"021\", change = [9,4,3,5,7,2,1,9,0,6]\nOutput: \"934\"\nExplanation: Replace the substring \"021\":\n- 0 maps to change[0] = 9.\n- 2 maps to change[2] = 3.\n- 1 maps to change[1] = 4.\nThus, \"021\" becomes \"934\".\n\"934\" is the largest number that can be created, so return it.\n\nExample 3:\nInput: num = \"5\", change = [1,4,7,5,3,2,5,6,9,4]\nOutput: \"5\"\nExplanation: \"5\" is already the largest number that can be created, so return it.\n\nConstraints:\n- 1 <= num.length <= 10^5\n- num consists of only digits 0-9.\n- change.length == 10\n- 0 <= change[d] <= 9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def maximumNumber(self, num, change):\n \"\"\"\n :type num: str\n :type change: List[int]\n :rtype: str\n \"\"\"\n mutated = False\n result = map(int, list(num))\n for i, d in enumerate(result):\n if change[d] < d:\n if mutated:\n break\n elif change[d] > d:\n result[i] = str(change[d])\n mutated = True\n return \"\".join(map(str, result))\n"}} diff --git a/cp/cp-11295.jsonl b/cp/cp-11295.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a1503fd36e954d40de9d05b671764408df382002 --- /dev/null +++ b/cp/cp-11295.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11295", "name": "LeetCode 1947: Maximum Compatibility Score Sum"} +{"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 Compatibility Score Sum (Difficulty: Medium)\nTags: Array, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask\n\nThere is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes).\nThe survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed).\nEach student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor.\nYou are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores.\nGiven students and mentors, return the maximum compatibility score sum that can be achieved.\n\nExample 1:\nInput: students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]\nOutput: 8\nExplanation: We assign students to mentors in the following way:\n- student 0 to mentor 2 with a compatibility score of 3.\n- student 1 to mentor 0 with a compatibility score of 2.\n- student 2 to mentor 1 with a compatibility score of 3.\nThe compatibility score sum is 3 + 2 + 3 = 8.\n\nExample 2:\nInput: students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]\nOutput: 0\nExplanation: The compatibility score of any student-mentor pair is 0.\n\nConstraints:\n- m == students.length == mentors.length\n- n == students[i].length == mentors[j].length\n- 1 <= m, n <= 8\n- students[i][k] is either 0 or 1.\n- mentors[j][k] is either 0 or 1."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m^2 * (n + m))\n# Space: O(m^2)\n\nimport itertools\n\n\n# weighted bipartite matching solution\nclass Solution(object):\n def maxCompatibilitySum(self, students, mentors):\n \"\"\"\n :type students: List[List[int]]\n :type mentors: List[List[int]]\n :rtype: int\n \"\"\"\n # Template translated from:\n # https://github.com/kth-competitive-programming/kactl/blob/main/content/graph/WeightedMatching.h\n def hungarian(a): # Time: O(n^2 * m), Space: O(n + m)\n if not a:\n return 0, []\n n, m = len(a)+1, len(a[0])+1\n u, v, p, ans = [0]*n, [0]*m, [0]*m, [0]*(n-1)\n for i in range(1, n):\n p[0] = i\n j0 = 0 # add \"dummy\" worker 0\n dist, pre = [float(\"inf\")]*m, [-1]*m\n done = [False]*(m+1)\n while True: # dijkstra\n done[j0] = True\n i0, j1, delta = p[j0], None, float(\"inf\")\n for j in range(1, m):\n if done[j]:\n continue\n cur = a[i0-1][j-1]-u[i0]-v[j]\n if cur < dist[j]:\n dist[j], pre[j] = cur, j0\n if dist[j] < delta:\n delta, j1 = dist[j], j\n for j in range(m):\n if done[j]:\n u[p[j]] += delta\n v[j] -= delta\n else:\n dist[j] -= delta\n j0 = j1\n if not p[j0]:\n break\n while j0: # update alternating path\n j1 = pre[j0]\n p[j0], j0 = p[j1], j1\n for j in range(1, m):\n if p[j]:\n ans[p[j]-1] = j-1\n return -v[0], ans # min cost\n\n def score(s, m):\n return sum(int(a == b) for a, b in itertools.izip(s, m))\n\n return -hungarian([[-score(s, m) for m in mentors] for s in students])[0]\n\n\n# Time: O(m * (n + 2^m))\n# Space: O(2^m)\n# dp solution\nclass Solution2(object):\n def maxCompatibilitySum(self, students, mentors):\n \"\"\"\n :type students: List[List[int]]\n :type mentors: List[List[int]]\n :rtype: int\n \"\"\"\n def popcount(n): # Time: O(logn) ~= O(1) if n is a 32-bit number\n result = 0\n while n:\n n &= n-1\n result += 1\n return result\n\n def masks(vvi):\n result = []\n for vi in vvi:\n mask, bit = 0, 1\n for i in range(len(vi)):\n if vi[i]:\n mask |= bit\n bit <<= 1\n result.append(mask)\n return result\n\n nums1, nums2 = masks(students), masks(mentors)\n dp = [(0, 0)]*(2**len(nums2))\n for mask in range(len(dp)):\n bit = 1\n for i in range(len(nums2)):\n if (mask&bit) == 0:\n dp[mask|bit] = max(dp[mask|bit], (dp[mask][0]+(len(students[0])-popcount(nums1[dp[mask][1]]^nums2[i])), dp[mask][1]+1))\n bit <<= 1\n return dp[-1][0]\n"}} diff --git a/cp/cp-11296.jsonl b/cp/cp-11296.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b0e787b2d32054e4a8127c7aee315e5fd1adab24 --- /dev/null +++ b/cp/cp-11296.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11296", "name": "LeetCode 1948: Delete Duplicate Folders 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: Delete Duplicate Folders in System (Difficulty: Hard)\nTags: Array, Hash Table, String, Trie, Hash Function\n\nDue to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system.\nTwo folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical, then mark the folders as well as all their subfolders.\nOnce all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted.\nReturn the 2D array ans containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order.\n\nExample 1:\nInput: paths = [[\"a\"],[\"c\"],[\"d\"],[\"a\",\"b\"],[\"c\",\"b\"],[\"d\",\"a\"]]\nOutput: [[\"d\"],[\"d\",\"a\"]]\nExplanation: The file structure is as shown.\nFolders \"/a\" and \"/c\" (and their subfolders) are marked for deletion because they both contain an empty\nfolder named \"b\".\n\nExample 2:\nInput: paths = [[\"a\"],[\"c\"],[\"a\",\"b\"],[\"c\",\"b\"],[\"a\",\"b\",\"x\"],[\"a\",\"b\",\"x\",\"y\"],[\"w\"],[\"w\",\"y\"]]\nOutput: [[\"c\"],[\"c\",\"b\"],[\"a\"],[\"a\",\"b\"]]\nExplanation: The file structure is as shown. \nFolders \"/a/b/x\" and \"/w\" (and their subfolders) are marked for deletion because they both contain an empty folder named \"y\".\nNote that folders \"/a\" and \"/c\" are identical after the deletion, but they are not deleted because they were not marked beforehand.\n\nExample 3:\nInput: paths = [[\"a\",\"b\"],[\"c\",\"d\"],[\"c\"],[\"a\"]]\nOutput: [[\"c\"],[\"c\",\"d\"],[\"a\"],[\"a\",\"b\"]]\nExplanation: All folders are unique in the file system.\nNote that the returned array can be in a different order as the order does not matter.\n\nConstraints:\n- 1 <= paths.length <= 2 * 10^4\n- 1 <= paths[i].length <= 500\n- 1 <= paths[i][j].length <= 10\n- 1 <= sum(paths[i][j].length) <= 2 * 10^5\n- path[i][j] consists of lowercase English letters.\n- No two paths lead to the same folder.\n- For any folder not at the root level, its parent folder will also be in the input."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * m * l + tlogt + l * t), m is the max number of folders in a path,\n# , n is the number of paths\n# , l is the max length of folder name\n# , t is the size of trie\n# Space: O(l * t)\n\nimport collections\n\n\nclass Solution(object):\n def deleteDuplicateFolder(self, paths):\n \"\"\"\n :type paths: List[List[str]]\n :rtype: List[List[str]]\n \"\"\"\n def mark(node, lookup, node_ids):\n id_pairs = []\n for subfolder_id, child in node.iteritems():\n if child == \"_del\":\n continue\n id_pairs.append((subfolder_id, mark(child, lookup, node_ids)))\n id_pairs.sort()\n node_id = node_ids[tuple(id_pairs)]\n if node_id:\n if node_id in lookup:\n lookup[node_id][\"_del\"]\n node[\"_del\"]\n else:\n lookup[node_id] = node\n return node_id\n\n def sweep(node, id_folders, path, result):\n if path:\n result.append([id_folders[i] for i in path])\n for subfolder_id, child in node.iteritems():\n if \"_del\" in child:\n continue\n path.append(subfolder_id)\n sweep(child, id_folders, path, result)\n path.pop()\n\n _trie = lambda: collections.defaultdict(_trie)\n trie = _trie()\n folder_ids = collections.defaultdict()\n folder_ids.default_factory = folder_ids.__len__\n id_folders = {}\n for path in paths:\n node = trie\n for folder in path:\n if folder_ids[folder] not in id_folders:\n id_folders[folder_ids[folder]] = folder\n node = node[folder_ids[folder]]\n node_ids = collections.defaultdict()\n node_ids.default_factory = node_ids.__len__\n mark(trie, {}, node_ids)\n result = []\n sweep(trie, id_folders, [], result)\n return result\n\n\n# Time: O(n * m * l + l * tlogt + l * t^2), m is the max number of folders in a path,\n# , n is the number of paths\n# , l is the max length of folder name\n# , t is the size of trie\n# Space: O(l * t^2)\nimport collections\n\n\nclass Solution2(object):\n def deleteDuplicateFolder(self, paths):\n \"\"\"\n :type paths: List[List[str]]\n :rtype: List[List[str]]\n \"\"\"\n def mark(node, lookup):\n serialized_tree = \"(\" + \"\".join(subfolder + mark(child, lookup) for subfolder, child in sorted(node.iteritems()) if child != \"_del\") + \")\"\n if serialized_tree != \"()\":\n if serialized_tree in lookup:\n lookup[serialized_tree][\"_del\"]\n node[\"_del\"]\n else:\n lookup[serialized_tree] = node\n return serialized_tree\n \n def sweep(node, path, result):\n if path:\n result.append(path[:])\n for subfolder, child in node.iteritems():\n if \"_del\" in child:\n continue\n path.append(subfolder)\n sweep(child, path, result)\n path.pop()\n\n _trie = lambda: collections.defaultdict(_trie)\n trie = _trie()\n for path in paths:\n reduce(dict.__getitem__, path, trie)\n mark(trie, {})\n result = []\n sweep(trie, [], result)\n return result\n"}} diff --git a/cp/cp-11298.jsonl b/cp/cp-11298.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b183da16573d5bbc252045a3e3a586d4522a400f --- /dev/null +++ b/cp/cp-11298.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11298", "name": "LeetCode 1952: Three Divisors"} +{"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: Three Divisors (Difficulty: Easy)\nTags: Math, Enumeration, Number Theory\n\nGiven an integer n, return true if n has exactly three positive divisors. Otherwise, return false.\nAn integer m is a divisor of n if there exists an integer k such that n = k * m.\n\nExample 1:\nInput: n = 2\nOutput: false\nExplantion: 2 has only two divisors: 1 and 2.\n\nExample 2:\nInput: n = 4\nOutput: true\nExplantion: 4 has three divisors: 1, 2, and 4.\n\nConstraints:\n- 1 <= n <= 10^4"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(sqrt(n))\n# Space: O(1)\n\nclass Solution(object):\n def isThree(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n cnt = 0\n i = 1\n while i*i <= n and cnt <= 3:\n if n%i == 0:\n cnt += 1 if i*i == n else 2\n i += 1\n return cnt == 3\n"}} diff --git a/cp/cp-11299.jsonl b/cp/cp-11299.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..67dbab1bac770ada58d49ba365ed1011baf9d5be --- /dev/null +++ b/cp/cp-11299.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11299", "name": "LeetCode 1953: Maximum Number Of Weeks For Which You Can Work"} +{"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 Number of Weeks for Which You Can Work (Difficulty: Medium)\nTags: Array, Greedy\n\nThere are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has.\nYou can work on the projects following these two rules:\nOnce all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints.\nReturn the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.\n\nExample 1:\nInput: milestones = [1,2,3]\nOutput: 6\nExplanation: One possible scenario is:\n​​​​- During the 1st week, you will work on a milestone of project 0.\n- During the 2nd week, you will work on a milestone of project 2.\n- During the 3rd week, you will work on a milestone of project 1.\n- During the 4th week, you will work on a milestone of project 2.\n- During the 5th week, you will work on a milestone of project 1.\n- During the 6th week, you will work on a milestone of project 2.\nThe total number of weeks is 6.\n\nExample 2:\nInput: milestones = [5,2,1]\nOutput: 7\nExplanation: One possible scenario is:\n- During the 1st week, you will work on a milestone of project 0.\n- During the 2nd week, you will work on a milestone of project 1.\n- During the 3rd week, you will work on a milestone of project 0.\n- During the 4th week, you will work on a milestone of project 1.\n- During the 5th week, you will work on a milestone of project 0.\n- During the 6th week, you will work on a milestone of project 2.\n- During the 7th week, you will work on a milestone of project 0.\nThe total number of weeks is 7.\nNote that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules.\nThus, one milestone in project 0 will remain unfinished.\n\nConstraints:\n- n == milestones.length\n- 1 <= n <= 10^5\n- 1 <= milestones[i] <= 10^9"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def numberOfWeeks(self, milestones):\n \"\"\"\n :type milestones: List[int]\n :rtype: int\n \"\"\"\n total, max_num = sum(milestones), max(milestones)\n other_total = (total-max_num)\n return other_total+min(other_total+1, max_num)\n"}} diff --git a/cp/cp-11300.jsonl b/cp/cp-11300.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6355d2156afbef715a0eafc04209c573d4173d6d --- /dev/null +++ b/cp/cp-11300.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11300", "name": "LeetCode 1954: Minimum Garden Perimeter To Collect Enough Apples"} +{"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: Minimum Garden Perimeter to Collect Enough Apples (Difficulty: Medium)\nTags: Math, Binary Search\n\nIn a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it.\nYou will buy an axis-aligned square plot of land that is centered at (0, 0).\nGiven an integer neededApples, return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot.\nThe value of |x| is defined as:\n\nExample 1:\nInput: neededApples = 1\nOutput: 8\nExplanation: A square plot of side length 1 does not contain any apples.\nHowever, a square plot of side length 2 has 12 apples inside (as depicted in the image above).\nThe perimeter is 2 * 4 = 8.\n\nExample 2:\nInput: neededApples = 13\nOutput: 16\n\nExample 3:\nInput: neededApples = 1000000000\nOutput: 5040\n\nConstraints:\n- 1 <= neededApples <= 10^15"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(1)\n# Space: O(1)\n\nimport math\n\n\nclass Solution(object):\n def minimumPerimeter(self, neededApples):\n \"\"\"\n :type neededApples: int\n :rtype: int\n \"\"\"\n # find min r, s.t. 4r^3+6r^2+2r-neededApples >= 0\n # => by depressed cubic (https://en.wikipedia.org/wiki/Cubic_equation#Depressed_cubic)\n # let x = r+(6/(3*4)), r = x-(1/2)\n # 4(x-(1/2))^3+6(x-(1/2))^2+2(x-(1/2))-neededApples\n # = 4(x^3-3/2x^2+3/4x-1/8)\n # + 6(x^2-x+1/4)\n # + 2(x-1/2)\n # = 4x^3-x-neededApples >= 0\n #\n # find x, s.t. 4x^3-x-neededApples = 0 <=> x^3+(-1/4)x+(-neededApples/4) = 0\n # => by Cardano's formula (https://en.wikipedia.org/wiki/Cubic_equation#Cardano's_formula)\n # x^3 + px + q = 0, p = (-1/4), q = (-neededApples/4)\n # since (q/2)^2+(p/3)^3 = neededApples^2/64-1/1728 > 0 => only one real root\n # => x = (-q/2 + ((q/2)^2+(p/3)^3)^(1/2)) + (-q/2 - ((q/2)^2+(p/3)^3)^(1/2))\n # r = x-(1/2)\n # => min r = ceil(r)\n\n a, b, c, d = 4.0, 6.0, 2.0, float(-neededApples)\n p = (3*a*c-b**2)/(3*a**2) # -1/4.0\n q = (2*b**3-9*a*b*c+27*a**2*d)/(27*a**3) # -neededApples/4.0\n assert((q/2)**2+(p/3)**3 > 0) # case of only one real root\n x = (-q/2 + ((q/2)**2+(p/3)**3)**0.5)**(1.0/3) + \\\n (-q/2 - ((q/2)**2+(p/3)**3)**0.5)**(1.0/3)\n return 8*int(math.ceil(x - b/(3*a)))\n \n\n# Time: O(1)\n# Space: O(1)\nclass Solution2(object):\n def minimumPerimeter(self, neededApples):\n \"\"\"\n :type neededApples: int\n :rtype: int\n \"\"\"\n # r+r , (r-1)+r, ..., 1+r, 0+r , 1+r, ..., (r-1)+r, r+r\n # r+(r-1), 0+(r-1), r+(r-1)\n # . . . \n # . . . \n # . . . \n # r+1 , (r-1)+1, ..., 1+1, 1+0 , 1+1, ..., (r-1)+1, r+1\n # r+0 , (r-1)+0, ..., 1+0, 0+0 , 1+0, ..., (r-1)+0, r+0\n # r+1 , (r-1)+1, ..., 1+1, 1+0 , 1+1, ..., (r-1)+1, r+1\n # . . . \n # . . . \n # . . . \n # r+(r-1), 0+(r-1), r+(r-1)\n # r+r , (r-1)+r, ..., 1+r, 0+r , 1+r, ..., r+(r-1), r+r\n #\n # each up/down direction forms an arithmetic sequence, there are 2r+1 columns\n # => 2*(1+r)*r/2 * (2r+1)\n #\n # each left/right direction forms an arithmetic sequence, there are 2r+1 rows\n # => 2*(1+r)*r/2 * (2r+1)\n #\n # => total = 2 * 2*(1+r)*r/2 * (2r+1) = r*(2r+1)*(2r+2) = 4r^3+6r^2+2r\n # => find min r, s.t. (2r)(2r+1)*(2r+2) >= 2*neededApples\n # => find min x = 2r+2, s.t. (x-2)(x-1)(x) >= 2*neededApples\n\n x = int((2*neededApples)**(1.0/3))\n x -= x%2\n assert((x-2)*(x-1)*x < 2*neededApples < (x+2)**3)\n x += 2\n if (x-2)*(x-1)*x < 2*neededApples:\n x += 2\n return 8*(x-2)//2\n\n\n# Time: O(logn)\n# Space: O(1)\nclass Solution3(object):\n def minimumPerimeter(self, neededApples):\n \"\"\"\n :type neededApples: int\n :rtype: int\n \"\"\"\n # 2r , 2r-1, ..., r+1, r , r+1, ..., 2*r-1, 2*r\n # 2r-1, r-1, 2r-1\n # . . . \n # . . . \n # . . . \n # r+1 , r, ..., 2, 1 , 2, ..., r , r+1\n # r , r-1, ..., 1, 0 , 1, ..., r-1, r\n # r+1 , r, ..., 2, 1 , 2, ..., r , r+1\n # . . . \n # . . . \n # . . . \n # 2r-1, r-1, 2r-1\n # 2r , 2r-1, ..., r+1, r , r+1, ..., 2*r-1, 2*r\n #\n # the sum of each row/col forms an arithmetic sequence\n # => let ai = (((r + (r-1) + ... + r + 0) + (0 + 1 + 2 + ... + r)) - 0) + i*(2r+1)\n # = (2*(0+r)*(r+1)/2-0) + i*(2r+1)\n # = r*(r+1) + i*(2r+1)\n # => total = 2*(a0 + a1 + ... ar) - a0\n # = 2*(r*(r+1) + r*(r+1) + r*(2r+1)))*(r+1)/2 - r*(r+1)\n # = r*(4r+3)*(r+1)-r*(r+1)\n # = 4r^3+6r^2+2r\n # => find min r, s.t. 4r^3+6r^2+2r >= neededApples\n\n def check(neededApples, x):\n return r*(2*r+1)*(2*r+2) >= neededApples\n\n left, right = 1, int((neededApples/4.0)**(1.0/3))\n while left <= right:\n mid = left + (right-left)//2\n if check(neededApples, mid):\n right = mid-1\n else:\n left = mid+1\n return 8*left\n"}} diff --git a/cp/cp-11301.jsonl b/cp/cp-11301.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e7daf43d6ee4393a5f6406a51d45467e5a5b48d7 --- /dev/null +++ b/cp/cp-11301.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11301", "name": "LeetCode 1955: Count Number Of Special 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: Count Number of Special Subsequences (Difficulty: Hard)\nTags: Array, Dynamic Programming\n\nA sequence is special if it consists of a positive number of 0s, followed by a positive number of 1s, then a positive number of 2s.\nGiven an array nums (consisting of only integers 0, 1, and 2), return the number of different subsequences that are special. Since the answer may be very large, return it modulo 109 + 7.\nA subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different.\n\nExample 1:\nInput: nums = [0,1,2,2]\nOutput: 3\nExplanation: The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2].\n\nExample 2:\nInput: nums = [2,2,0,0]\nOutput: 0\nExplanation: There are no special subsequences in [2,2,0,0].\n\nExample 3:\nInput: nums = [0,1,2,0,1,2]\nOutput: 7\nExplanation: The special subsequences are bolded:\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 0 <= nums[i] <= 2"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def countSpecialSubsequences(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n dp = [0]*3\n for x in nums:\n dp[x] = ((dp[x]+dp[x])%MOD+(dp[x-1] if x-1 >= 0 else 1))%MOD\n return dp[-1]\n"}} diff --git a/cp/cp-11303.jsonl b/cp/cp-11303.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5649327a090ba4699dcbdfd983ec5a9971bdbf9e --- /dev/null +++ b/cp/cp-11303.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11303", "name": "LeetCode 1957: Delete Characters To Make Fancy 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: Delete Characters to Make Fancy String (Difficulty: Easy)\nTags: String\n\nA fancy string is a string where no three consecutive characters are equal.\nGiven a string s, delete the minimum possible number of characters from s to make it fancy.\nReturn the final string after the deletion. It can be shown that the answer will always be unique.\n\nExample 1:\nInput: s = \"leeetcode\"\nOutput: \"leetcode\"\nExplanation:\nRemove an 'e' from the first group of 'e's to create \"leetcode\".\nNo three consecutive characters are equal, so return \"leetcode\".\n\nExample 2:\nInput: s = \"aaabaaaa\"\nOutput: \"aabaa\"\nExplanation:\nRemove an 'a' from the first group of 'a's to create \"aabaaaa\".\nRemove two 'a's from the second group of 'a's to create \"aabaa\".\nNo three consecutive characters are equal, so return \"aabaa\".\n\nExample 3:\nInput: s = \"aab\"\nOutput: \"aab\"\nExplanation: No three consecutive characters are equal, so return \"aab\".\n\nConstraints:\n- 1 <= s.length <= 10^5\n- s consists only of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\n# inplace solution\nclass Solution(object):\n def makeFancyString(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n s = list(s)\n cnt = j = 0\n for i, c in enumerate(s):\n cnt = cnt+1 if i >= 1 and c == s[i-1] else 1\n if cnt < 3:\n s[j] = c\n j += 1\n s[:] = s[:j]\n return \"\".join(s)\n"}} diff --git a/cp/cp-11304.jsonl b/cp/cp-11304.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5b295f15cd9a7f7345c76931e67440043072cb1b --- /dev/null +++ b/cp/cp-11304.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11304", "name": "LeetCode 1958: Check If Move Is Legal"} +{"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: Check if Move is Legal (Difficulty: Medium)\nTags: Array, Matrix, Enumeration\n\nYou are given a 0-indexed 8 x 8 grid board, where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.', white cells are represented by 'W', and black cells are represented by 'B'.\nEach move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal).\nA good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color, and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below:\nGiven two integers rMove and cMove and a character color representing the color you are playing as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, or false if it is not legal.\n\nExample 1:\nInput: board = [[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\"W\",\"B\",\"B\",\".\",\"W\",\"W\",\"W\",\"B\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"]], rMove = 4, cMove = 3, color = \"B\"\nOutput: true\nExplanation: '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.\nThe two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.\n\nExample 2:\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"B\",\".\",\".\",\"W\",\".\",\".\",\".\"],[\".\",\".\",\"W\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\"B\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\"B\",\"W\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\"W\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\"B\"]], rMove = 4, cMove = 4, color = \"W\"\nOutput: false\nExplanation: While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.\n\nConstraints:\n- board.length == board[r].length == 8\n- 0 <= rMove, cMove < 8\n- board[rMove][cMove] == '.'\n- color is either 'B' or 'W'."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(8 * n) = O(1), grid is a n x n board and n = 8\n# Space: O(1)\n\nclass Solution(object):\n def checkMove(self, board, rMove, cMove, color):\n \"\"\"\n :type board: List[List[str]]\n :type rMove: int\n :type cMove: int\n :type color: str\n :rtype: bool\n \"\"\"\n def check(board, color, r, c, dr, dc):\n l = 2\n while 0 <= r < len(board) and 0 <= c < len(board[0]) and board[r][c] != '.':\n if board[r][c] == color:\n return l >= 3 \n r += dr\n c += dc\n l += 1\n return False\n\n directions = [(0, -1), (0, 1), (-1, 0), (1, 0),\n (-1, -1), (1, -1), (-1, 1), (1, 1)]\n for dr, dc in directions:\n r, c = rMove+dr, cMove+dc\n if check(board, color, r, c, dr, dc):\n return True\n return False\n"}} diff --git a/cp/cp-11305.jsonl b/cp/cp-11305.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..15cec62c3c1fd87544d8dd3274a627dc21ceabaf --- /dev/null +++ b/cp/cp-11305.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11305", "name": "LeetCode 1959: Minimum Total Space Wasted With K Resizing Operations"} +{"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: Minimum Total Space Wasted With K Resizing Operations (Difficulty: Medium)\nTags: Array, Dynamic Programming\n\nYou are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size).\nThe size of the array at time t, sizet, must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted at time t is defined as sizet - nums[t], and the total space wasted is the sum of the space wasted across every time t where 0 <= t < nums.length.\nReturn the minimum total space wasted if you can resize the array at most k times.\nNote: The array can have any size at the start and does not count towards the number of resizing operations.\n\nExample 1:\nInput: nums = [10,20], k = 0\nOutput: 10\nExplanation: size = [20,20].\nWe can set the initial size to be 20.\nThe total wasted space is (20 - 10) + (20 - 20) = 10.\n\nExample 2:\nInput: nums = [10,20,30], k = 1\nOutput: 10\nExplanation: size = [20,20,30].\nWe can set the initial size to be 20 and resize to 30 at time 2. \nThe total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10.\n\nExample 3:\nInput: nums = [10,20,15,30,20], k = 2\nOutput: 15\nExplanation: size = [10,20,20,30,30].\nWe can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3.\nThe total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15.\n\nConstraints:\n- 1 <= nums.length <= 200\n- 1 <= nums[i] <= 10^6\n- 0 <= k <= nums.length - 1"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(k * n^2)\n# Space: O(k * n)\n\nclass Solution(object):\n def minSpaceWastedKResizing(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n INF = float(\"inf\")\n k += 1\n dp = [[INF]*(k+1) for _ in range(len(nums)+1)]\n dp[0][0] = 0\n for i in range(1, len(nums)+1):\n total = max_num = 0\n for j in reversed(range(1, i+1)):\n total += nums[j-1]\n max_num = max(max_num, nums[j-1])\n for m in range(1, k+1):\n if dp[j-1][m-1] != INF:\n dp[i][m] = min(dp[i][m], dp[j-1][m-1] + (max_num*(i-j+1)-total))\n return dp[-1][-1]\n"}} diff --git a/cp/cp-11306.jsonl b/cp/cp-11306.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cf9f1b9694662723e0f1718bd958dac9a50f085d --- /dev/null +++ b/cp/cp-11306.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11306", "name": "LeetCode 1960: Maximum Product Of The Length Of Two 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: Maximum Product of the Length of Two Palindromic Substrings (Difficulty: Hard)\nTags: String, Rolling Hash, Hash Function\n\nYou are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized.\nMore formally, you want to choose four integers i, j, k, l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive.\nReturn the maximum possible product of the lengths of the two non-intersecting palindromic substrings.\nA palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string.\n\nExample 1:\nInput: s = \"ababbb\"\nOutput: 9\nExplanation: Substrings \"aba\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.\n\nExample 2:\nInput: s = \"zaaaxbbby\"\nOutput: 9\nExplanation: Substrings \"aaa\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.\n\nConstraints:\n- 2 <= s.length <= 10^5\n- s consists of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def maxProduct(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\n P = manacher(s)\n q = collections.deque()\n left = [0]\n for i in range(len(s)):\n while q and q[0][1] < i:\n q.popleft()\n left.append(max(left[-1], 1+2*(i-q[0][0]) if q else 1))\n q.append((i, i+P[2*i+2]//2))\n q = collections.deque()\n result = right = 0\n for i in reversed(range(len(s))):\n while q and q[0][1] > i:\n q.popleft()\n right = max(right, 1+2*(q[0][0]-i) if q else 1)\n q.append((i, i-P[2*i+2]//2))\n result = max(result, left[i]*right)\n return result\n\n\n# Time: O(n)\n# Space: O(n)\nclass Solution2(object):\n def maxProduct(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\n import operator\n def accumulate(iterable, func=operator.add, initial=None):\n it = iter(iterable)\n total = initial\n if initial is None:\n try:\n total = next(it)\n except StopIteration:\n return\n yield total\n for element in it:\n total = func(total, element)\n yield total\n\n def fin_max_len(s):\n P = manacher(s)\n intervals = [[(i-2)//2-P[i]//2, (i-2)//2+P[i]//2] for i in range(2,len(P)-2, 2)]\n dp = [0]*len(s)\n for l, r in reversed(intervals): \n dp[r] = r-l+1\n for i in reversed(range(len(s)-1)):\n dp[i] = max(dp[i], dp[i+1]-2)\n return list(accumulate(dp, max, 0))\n \n l1, l2 = fin_max_len(s), fin_max_len(s[::-1])[::-1]\n return max(x*y for x, y in itertools.izip(l1, l2))\n"}} diff --git a/cp/cp-11307.jsonl b/cp/cp-11307.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3ac5ebe86a8f4167b3a3b8981c5039c0adc8192b --- /dev/null +++ b/cp/cp-11307.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11307", "name": "LeetCode 1961: Check If String Is A Prefix Of 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: Check If String Is a Prefix of Array (Difficulty: Easy)\nTags: Array, Two Pointers, String\n\nGiven a string s and an array of strings words, determine whether s is a prefix string of words.\nA string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length.\nReturn true if s is a prefix string of words, or false otherwise.\n\nExample 1:\nInput: s = \"iloveleetcode\", words = [\"i\",\"love\",\"leetcode\",\"apples\"]\nOutput: true\nExplanation:\ns can be made by concatenating \"i\", \"love\", and \"leetcode\" together.\n\nExample 2:\nInput: s = \"iloveleetcode\", words = [\"apples\",\"i\",\"love\",\"leetcode\"]\nOutput: false\nExplanation:\nIt is impossible to make s using a prefix of arr.\n\nConstraints:\n- 1 <= words.length <= 100\n- 1 <= words[i].length <= 20\n- 1 <= s.length <= 1000\n- words[i] and s consist of only lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def isPrefixString(self, s, words):\n \"\"\"\n :type s: str\n :type words: List[str]\n :rtype: bool\n \"\"\"\n i = j = 0\n for c in s:\n if i == len(words) or words[i][j] != c:\n return False \n j += 1\n if j == len(words[i]):\n i += 1\n j = 0\n return j == 0\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def isPrefixString(self, s, words):\n \"\"\"\n :type s: str\n :type words: List[str]\n :rtype: bool\n \"\"\"\n i = 0\n for word in words:\n for c in word:\n if i == len(s) or s[i] != c:\n return False\n i += 1\n if i == len(s):\n return True\n return False\n"}} diff --git a/cp/cp-11308.jsonl b/cp/cp-11308.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3b3766a47551cb863a3611653599aa2acac4bf6e --- /dev/null +++ b/cp/cp-11308.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11308", "name": "LeetCode 1962: Remove Stones To Minimize The Total"} +{"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: Remove Stones to Minimize the Total (Difficulty: Medium)\nTags: Array, Greedy, Heap (Priority Queue)\n\nYou are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times:\nNotice that you can apply the operation on the same pile more than once.\nReturn the minimum possible total number of stones remaining after applying the k operations.\nfloor(x) is the largest integer that is smaller than or equal to x (i.e., rounds x down).\n\nExample 1:\nInput: piles = [5,4,9], k = 2\nOutput: 12\nExplanation: Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [5,4,5].\n- Apply the operation on pile 0. The resulting piles are [3,4,5].\nThe total number of stones in [3,4,5] is 12.\n\nExample 2:\nInput: piles = [4,3,6,7], k = 3\nOutput: 12\nExplanation: Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [4,3,3,7].\n- Apply the operation on pile 3. The resulting piles are [4,3,3,4].\n- Apply the operation on pile 0. The resulting piles are [2,3,3,4].\nThe total number of stones in [2,3,3,4] is 12.\n\nConstraints:\n- 1 <= piles.length <= 10^5\n- 1 <= piles[i] <= 10^4\n- 1 <= k <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + klogn)\n# Space: O(1)\n\nimport heapq\n\n\nclass Solution(object):\n def minStoneSum(self, piles, k):\n \"\"\"\n :type piles: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n for i, x in enumerate(piles):\n piles[i] = -x\n heapq.heapify(piles)\n for i in range(k):\n heapq.heappush(piles, heapq.heappop(piles)//2)\n return -sum(piles)\n"}} diff --git a/cp/cp-11309.jsonl b/cp/cp-11309.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..45e68e04d5d698dc3c7fd8a4600ced5dc8b4dc41 --- /dev/null +++ b/cp/cp-11309.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11309", "name": "LeetCode 1963: Minimum Number Of Swaps To Make The String Balanced"} +{"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: Minimum Number of Swaps to Make the String Balanced (Difficulty: Medium)\nTags: Two Pointers, String, Stack, Greedy\n\nYou are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.\nA string is called balanced if and only if:\nYou may swap the brackets at any two indices any number of times.\nReturn the minimum number of swaps to make s balanced.\n\nExample 1:\nInput: s = \"][][\"\nOutput: 1\nExplanation: You can make the string balanced by swapping index 0 with index 3.\nThe resulting string is \"[[]]\".\n\nExample 2:\nInput: s = \"]]][[[\"\nOutput: 2\nExplanation: You can do the following to make the string balanced:\n- Swap index 0 with index 4. s = \"[]][][\".\n- Swap index 1 with index 5. s = \"[[][]]\".\nThe resulting string is \"[[][]]\".\n\nExample 3:\nInput: s = \"[]\"\nOutput: 0\nExplanation: The string is already balanced.\n\nConstraints:\n- n == s.length\n- 2 <= n <= 10^6\n- n is even.\n- s[i] is either '[' or ']'.\n- The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minSwaps(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result = curr = 0\n for c in s:\n if c == ']':\n curr += 1\n result = max(result, curr)\n else:\n curr -= 1\n return (result+1)//2\n"}} diff --git a/cp/cp-11310.jsonl b/cp/cp-11310.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c70496d769924dfac9b13e4f19595b6ba757d4c3 --- /dev/null +++ b/cp/cp-11310.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11310", "name": "LeetCode 1964: Find The Longest Valid Obstacle Course At Each Position"} +{"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 the Longest Valid Obstacle Course at Each Position (Difficulty: Hard)\nTags: Array, Binary Search, Binary Indexed Tree\n\nYou want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle.\nFor every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that:\nReturn an array ans of length n, where ans[i] is the length of the longest obstacle course for index i as described above.\n\nExample 1:\nInput: obstacles = [1,2,3,2]\nOutput: [1,2,3,3]\nExplanation: The longest valid obstacle course at each position is:\n- i = 0: [1], [1] has length 1.\n- i = 1: [1,2], [1,2] has length 2.\n- i = 2: [1,2,3], [1,2,3] has length 3.\n- i = 3: [1,2,3,2], [1,2,2] has length 3.\n\nExample 2:\nInput: obstacles = [2,2,1]\nOutput: [1,2,1]\nExplanation: The longest valid obstacle course at each position is:\n- i = 0: [2], [2] has length 1.\n- i = 1: [2,2], [2,2] has length 2.\n- i = 2: [2,2,1], [1] has length 1.\n\nExample 3:\nInput: obstacles = [3,1,5,6,4,2]\nOutput: [1,1,2,3,2,2]\nExplanation: The longest valid obstacle course at each position is:\n- i = 0: [3], [3] has length 1.\n- i = 1: [3,1], [1] has length 1.\n- i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid.\n- i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid.\n- i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid.\n- i = 5: [3,1,5,6,4,2], [1,2] has length 2.\n\nConstraints:\n- n == obstacles.length\n- 1 <= n <= 10^5\n- 1 <= obstacles[i] <= 10^7"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(n)\n\nimport bisect\n\n\n# binary search solution\nclass Solution(object):\n def longestObstacleCourseAtEachPosition(self, obstacles):\n \"\"\"\n :type obstacles: List[int]\n :rtype: List[int]\n \"\"\"\n result, stk = [], []\n for x in obstacles:\n i = bisect.bisect_right(stk, x)\n result.append(i+1)\n if i == len(stk):\n stk.append(0)\n stk[i] = x\n return result\n \n\n# Range Maximum Query\nclass SegmentTree(object): # 0-based index\n def __init__(self, N,\n build_fn=lambda x, y: [y]*(2*x),\n query_fn=lambda x, y: y if x is None else max(x, y), # (lambda x, y: y if x is None else min(x, y))\n update_fn=lambda x, y: y,\n default_val=0):\n self.N = N\n self.H = (N-1).bit_length()\n self.query_fn = query_fn\n self.update_fn = update_fn\n self.default_val = default_val\n self.tree = build_fn(N, default_val)\n self.lazy = [None]*N\n\n def __apply(self, x, val):\n self.tree[x] = self.update_fn(self.tree[x], val)\n if x < self.N:\n self.lazy[x] = self.update_fn(self.lazy[x], val)\n\n def update(self, L, R, h): # Time: O(logN), Space: O(N)\n def pull(x):\n while x > 1:\n x //= 2\n self.tree[x] = self.query_fn(self.tree[x*2], self.tree[x*2+1])\n if self.lazy[x] is not None:\n self.tree[x] = self.update_fn(self.tree[x], self.lazy[x])\n\n L += self.N\n R += self.N\n L0, R0 = L, R\n while L <= R:\n if L & 1: # is right child\n self.__apply(L, h) \n L += 1\n if R & 1 == 0: # is left child\n self.__apply(R, h)\n R -= 1\n L //= 2\n R //= 2\n pull(L0)\n pull(R0)\n\n def query(self, L, R): # Time: O(logN), Space: O(N)\n def push(x):\n n = 2**self.H\n while n != 1:\n y = x // n\n if self.lazy[y] is not None:\n self.__apply(y*2, self.lazy[y])\n self.__apply(y*2 + 1, self.lazy[y])\n self.lazy[y] = None\n n //= 2\n\n result = None\n if L > R:\n return result\n\n L += self.N\n R += self.N\n push(L)\n push(R)\n while L <= R:\n if L & 1: # is right child\n result = self.query_fn(result, self.tree[L])\n L += 1\n if R & 1 == 0: # is left child\n result = self.query_fn(result, self.tree[R])\n R -= 1\n L //= 2\n R //= 2\n return result\n \n def __str__(self):\n showList = []\n for i in range(self.N):\n showList.append(self.query(i, i))\n return \",\".join(map(str, showList))\n\n\n# Time: O(nlogn)\n# Space: O(n)\n# segment tree solution\nclass Solution2_TLE(object):\n def longestObstacleCourseAtEachPosition(self, obstacles):\n \"\"\"\n :type obstacles: List[int]\n :rtype: List[int]\n \"\"\"\n sorted_obstacles = sorted(set(obstacles))\n lookup = {x:i for i, x in enumerate(sorted_obstacles)}\n segment_tree = SegmentTree(len(lookup))\n result = []\n for x in obstacles:\n cnt = segment_tree.query(0, lookup[x])+1\n result.append(cnt)\n segment_tree.update(lookup[x], lookup[x], cnt)\n return result\n"}} diff --git a/cp/cp-11312.jsonl b/cp/cp-11312.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c8bb494aa06ada05177a0032792adfb70ae9f693 --- /dev/null +++ b/cp/cp-11312.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11312", "name": "LeetCode 1967: Number Of Strings That Appear As Substrings In Word"} +{"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 Strings That Appear as Substrings in Word (Difficulty: Easy)\nTags: Array, String\n\nGiven an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word.\nA substring is a contiguous sequence of characters within a string.\n\nExample 1:\nInput: patterns = [\"a\",\"abc\",\"bc\",\"d\"], word = \"abc\"\nOutput: 3\nExplanation:\n- \"a\" appears as a substring in \"abc\".\n- \"abc\" appears as a substring in \"abc\".\n- \"bc\" appears as a substring in \"abc\".\n- \"d\" does not appear as a substring in \"abc\".\n3 of the strings in patterns appear as a substring in word.\n\nExample 2:\nInput: patterns = [\"a\",\"b\",\"c\"], word = \"aaaaabbbbb\"\nOutput: 2\nExplanation:\n- \"a\" appears as a substring in \"aaaaabbbbb\".\n- \"b\" appears as a substring in \"aaaaabbbbb\".\n- \"c\" does not appear as a substring in \"aaaaabbbbb\".\n2 of the strings in patterns appear as a substring in word.\n\nExample 3:\nInput: patterns = [\"a\",\"a\",\"a\"], word = \"ab\"\nOutput: 3\nExplanation: Each of the patterns appears as a substring in word \"ab\".\n\nConstraints:\n- 1 <= patterns.length <= 100\n- 1 <= patterns[i].length <= 100\n- 1 <= word.length <= 100\n- patterns[i] and word consist of lowercase English letters."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * l + m), n is the number of patterns\n# , l is the max length of patterns\n# , m is the length of word \n# Space: O(t) , t is the total size of ac automata trie\n\nimport collections\n\n\nclass AhoNode(object):\n def __init__(self):\n self.children = collections.defaultdict(AhoNode)\n self.indices = []\n self.suffix = None\n self.output = None\n\n\nclass AhoTrie(object):\n def step(self, letter):\n while self.__node and letter not in self.__node.children:\n self.__node = self.__node.suffix\n self.__node = self.__node.children[letter] if self.__node else self.__root\n return self.__get_ac_node_outputs(self.__node)\n \n def __init__(self, patterns):\n self.__root = self.__create_ac_trie(patterns)\n self.__node = self.__create_ac_suffix_and_output_links(self.__root)\n self.__lookup = set() # modified\n \n def __create_ac_trie(self, patterns): # Time: O(n * l), Space: O(t)\n root = AhoNode()\n for i, pattern in enumerate(patterns):\n node = root\n for c in pattern:\n node = node.children[c]\n node.indices.append(i)\n return root\n\n def __create_ac_suffix_and_output_links(self, root): # Time: O(n * l), Space: O(t)\n queue = collections.deque()\n for node in root.children.itervalues():\n queue.append(node)\n node.suffix = root\n\n while queue:\n node = queue.popleft()\n for c, child in node.children.iteritems():\n queue.append(child)\n suffix = node.suffix\n while suffix and c not in suffix.children:\n suffix = suffix.suffix\n child.suffix = suffix.children[c] if suffix else root\n child.output = child.suffix if child.suffix.indices else child.suffix.output\n \n return root\n\n def __get_ac_node_outputs(self, node): # Total Time: O(n), modified\n result = []\n if node not in self.__lookup: # modified\n self.__lookup.add(node) # modified\n for i in node.indices:\n result.append(i)\n output = node.output\n while output and output not in self.__lookup: # modified\n self.__lookup.add(output) # modified\n for i in output.indices:\n result.append(i)\n output = output.output\n return result\n\n\n# ac automata solution\nclass Solution(object):\n def numOfStrings(self, patterns, word):\n \"\"\"\n :type patterns: List[str]\n :type word: str\n :rtype: int\n \"\"\"\n trie = AhoTrie(patterns)\n return sum(len(trie.step(c)) for c in word)\n\n\n# Time: O(n * (l + m)), n is the number of patterns\n# , l is the max length of patterns\n# , m is the length of word\n# Space: O(l)\n# kmp solution\nclass Solution2(object):\n def numOfStrings(self, patterns, word):\n \"\"\"\n :type patterns: List[str]\n :type word: str\n :rtype: int\n \"\"\"\n def getPrefix(pattern):\n prefix = [-1]*len(pattern)\n j = -1\n for i in range(1, len(pattern)):\n while j != -1 and pattern[j+1] != pattern[i]:\n j = prefix[j]\n if pattern[j+1] == pattern[i]:\n j += 1\n prefix[i] = j\n return prefix\n \n def kmp(text, pattern):\n if not pattern:\n return 0\n prefix = getPrefix(pattern)\n if len(text) < len(pattern):\n return -1\n j = -1\n for i in range(len(text)):\n while j != -1 and pattern[j+1] != text[i]:\n j = prefix[j]\n if pattern[j+1] == text[i]:\n j += 1\n if j+1 == len(pattern):\n return i-j\n return -1\n \n return sum(kmp(word, pattern) != -1 for pattern in patterns)\n\n\n# Time: O(n * m * l), n is the number of patterns\n# , l is the max length of patterns\n# , m is the length of word\n# Space: O(1)\n# built-in solution\nclass Solution3(object):\n def numOfStrings(self, patterns, word):\n return sum(pattern in word for pattern in patterns)\n"}} diff --git a/cp/cp-11313.jsonl b/cp/cp-11313.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7d9bacdb6cb2f71a90370dc2e34ba9fe3f207761 --- /dev/null +++ b/cp/cp-11313.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11313", "name": "LeetCode 1968: Array With Elements Not Equal To Average Of Neighbors"} +{"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: Array With Elements Not Equal to Average of Neighbors (Difficulty: Medium)\nTags: Array, Greedy, Sorting\n\nYou are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.\nMore formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i].\nReturn any rearrangement of nums that meets the requirements.\n\nExample 1:\nInput: nums = [1,2,3,4,5]\nOutput: [1,2,4,5,3]\nExplanation:\nWhen i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.\nWhen i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.\nWhen i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.\n\nExample 2:\nInput: nums = [6,2,0,9,7]\nOutput: [9,7,6,2,0]\nExplanation:\nWhen i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.\nWhen i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.\nWhen i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.\nNote that the original array [6,2,0,9,7] also satisfies the conditions.\n\nConstraints:\n- 3 <= nums.length <= 10^5\n- 0 <= nums[i] <= 10^5"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n) ~ O(n^2), O(n) on average\n# Space: O(1)\n\n# Tri Partition (aka Dutch National Flag Problem) with virtual index solution\nclass Solution(object):\n def rearrangeArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n def nth_element(nums, n, compare=lambda a, b: a < b):\n def tri_partition(nums, left, right, target, compare):\n mid = left\n while mid <= right:\n if nums[mid] == target:\n mid += 1\n elif compare(nums[mid], target):\n nums[left], nums[mid] = nums[mid], nums[left]\n left += 1\n mid += 1\n else:\n nums[mid], nums[right] = nums[right], nums[mid]\n right -= 1\n return left, right\n\n left, right = 0, len(nums)-1\n while left <= right:\n pivot_idx = randint(left, right)\n pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)\n if pivot_left <= n <= pivot_right:\n return\n elif pivot_left > n:\n right = pivot_left-1\n else: # pivot_right < n.\n left = pivot_right+1\n\n def reversedTriPartitionWithVI(nums, val):\n def idx(i, N):\n return (1 + 2 * (i)) % N\n\n N = len(nums)//2 * 2 + 1\n i, j, n = 0, 0, len(nums) - 1\n while j <= n:\n if nums[idx(j, N)] > val:\n nums[idx(i, N)], nums[idx(j, N)] = nums[idx(j, N)], nums[idx(i, N)]\n i += 1\n j += 1\n elif nums[idx(j, N)] < val:\n nums[idx(j, N)], nums[idx(n, N)] = nums[idx(n, N)], nums[idx(j, N)]\n n -= 1\n else:\n j += 1\n\n mid = (len(nums)-1)//2\n nth_element(nums, mid)\n reversedTriPartitionWithVI(nums, nums[mid])\n return nums\n\n\n# Time: O(nlogn)\n# Space: O(n)\n# Sorting and reorder solution\nclass Solution2(object):\n def rearrangeArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n nums.sort()\n mid = (len(nums)-1)//2\n nums[::2], nums[1::2] = nums[mid::-1], nums[:mid:-1]\n return nums\n"}} diff --git a/cp/cp-11314.jsonl b/cp/cp-11314.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd2e28a25895b7f87b565cc848bdd797ab5c3bdd --- /dev/null +++ b/cp/cp-11314.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11314", "name": "LeetCode 1969: Minimum Non Zero Product Of The Array 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: Minimum Non-Zero Product of the Array Elements (Difficulty: Medium)\nTags: Math, Greedy, Recursion\n\nYou are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed to do the following operation any number of times:\nFor example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have x = 1111 and y = 0001.\nFind the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 109 + 7.\nNote: The answer should be the minimum product before the modulo operation is done.\n\nExample 1:\nInput: p = 1\nOutput: 1\nExplanation: nums = [1].\nThere is only one element, so the product equals that element.\n\nExample 2:\nInput: p = 2\nOutput: 6\nExplanation: nums = [01, 10, 11].\nAny swap would either make the product 0 or stay the same.\nThus, the array product of 1 * 2 * 3 = 6 is already minimized.\n\nExample 3:\nInput: p = 3\nOutput: 1512\nExplanation: nums = [001, 010, 011, 100, 101, 110, 111]\n- In the first operation we can swap the leftmost bit of the second and fifth elements.\n - The resulting array is [001, 110, 011, 100, 001, 110, 111].\n- In the second operation we can swap the middle bit of the third and fourth elements.\n - The resulting array is [001, 110, 001, 110, 001, 110, 111].\nThe array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.\n\nConstraints:\n- 1 <= p <= 60"}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(min(p, logM))\n# Space: O(1)\n\nclass Solution(object):\n def minNonZeroProduct(self, p):\n \"\"\"\n :type p: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n\n # max_num = 2^p-1\n max_num_mod = (pow(2, p, MOD)-1)%MOD # max_num % MOD\n\n # pair_product = max_num-1\n pair_product_mod = (max_num_mod-1)%MOD # (max_num_mod-1) % MOD\n\n # since pair_product^MOD % MOD = pair_product_mod^MOD % MOD = pair_product_mod\n # => pair_product_mod^(MOD-1) % MOD = 1\n # => pair_product_mod^(pair_cnt) % MOD = pair_product_mod^(pair_cnt%(MOD-1)) %MOD\n pair_cnt_mod_m_1 = (pow(2, p-1, MOD-1)-1) % (MOD-1) # pair_cnt%(MOD-1)\n\n # the ans is:\n # max_num * pair_product^pair_cnt % MOD\n # = max_num_mod * pair_product_mod^(pair_cnt_mod_m_1) % MOD\n return (max_num_mod*pow(pair_product_mod, pair_cnt_mod_m_1, MOD)) % MOD\n"}} diff --git a/cp/cp-11315.jsonl b/cp/cp-11315.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a67d02aeb98283de4159592967351f1c98cd6e3b --- /dev/null +++ b/cp/cp-11315.jsonl @@ -0,0 +1,4 @@ +{"type": "session", "harness": "opencode", "id": "cp-11315", "name": "LeetCode 1970: Last Day Where You Can Still Cross"} +{"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: Last Day Where You Can Still Cross (Difficulty: Hard)\nTags: Array, Binary Search, Depth-First Search, Breadth-First Search, Union Find, Matrix\n\nThere is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively.\nInitially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1).\nYou want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down).\nReturn the last day where it is possible to walk from the top to the bottom by only walking on land cells.\n\nExample 1:\nInput: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]\nOutput: 2\nExplanation: The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 2.\n\nExample 2:\nInput: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]\nOutput: 1\nExplanation: The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 1.\n\nExample 3:\nInput: row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]\nOutput: 3\nExplanation: The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 3.\n\nConstraints:\n- 2 <= row, col <= 2 * 10^4\n- 4 <= row * col <= 2 * 10^4\n- cells.length == row * col\n- 1 <= ri <= row\n- 1 <= ci <= col\n- All the values of cells are unique."}} +{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n + c * α(c)) = O(m * n)\n# Space: O(m * n)\n\nclass UnionFind(object): # Time: O(n * α(n)), Space: O(n)\n def __init__(self, n):\n self.set = range(n)\n self.rank = [0]*n\n\n def find_set(self, x):\n stk = []\n while self.set[x] != x: # path compression\n stk.append(x)\n x = self.set[x]\n while stk:\n self.set[stk.pop()] = x\n return x\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root == y_root:\n return False\n if self.rank[x_root] < self.rank[y_root]: # union by rank\n self.set[x_root] = y_root\n elif self.rank[x_root] > self.rank[y_root]:\n self.set[y_root] = x_root\n else:\n self.set[y_root] = x_root\n self.rank[x_root] += 1\n return True\n\n\nclass Solution(object):\n def latestDayToCross(self, row, col, cells):\n \"\"\"\n :type row: int\n :type col: int\n :type cells: List[List[int]]\n :rtype: int\n \"\"\"\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n def index(n, i, j):\n return i*n+j\n\n start, end = row*col, row*col+1\n uf = UnionFind(row*col+2)\n lookup = [[False]*col for _ in range(row)]\n for i in reversed(range(len(cells))):\n r, c = cells[i]\n r, c = r-1, c-1\n for dr, dc in directions:\n nr, nc = r+dr, c+dc\n if not (0 <= nr < row and 0 <= nc < col and lookup[nr][nc]):\n continue\n uf.union_set(index(col, r, c), index(col, nr, nc))\n if r == 0:\n uf.union_set(start, index(col, r, c))\n if r == row-1:\n uf.union_set(end, index(col, r, c))\n if uf.find_set(start) == uf.find_set(end):\n return i\n lookup[r][c] = True\n return -1\n"}}