Upload folder using huggingface_hub (part 14)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- cp/cp-11316.jsonlAdded+4
- cp/cp-11318.jsonlAdded+4
- cp/cp-11319.jsonlAdded+4
- cp/cp-11320.jsonlAdded+4
- cp/cp-11321.jsonlAdded+4
- cp/cp-11323.jsonlAdded+4
- cp/cp-11324.jsonlAdded+4
- cp/cp-11325.jsonlAdded+4
- cp/cp-11328.jsonlAdded+4
- cp/cp-11329.jsonlAdded+4
- cp/cp-11330.jsonlAdded+4
- cp/cp-11332.jsonlAdded+4
- cp/cp-11333.jsonlAdded+4
- cp/cp-11334.jsonlAdded+4
- cp/cp-11335.jsonlAdded+4
- cp/cp-11336.jsonlAdded+4
- cp/cp-11337.jsonlAdded+4
- cp/cp-11338.jsonlAdded+4
- cp/cp-11339.jsonlAdded+4
- cp/cp-11342.jsonlAdded+4
- cp/cp-11343.jsonlAdded+4
- cp/cp-11344.jsonlAdded+4
- cp/cp-11346.jsonlAdded+4
- cp/cp-11347.jsonlAdded+4
- cp/cp-11348.jsonlAdded+4
- cp/cp-11349.jsonlAdded+4
- cp/cp-11351.jsonlAdded+4
- cp/cp-11352.jsonlAdded+4
- cp/cp-11353.jsonlAdded+4
- cp/cp-11355.jsonlAdded+4
- cp/cp-11356.jsonlAdded+4
- cp/cp-11357.jsonlAdded+4
- cp/cp-11358.jsonlAdded+4
- cp/cp-11360.jsonlAdded+4
- cp/cp-11361.jsonlAdded+4
- cp/cp-11362.jsonlAdded+4
- cp/cp-11363.jsonlAdded+4
- cp/cp-11364.jsonlAdded+4
- cp/cp-11365.jsonlAdded+4
- cp/cp-11366.jsonlAdded+4
- cp/cp-11367.jsonlAdded+4
- cp/cp-11369.jsonlAdded+4
- cp/cp-11370.jsonlAdded+4
- cp/cp-11371.jsonlAdded+4
- cp/cp-11372.jsonlAdded+4
- cp/cp-11374.jsonlAdded+4
- cp/cp-11375.jsonlAdded+4
- cp/cp-11376.jsonlAdded+4
- cp/cp-11377.jsonlAdded+4
- cp/cp-11378.jsonlAdded+4
1234{"type": "session", "harness": "opencode", "id": "cp-11316", "name": "LeetCode 1971: Find If Path Exists In 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: Find if Path Exists in Graph (Difficulty: Easy)\nTags: Depth-First Search, Breadth-First Search, Union Find, Graph\n\nThere is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.\nYou want to determine if there is a valid path that exists from vertex source to vertex destination.\nGiven edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.\n\nExample 1:\nInput: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2\nOutput: true\nExplanation: There are two paths from vertex 0 to vertex 2:\n- 0 → 1 → 2\n- 0 → 2\n\nExample 2:\nInput: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5\nOutput: false\nExplanation: There is no path from vertex 0 to vertex 5.\n\nConstraints:\n- 1 <= n <= 2 * 10^5\n- 0 <= edges.length <= 2 * 10^5\n- edges[i].length == 2\n- 0 <= ui, vi <= n - 1\n- ui != vi\n- 0 <= source, destination <= n - 1\n- There are no duplicate edges.\n- There are no self edges."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(|V| + |E|)\n# Space: O(|V| + |E|)\n\nimport collections\n\n\n# bi-bfs solution\nclass Solution(object):\n def validPath(self, n, edges, start, end):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type start: int\n :type end: int\n :rtype: bool\n \"\"\"\n def bi_bfs(adj, start, target):\n left, right = {start}, {target}\n lookup = set()\n steps = 0\n while left:\n for pos in left:\n lookup.add(pos)\n new_left = set()\n for pos in left:\n if pos in right: \n return steps\n for nei in adj[pos]:\n if nei in lookup:\n continue\n new_left.add(nei)\n left = new_left\n steps += 1\n if len(left) > len(right): \n left, right = right, left\n return -1\n\n adj = collections.defaultdict(list)\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n return bi_bfs(adj, start, end) >= 0\n\n\n# Time: O(|V| + |E|)\n# Space: O(|V| + |E|)\n# bfs solution\nclass Solution2(object):\n def validPath(self, n, edges, start, end):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type start: int\n :type end: int\n :rtype: bool\n \"\"\"\n def bfs(adj, start, target):\n q = [start]\n lookup = set(q)\n steps = 0\n while q:\n new_q = []\n for pos in q:\n if pos == target:\n return steps\n for nei in adj[pos]:\n if nei in lookup:\n continue\n lookup.add(nei)\n new_q.append(nei)\n q = new_q\n steps += 1\n return -1 \n\n adj = collections.defaultdict(list)\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n return bfs(adj, start, end) >= 0\n\n\n# Time: O(|V| + |E|)\n# Space: O(|V| + |E|)\n# dfs solution\nclass Solution3(object):\n def validPath(self, n, edges, start, end):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type start: int\n :type end: int\n :rtype: bool\n \"\"\"\n def dfs(adj, start, target):\n stk = [start]\n lookup = set(stk)\n while stk:\n pos = stk.pop()\n if pos == target:\n return True\n for nei in reversed(adj[pos]):\n if nei in lookup:\n continue\n lookup.add(nei)\n stk.append(nei)\n return False \n\n adj = collections.defaultdict(list)\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n return dfs(adj, start, end)\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11318", "name": "LeetCode 1974: Minimum Time To Type Word Using Special Typewriter"}{"type": "message", "message": {"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 Type Word Using Special Typewriter (Difficulty: Easy)\nTags: String, Greedy\n\nThere is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.\nEach second, you may perform one of the following operations:\nGiven a string word, return the minimum number of seconds to type out the characters in word.\n\nExample 1:\nInput: word = \"abc\"\nOutput: 5\nExplanation: \nThe characters are printed as follows:\n- Type the character 'a' in 1 second since the pointer is initially on 'a'.\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer clockwise to 'c' in 1 second.\n- Type the character 'c' in 1 second.\n\nExample 2:\nInput: word = \"bza\"\nOutput: 7\nExplanation:\nThe characters are printed as follows:\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer counterclockwise to 'z' in 2 seconds.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'a' in 1 second.\n- Type the character 'a' in 1 second.\n\nExample 3:\nInput: word = \"zjpc\"\nOutput: 34\nExplanation:\nThe characters are printed as follows:\n- Move the pointer counterclockwise to 'z' in 1 second.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'j' in 10 seconds.\n- Type the character 'j' in 1 second.\n- Move the pointer clockwise to 'p' in 6 seconds.\n- Type the character 'p' in 1 second.\n- Move the pointer counterclockwise to 'c' in 13 seconds.\n- Type the character 'c' in 1 second.\n\nConstraints:\n- 1 <= word.length <= 100\n- word consists of lowercase English letters."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space; O(1)\n\nclass Solution(object):\n def minTimeToType(self, word):\n \"\"\"\n :type word: str\n :rtype: int\n \"\"\"\n return (min((ord(word[0])-ord('a'))%26, (ord('a')-ord(word[0]))%26)+1) + \\\n sum(min((ord(word[i])-ord(word[i-1]))%26, (ord(word[i-1])-ord(word[i]))%26)+1\n for i in range(1, len(word)))\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11319", "name": "LeetCode 1975: Maximum Matrix 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 Matrix Sum (Difficulty: Medium)\nTags: Array, Greedy, Matrix\n\nYou are given an n x n integer matrix. You can do the following operation any number of times:\nTwo elements are considered adjacent if and only if they share a border.\nYour goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.\n\nExample 1:\nInput: matrix = [[1,-1],[-1,1]]\nOutput: 4\nExplanation: We can follow the following steps to reach sum equals 4:\n- Multiply the 2 elements in the first row by -1.\n- Multiply the 2 elements in the first column by -1.\n\nExample 2:\nInput: matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]\nOutput: 16\nExplanation: We can follow the following step to reach sum equals 16:\n- Multiply the 2 last elements in the second row by -1.\n\nConstraints:\n- n == matrix.length == matrix[i].length\n- 2 <= n <= 250\n- -10^5 <= matrix[i][j] <= 10^5"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(1)\n\nclass Solution(object):\n def maxMatrixSum(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: int\n \"\"\"\n abs_total = sum(abs(x) for row in matrix for x in row)\n min_abs_val = min(abs(x) for row in matrix for x in row)\n neg_cnt = sum(x < 0 for row in matrix for x in row)\n return abs_total if neg_cnt%2 == 0 else abs_total - 2*min_abs_val\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11320", "name": "LeetCode 1976: Number Of Ways To Arrive At Destination"}{"type": "message", "message": {"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 Arrive at Destination (Difficulty: Medium)\nTags: Dynamic Programming, Graph, Topological Sort, Shortest Path\n\nYou are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.\nYou are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time.\nReturn the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7.\n\nExample 1:\nInput: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]\nOutput: 4\nExplanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.\nThe four ways to get there in 7 minutes are:\n- 0 ➝ 6\n- 0 ➝ 4 ➝ 6\n- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6\n- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6\n\nExample 2:\nInput: n = 2, roads = [[1,0,10]]\nOutput: 1\nExplanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.\n\nConstraints:\n- 1 <= n <= 200\n- n - 1 <= roads.length <= n * (n - 1) / 2\n- roads[i].length == 3\n- 0 <= ui, vi <= n - 1\n- 1 <= timei <= 10^9\n- ui != vi\n- There is at most one road connecting any two intersections.\n- You can reach any intersection from any other intersection."}}{"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 heapq\n\n\nclass Solution(object):\n def countPaths(self, n, roads):\n \"\"\"\n :type n: int\n :type roads: List[List[int]]\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n\n def dijkstra(adj, start, target):\n best = collections.defaultdict(lambda:float(\"inf\"))\n best[start] = 0\n min_heap = [(0, start)]\n dp = [0]*(len(adj)) # modified, add dp to keep number of ways\n dp[0] = 1\n while min_heap:\n curr, u = heapq.heappop(min_heap)\n if best[u] < curr:\n continue\n if u == target: # modified, early return\n break\n for v, w in adj[u]: \n if v in best and best[v] <= curr+w:\n if best[v] == curr+w: # modified, update number of ways in this minimal time\n dp[v] = (dp[v]+dp[u])%MOD\n continue\n dp[v] = dp[u] # modified, init number of ways in this minimal time\n best[v] = curr+w\n heapq.heappush(min_heap, (curr+w, v))\n return dp[target]\n\n adj = [[] for i in range(n)]\n for u, v, w in roads:\n adj[u].append((v, w))\n adj[v].append((u, w))\n return dijkstra(adj, 0, n-1)\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11321", "name": "LeetCode 1977: Number Of Ways To Separate 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 to Separate Numbers (Difficulty: Hard)\nTags: String, Dynamic Programming, Suffix Array\n\nYou wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros.\nReturn the number of possible lists of integers that you could have written down to get the string num. Since the answer may be large, return it modulo 109 + 7.\n\nExample 1:\nInput: num = \"327\"\nOutput: 2\nExplanation: You could have written down the numbers:\n3, 27\n327\n\nExample 2:\nInput: num = \"094\"\nOutput: 0\nExplanation: No numbers can have leading zeros and all numbers must be positive.\n\nExample 3:\nInput: num = \"0\"\nOutput: 0\nExplanation: No numbers can have leading zeros and all numbers must be positive.\n\nConstraints:\n- 1 <= num.length <= 3500\n- num consists of digits '0' through '9'."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^2)\n# Space: O(n^2)\n\nclass Solution(object):\n def numberOfCombinations(self, num):\n \"\"\"\n :type num: str\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n def find_longest_common_prefix(num):\n lcp = [[0]*(len(num)+1) for _ in range(len(num)+1)] # lcp[i][j]: longest length of the common prefix which starts at num[i], num[j]\n for i in reversed(range(len(lcp)-1)):\n for j in reversed(range(len(lcp[0])-1)):\n if num[i] == num[j]:\n lcp[i][j] = lcp[i+1][j+1]+1\n return lcp\n\n def is_less_or_equal_to_with_same_length(num, lcp, i, j, l):\n return lcp[i][j] >= l or num[i+lcp[i][j]] < num[j+lcp[i][j]]\n\n lcp = find_longest_common_prefix(num)\n dp = [[0]*len(num) for _ in range(len(num))] # dp[i][l]: the count of numbers ending at num[i], where the length of the last number is l+1\n dp[0][0] = int(num[0] != '0')\n for i in range(1, len(num)):\n dp[i][i] = dp[i-1][i-1]\n if num[i] == '0':\n continue\n accu = 0\n for l in range(len(num)-i+1):\n ni = i+l-1\n dp[ni][l-1] = accu # accumulated count where the length of the second to last number ending at num[i-1] is shorter than the length of the last number ending at num[i+l-1]\n if i-l < 0:\n continue\n if num[i-l] != '0' and is_less_or_equal_to_with_same_length(num, lcp, i-l, i, l):\n dp[ni][l-1] = (dp[ni][l-1] + dp[i-1][l-1]) % MOD\n accu = (accu + dp[i-1][l-1]) % MOD\n return reduce(lambda total, x: (total+x)%MOD, dp[-1], 0)\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11323", "name": "LeetCode 1980: Find Unique 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 Unique Binary String (Difficulty: Medium)\nTags: Array, Hash Table, String, Backtracking\n\nGiven an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.\n\nExample 1:\nInput: nums = [\"01\",\"10\"]\nOutput: \"11\"\nExplanation: \"11\" does not appear in nums. \"00\" would also be correct.\n\nExample 2:\nInput: nums = [\"00\",\"01\"]\nOutput: \"11\"\nExplanation: \"11\" does not appear in nums. \"10\" would also be correct.\n\nExample 3:\nInput: nums = [\"111\",\"011\",\"001\"]\nOutput: \"101\"\nExplanation: \"101\" does not appear in nums. \"000\", \"010\", \"100\", and \"110\" would also be correct.\n\nConstraints:\n- n == nums.length\n- 1 <= n <= 16\n- nums[i].length == n\n- nums[i] is either '0' or '1'.\n- All the strings of nums are unique."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def findDifferentBinaryString(self, nums):\n \"\"\"\n :type nums: List[str]\n :rtype: str\n \"\"\"\n return \"\".join(\"01\"[nums[i][i] == '0'] for i in range(len(nums)))\n\n\n# Time: O(k * n) = O(n^2), k is len(nums)\n# , n is len(nums[0])\n# Space: O(k) = O(n)\nclass Solution2(object):\n def findDifferentBinaryString(self, nums):\n \"\"\"\n :type nums: List[str]\n :rtype: str\n \"\"\"\n lookup = set(map(lambda x: int(x, 2), nums)) # Time: O(k * n) = O(n^2)\n return next(bin(i)[2:].zfill(len(nums[0])) for i in range(2**len(nums[0])) if i not in lookup) # Time: O(k + n) = O(n)\n\n\n# Time: O(k * n + n * 2^n) = O(n * 2^n), k is len(nums)\n# , n is len(nums[0])\n# Space: O(k) = O(1) ~ O(2^n)\nclass Solution_Extra(object):\n def findAllDifferentBinaryStrings(self, nums):\n \"\"\"\n :type nums: List[str]\n :rtype: List[str]\n \"\"\"\n lookup = set(map(lambda x: int(x, 2), nums)) # Time: O(k * n) = O(n * 2^n)\n return [bin(i)[2:].zfill(len(nums[0])) for i in range(2**len(nums[0])) if i not in lookup] # Time: O(2^n + n * (2^n - k))\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11324", "name": "LeetCode 1981: Minimize The Difference Between Target And Chosen 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: Minimize the Difference Between Target and Chosen Elements (Difficulty: Medium)\nTags: Array, Dynamic Programming, Matrix\n\nYou are given an m x n integer matrix mat and an integer target.\nChoose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized.\nReturn the minimum absolute difference.\nThe absolute difference between two numbers a and b is the absolute value of a - b.\n\nExample 1:\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13\nOutput: 0\nExplanation: One possible choice is to:\n- Choose 1 from the first row.\n- Choose 5 from the second row.\n- Choose 7 from the third row.\nThe sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.\n\nExample 2:\nInput: mat = [[1],[2],[3]], target = 100\nOutput: 94\nExplanation: The best possible choice is to:\n- Choose 1 from the first row.\n- Choose 2 from the second row.\n- Choose 3 from the third row.\nThe sum of the chosen elements is 6, and the absolute difference is 94.\n\nExample 3:\nInput: mat = [[1,2,9,8,7]], target = 6\nOutput: 1\nExplanation: The best choice is to choose 7 from the first row.\nThe absolute difference is 1.\n\nConstraints:\n- m == mat.length\n- n == mat[i].length\n- 1 <= m, n <= 70\n- 1 <= mat[i][j] <= 70\n- 1 <= target <= 800"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(t * m * n), t is target\n# Space: O(t)\n\nclass Solution(object):\n def minimizeTheDifference(self, mat, target):\n \"\"\"\n :type mat: List[List[int]]\n :type target: int\n :rtype: int\n \"\"\"\n chosen_min = sum(min(row) for row in mat)\n if chosen_min >= target:\n return chosen_min-target\n dp = {0}\n for row in mat:\n dp = {total+x for total in dp for x in row if (total+x)-target < target-chosen_min}\n return min(abs(target-total) for total in dp)\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11325", "name": "LeetCode 1982: Find Array Given Subset 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 Array Given Subset Sums (Difficulty: Hard)\nTags: Array, Divide and Conquer\n\nYou are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2n subset sums of the unknown array (in no particular order).\nReturn the array ans of length n representing the unknown array. If multiple answers exist, return any of them.\nAn array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0.\nNote: Test cases are generated such that there will always be at least one correct answer.\n\nExample 1:\nInput: n = 3, sums = [-3,-2,-1,0,0,1,2,3]\nOutput: [1,2,-3]\nExplanation: [1,2,-3] is able to achieve the given subset sums:\n- []: sum is 0\n- [1]: sum is 1\n- [2]: sum is 2\n- [1,2]: sum is 3\n- [-3]: sum is -3\n- [1,-3]: sum is -2\n- [2,-3]: sum is -1\n- [1,2,-3]: sum is 0\nNote that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.\n\nExample 2:\nInput: n = 2, sums = [0,0,0,0]\nOutput: [0,0]\nExplanation: The only correct answer is [0,0].\n\nExample 3:\nInput: n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]\nOutput: [0,-1,4,5]\nExplanation: [0,-1,4,5] is able to achieve the given subset sums.\n\nConstraints:\n- 1 <= n <= 15\n- sums.length == 2n\n- -10^4 <= sums[i] <= 10^4"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * 2^n), len(sums) = 2^n\n# Space: O(1)\n\n# [proof]\n# - let d = sorted_sums[0]-sorted_sums[1] and d != -d (d = 0 is trival), where one of +d/-d is the smallest positive or largest negative number of the original solution of [S1, ..., S(2^n)]\n# - given Sp-d = 0 for some p in [1, 2^n] and Sq-(-d) = 0 for some q in [1, 2^n]\n# assume d is a number of the original solution of [S1, ..., S(2^n)] (the proof where -d is a number of the original solution is vice versa)\n# let Sq = x1+...+xi where 1 <= i <= n-1\n# let [d]+[x1, ..., xi]+[x(i+1), ..., x(n-1)] be the original solution\n# => new_sums([S1, ..., S(2^n)], d)\n# = subset_sums([x1, ..., xi]+[x(i+1), ..., x(n-1)])\n# if we choose -d as a number of a solution of [S1, ..., S(2^n)]\n# => new_sums([S1, ..., S(2^n)], -d)\n# = new_sums([S1, ..., S(2^n)], -(x1+...+xi))\n# = subset_sums([(-x1), ..., (-xi)]+[x(i+1), ..., x(n-1)])\n# => [-d]+[(-x1), ..., (-xi)]+[x(i+1), ..., x(n-1)] is also a solution\n#\n# [conclusion]\n# - if new_sums with +d/-d (including d = 0) both contain zero, we can choose either one\n# - if only one of new_sums with +d/-d contains zero, we can only choose the one with zero since subset_sums must contain zero\n\n# optimized from solution4 (not using dict), runtime: 1040 ms\nclass Solution(object):\n def recoverArray(self, n, sums):\n \"\"\"\n :type n: int\n :type sums: List[int]\n :rtype: List[int]\n \"\"\"\n sums.sort() # Time: O(2^n * log(2^n)) = O(n * 2^n)\n shift, l = 0, len(sums)\n result = []\n for _ in range(n): # log(2^n) times, each time costs O(2^(n-len(result))), Total Time: O(2^n)\n new_shift = sums[0]-sums[1]\n assert(new_shift <= 0)\n has_zero, j, k = False, 0, 0\n for i in range(l):\n if k < j and sums[k] == sums[i]: # skip shifted one\n k += 1\n else:\n if shift == sums[i]-new_shift:\n has_zero = True\n sums[j] = sums[i]-new_shift\n j += 1\n if has_zero: # contain 0, choose this side\n result.append(new_shift)\n else: # contain no 0, choose another side and shift 0 offset\n result.append(-new_shift)\n shift -= new_shift\n l //= 2\n return result\n\n\n# Time: O(2^n + n * r), len(sums) = 2^n\n# , r = max(sums)-min(sums)\n# Space: O(2^n + r)\nimport collections\n\n\n# optimized from solution4 (not using dict), runtime: 968 ms\nclass Solution2(object):\n def recoverArray(self, n, sums):\n \"\"\"\n :type n: int\n :type sums: List[int]\n :rtype: List[int]\n \"\"\"\n min_sum, max_sum = min(sums), max(sums)\n dp = [0]*(max_sum-min_sum+1)\n for x in sums:\n dp[x-min_sum] += 1\n sorted_sums = [x for x in range(min_sum, max_sum+1) if dp[x-min_sum]] # Time: O(r)\n shift = 0\n result = []\n for _ in range(n): # log(2^n) times, each time costs O(2^(n-len(result)))+O(r), Total Time: O(2^n + n * r)\n new_dp = [0]*(max_sum-min_sum+1)\n new_sorted_sums = []\n new_shift = sorted_sums[0]-sorted_sums[1] if dp[sorted_sums[0]-min_sum] == 1 else 0\n assert(new_shift <= 0)\n for x in sorted_sums:\n if not dp[x-min_sum]:\n continue\n dp[(x-new_shift)-min_sum] -= dp[x-min_sum] if new_shift else dp[x-min_sum]//2\n new_dp[(x-new_shift)-min_sum] = dp[x-min_sum]\n new_sorted_sums.append(x-new_shift)\n dp = new_dp\n sorted_sums = new_sorted_sums\n if dp[shift-min_sum]: # contain 0, choose this side\n result.append(new_shift)\n else: # contain no 0, choose another side and shift 0 offset\n result.append(-new_shift)\n shift -= new_shift\n return result\n\n\n# Time: O(n * 2^n), len(sums) = 2^n\n# Space: O(2^n)\nimport collections\nimport operator\n\n\n# optimized from solution4, runtime: 1044 ms\nclass Solution3(object):\n def recoverArray(self, n, sums):\n \"\"\"\n :type n: int\n :type sums: List[int]\n :rtype: List[int]\n \"\"\"\n dp = {k: v for k, v in collections.Counter(sums).iteritems()}\n total = reduce(operator.ior, dp.itervalues(), 0)\n basis = total&-total # find rightmost bit 1\n if basis > 1:\n for k in dp.iterkeys():\n dp[k] //= basis\n sorted_sums = sorted(dp.iterkeys()) # Time: O(2^n * log(2^n)) = O(n * 2^n)\n shift = 0\n result = [0]*(basis.bit_length()-1)\n for _ in range(n-len(result)): # log(2^n) times, each time costs O(2^(n-len(result))), Total Time: O(2^n)\n new_dp = {}\n new_sorted_sums = []\n new_shift = sorted_sums[0]-sorted_sums[1]\n assert(new_shift < 0)\n for x in sorted_sums:\n if not dp[x]:\n continue\n dp[x-new_shift] -= dp[x]\n new_dp[x-new_shift] = dp[x]\n new_sorted_sums.append(x-new_shift)\n dp = new_dp\n sorted_sums = new_sorted_sums\n if shift in dp: # contain 0, choose this side\n result.append(new_shift)\n else: # contain no 0, choose another side and shift 0 offset\n result.append(-new_shift)\n shift -= new_shift\n return result\n\n\n# Time: O(n * 2^n), len(sums) = 2^n\n# Space: O(2^n)\nimport collections\n\n\n# optimized from solution4 (not using OrderedDict), runtime: 1024 ms\nclass Solution4(object):\n def recoverArray(self, n, sums):\n \"\"\"\n :type n: int\n :type sums: List[int]\n :rtype: List[int]\n \"\"\"\n dp = {k: v for k, v in collections.Counter(sums).iteritems()}\n sorted_sums = sorted(dp.iterkeys()) # Time: O(2^n * log(2^n)) = O(n * 2^n)\n shift = 0\n result = []\n for _ in range(n): # log(2^n) times, each time costs O(2^(n-len(result))), Total Time: O(2^n)\n new_dp = {}\n new_sorted_sums = []\n new_shift = sorted_sums[0]-sorted_sums[1] if dp[sorted_sums[0]] == 1 else 0\n assert(new_shift <= 0)\n for x in sorted_sums:\n if not dp[x]:\n continue\n dp[x-new_shift] -= dp[x] if new_shift else dp[x]//2\n new_dp[x-new_shift] = dp[x]\n new_sorted_sums.append(x-new_shift)\n dp = new_dp\n sorted_sums = new_sorted_sums\n if shift in dp: # contain 0, choose this side\n result.append(new_shift)\n else: # contain no 0, choose another side and shift 0 offset\n result.append(-new_shift)\n shift -= new_shift\n return result\n\n\n# Time: O(n * 2^n), len(sums) = 2^n\n# Space: O(2^n)\nimport collections\n\n\n# runtime: 1720 ms\nclass Solution5(object):\n def recoverArray(self, n, sums):\n \"\"\"\n :type n: int\n :type sums: List[int]\n :rtype: List[int]\n \"\"\"\n dp = OrderedDict(sorted(collections.Counter(sums).iteritems())) # Time: O(2^n * log(2^n)) = O(n * 2^n)\n shift = 0\n result = []\n for _ in range(n): # log(2^n) times, each time costs O(2^(n-len(result))), Total Time: O(2^n)\n new_dp = OrderedDict()\n it = iter(dp)\n min_sum = next(it)\n new_shift = min_sum-next(it) if dp[min_sum] == 1 else 0\n assert(new_shift <= 0)\n for x in dp.iterkeys():\n if not dp[x]:\n continue\n dp[x-new_shift] -= dp[x] if new_shift else dp[x]//2\n new_dp[x-new_shift] = dp[x]\n dp = new_dp\n if shift in dp: # contain 0, choose this side\n result.append(new_shift)\n else: # contain no 0, choose another side and shift 0 offset\n result.append(-new_shift)\n shift -= new_shift\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11328", "name": "LeetCode 1985: Find The Kth Largest Integer In 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: Find the Kth Largest Integer in the Array (Difficulty: Medium)\nTags: Array, String, Divide and Conquer, Sorting, Heap (Priority Queue), Quickselect\n\nYou are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros.\nReturn the string that represents the kth largest integer in nums.\nNote: Duplicate numbers should be counted distinctly. For example, if nums is [\"1\",\"2\",\"2\"], \"2\" is the first largest integer, \"2\" is the second-largest integer, and \"1\" is the third-largest integer.\n\nExample 1:\nInput: nums = [\"3\",\"6\",\"7\",\"10\"], k = 4\nOutput: \"3\"\nExplanation:\nThe numbers in nums sorted in non-decreasing order are [\"3\",\"6\",\"7\",\"10\"].\nThe 4th largest integer in nums is \"3\".\n\nExample 2:\nInput: nums = [\"2\",\"21\",\"12\",\"1\"], k = 3\nOutput: \"2\"\nExplanation:\nThe numbers in nums sorted in non-decreasing order are [\"1\",\"2\",\"12\",\"21\"].\nThe 3rd largest integer in nums is \"2\".\n\nExample 3:\nInput: nums = [\"0\",\"0\"], k = 2\nOutput: \"0\"\nExplanation:\nThe numbers in nums sorted in non-decreasing order are [\"0\",\"0\"].\nThe 2nd largest integer in nums is \"0\".\n\nConstraints:\n- 1 <= k <= nums.length <= 10^4\n- 1 <= nums[i].length <= 100\n- nums[i] consists of only digits.\n- nums[i] will not have any leading zeros."}}{"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\nclass Solution(object):\n def kthLargestNumber(self, nums, k):\n \"\"\"\n :type nums: List[str]\n :type k: int\n :rtype: str\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 nth_element(nums, k-1, compare=lambda a, b: a > b if len(a) == len(b) else len(a) > len(b))\n return nums[k-1]\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11329", "name": "LeetCode 1986: Minimum Number Of Work Sessions To Finish The 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 Number of Work Sessions to Finish the Tasks (Difficulty: Medium)\nTags: Array, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask\n\nThere are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break.\nYou should finish the given tasks in a way that satisfies the following conditions:\nGiven tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above.\nThe tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].\n\nExample 1:\nInput: tasks = [1,2,3], sessionTime = 3\nOutput: 2\nExplanation: You can finish the tasks in two work sessions.\n- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.\n- Second work session: finish the third task in 3 hours.\n\nExample 2:\nInput: tasks = [3,1,3,1,1], sessionTime = 8\nOutput: 2\nExplanation: You can finish the tasks in two work sessions.\n- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.\n- Second work session: finish the last task in 1 hour.\n\nExample 3:\nInput: tasks = [1,2,3,4,5], sessionTime = 15\nOutput: 1\nExplanation: You can finish all the tasks in one work session.\n\nConstraints:\n- n == tasks.length\n- 1 <= n <= 14\n- 1 <= tasks[i] <= 10\n- max(tasks[i]) <= sessionTime <= 15"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * 2^n)\n# Space: O(2^n)\n\nclass Solution(object):\n def minSessions(self, tasks, sessionTime):\n \"\"\"\n :type tasks: List[int]\n :type sessionTime: int\n :rtype: int\n \"\"\"\n # dp[mask]: min used time by choosing tasks in mask bitset\n dp = [float(\"inf\") for _ in range(1<<len(tasks))]\n dp[0] = 0\n for mask in range(len(dp)-1):\n basis = 1\n for task in tasks:\n new_mask = mask|basis\n basis <<= 1\n if new_mask == mask:\n continue\n if dp[mask]%sessionTime + task > sessionTime:\n task += sessionTime-dp[mask]%sessionTime # take a break\n dp[new_mask] = min(dp[new_mask], dp[mask]+task)\n return (dp[-1]+sessionTime-1)//sessionTime\n\n\n# Time: O(n * 2^n)\n# Space: O(2^n)\nclass Solution2(object):\n def minSessions(self, tasks, sessionTime):\n \"\"\"\n :type tasks: List[int]\n :type sessionTime: int\n :rtype: int\n \"\"\"\n # dp[mask][0]: min number of sessions by choosing tasks in mask bitset\n # dp[mask][1]: min used time of last session by choosing tasks in mask bitset\n dp = [[float(\"inf\")]*2 for _ in range(1<<len(tasks))]\n dp[0] = [0, sessionTime]\n for mask in range(len(dp)-1):\n basis = 1\n for task in tasks:\n new_mask = mask|basis\n basis <<= 1\n if new_mask == mask:\n continue\n if dp[mask][1]+task <= sessionTime:\n dp[new_mask] = min(dp[new_mask], [dp[mask][0], dp[mask][1]+task])\n else:\n dp[new_mask] = min(dp[new_mask], [dp[mask][0]+1, task])\n return dp[-1][0]\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11330", "name": "LeetCode 1987: Number Of Unique Good 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 Unique Good Subsequences (Difficulty: Hard)\nTags: String, Dynamic Programming\n\nYou are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of \"0\").\nFind the number of unique good subsequences of binary.\nReturn the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 109 + 7.\nA subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.\n\nExample 1:\nInput: binary = \"001\"\nOutput: 2\nExplanation: The good subsequences of binary are [\"0\", \"0\", \"1\"].\nThe unique good subsequences are \"0\" and \"1\".\n\nExample 2:\nInput: binary = \"11\"\nOutput: 2\nExplanation: The good subsequences of binary are [\"1\", \"1\", \"11\"].\nThe unique good subsequences are \"1\" and \"11\".\n\nExample 3:\nInput: binary = \"101\"\nOutput: 5\nExplanation: The good subsequences of binary are [\"1\", \"0\", \"1\", \"10\", \"11\", \"101\"]. \nThe unique good subsequences are \"0\", \"1\", \"10\", \"11\", and \"101\".\n\nConstraints:\n- 1 <= binary.length <= 10^5\n- binary consists of only '0's and '1's."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def numberOfUniqueGoodSubsequences(self, binary):\n \"\"\"\n :type binary: str\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n ends0, ends1 = 0, 0\n has_zero = False\n for b in binary:\n if b == '1':\n ends1 = (ends0+ends1+1)%MOD # curr subsequences end with 1 is all prev distinct subsequences appended by 1 and plus \"1\"\n else:\n ends0 = (ends0+ends1)%MOD # curr subsequences end with 0 is all prev distinct subsequences appended by 0 and don't plus \"0\"\n has_zero = True\n return (ends0+ends1+int(has_zero))%MOD # add \"0\" if has_zero\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11332", "name": "LeetCode 1991: Find The Middle Index 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: Find the Middle Index in Array (Difficulty: Easy)\nTags: Array, Prefix Sum\n\nGiven a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).\nA middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].\nIf middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0.\nReturn the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.\nNote: This question is the same as 724: https://leetcode.com/problems/find-pivot-index/\n\nExample 1:\nInput: nums = [2,3,-1,8,4]\nOutput: 3\nExplanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4\nThe sum of the numbers after index 3 is: 4 = 4\n\nExample 2:\nInput: nums = [1,-1,4]\nOutput: 2\nExplanation: The sum of the numbers before index 2 is: 1 + -1 = 0\nThe sum of the numbers after index 2 is: 0\n\nExample 3:\nInput: nums = [2,5]\nOutput: -1\nExplanation: There is no valid middleIndex.\n\nConstraints:\n- 1 <= nums.length <= 100\n- -1000 <= nums[i] <= 1000"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def findMiddleIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n total = sum(nums)\n accu = 0\n for i, x in enumerate(nums):\n if accu*2 == total-x:\n return i\n accu += x\n return -1\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11333", "name": "LeetCode 1992: Find All Groups Of Farmland"}{"type": "message", "message": {"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 Groups of Farmland (Difficulty: Medium)\nTags: Array, Depth-First Search, Breadth-First Search, Matrix\n\nYou are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland.\nTo keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group.\nland can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2].\nReturn a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order.\n\nExample 1:\nInput: land = [[1,0,0],[0,1,1],[0,1,1]]\nOutput: [[0,0,0,0],[1,1,2,2]]\nExplanation:\nThe first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].\nThe second group has a top left corner at land[1][1] and a bottom right corner at land[2][2].\n\nExample 2:\nInput: land = [[1,1],[1,1]]\nOutput: [[0,0,1,1]]\nExplanation:\nThe first group has a top left corner at land[0][0] and a bottom right corner at land[1][1].\n\nExample 3:\nInput: land = [[0]]\nOutput: []\nExplanation:\nThere are no groups of farmland.\n\nConstraints:\n- m == land.length\n- n == land[i].length\n- 1 <= m, n <= 300\n- land consists of only 0's and 1's.\n- Groups of farmland are rectangular in shape."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def findFarmland(self, land):\n \"\"\"\n :type land: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n result = []\n for i in range(len(land)):\n for j in range(len(land[0])):\n if land[i][j] != 1:\n continue\n ni, nj = i, j\n while ni+1 < len(land) and land[ni+1][j] == 1:\n ni += 1\n while nj+1 < len(land[0]) and land[i][nj+1] == 1:\n nj += 1\n for r in range(i, ni+1):\n for c in range(j, nj+1):\n land[r][c] = -1\n result.append([i, j, ni, nj])\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11334", "name": "LeetCode 1993: Operations On 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: Operations on Tree (Difficulty: Medium)\nTags: Array, Hash Table, 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 the ith node. The root of the tree is node 0, so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.\nThe data structure should support the following functions:\nImplement the LockingTree class:\n\nExample 1:\nInput\n[\"LockingTree\", \"lock\", \"unlock\", \"unlock\", \"lock\", \"upgrade\", \"lock\"]\n[[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]]\nOutput\n[null, true, false, true, true, true, false]\n\nExplanation\nLockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]);\nlockingTree.lock(2, 2); // return true because node 2 is unlocked.\n // Node 2 will now be locked by user 2.\nlockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.\nlockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.\n // Node 2 will now be unlocked.\nlockingTree.lock(4, 5); // return true because node 4 is unlocked.\n // Node 4 will now be locked by user 5.\nlockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).\n // Node 0 will now be locked by user 1 and node 4 will now be unlocked.\nlockingTree.lock(0, 1); // return false because node 0 is already locked.\n\nConstraints:\n- n == parent.length\n- 2 <= n <= 2000\n- 0 <= parent[i] <= n - 1 for i != 0\n- parent[0] == -1\n- 0 <= num <= n - 1\n- 1 <= user <= 10^4\n- parent represents a valid tree.\n- At most 2000 calls in total will be made to lock, unlock, and upgrade."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(n)\n# lock: O(1)\n# unlock: O(1)\n# upgrade: O(n)\n# Space: O(n)\n\nclass LockingTree(object):\n\n def __init__(self, parent):\n \"\"\"\n :type parent: List[int]\n \"\"\"\n self.__parent = parent\n self.__children = [[] for _ in range(len(parent))]\n for i, x in enumerate(parent):\n if x != -1:\n self.__children[x].append(i)\n self.__locked = {}\n\n def lock(self, num, user):\n \"\"\"\n :type num: int\n :type user: int\n :rtype: bool\n \"\"\"\n if num in self.__locked:\n return False\n self.__locked[num] = user\n return True\n\n def unlock(self, num, user):\n \"\"\"\n :type num: int\n :type user: int\n :rtype: bool\n \"\"\"\n if self.__locked.get(num) != user:\n return False\n del self.__locked[num]\n return True\n\n def upgrade(self, num, user):\n \"\"\"\n :type num: int\n :type user: int\n :rtype: bool\n \"\"\"\n node = num\n while node != -1:\n if node in self.__locked:\n return False\n node = self.__parent[node]\n result = False\n stk = [num]\n while stk:\n node = stk.pop()\n if node in self.__locked:\n del self.__locked[node]\n result = True\n for child in self.__children[node]:\n stk.append(child)\n if result:\n self.__locked[num] = user\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11335", "name": "LeetCode 1994: The Number Of Good 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: The Number of Good Subsets (Difficulty: Hard)\nTags: Array, Hash Table, Math, Dynamic Programming, Bit Manipulation, Counting, Number Theory, Bitmask\n\nYou are given an integer array nums. We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers.\nReturn the number of different good subsets in nums modulo 109 + 7.\nA subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.\n\nExample 1:\nInput: nums = [1,2,3,4]\nOutput: 6\nExplanation: The good subsets are:\n- [1,2]: product is 2, which is the product of distinct prime 2.\n- [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [1,3]: product is 3, which is the product of distinct prime 3.\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [3]: product is 3, which is the product of distinct prime 3.\n\nExample 2:\nInput: nums = [4,2,3,15]\nOutput: 5\nExplanation: The good subsets are:\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.\n- [3]: product is 3, which is the product of distinct prime 3.\n- [15]: product is 15, which is the product of distinct primes 3 and 5.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= nums[i] <= 30"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * 2^p), p is the number of primes in [1, n]\n# Space: O(2^p)\n\nimport collections\n\n\nclass Solution(object):\n def numberOfGoodSubsets(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def sieve_of_eratosthenes(n): # Time: O(n * log(logn)), Space: O(n)\n if n < 2:\n return []\n primes = [2]\n is_prime = [True]*((n+1)//2)\n for i in range(1, len(is_prime)):\n if not is_prime[i]:\n continue\n primes.append(2*i+1)\n for j in range(2*i*(i+1), len(is_prime), (2*i+1)):\n is_prime[j] = False\n return primes\n\n def to_mask(primes, x):\n mask, basis = 0, 1\n for p in primes:\n if x%p == 0:\n mask |= basis\n basis <<= 1\n return mask\n\n MOD = 10**9+7\n primes = sieve_of_eratosthenes(max(nums))\n dp = [0]*(1<<len(primes)) # dp[i] = the number of different good subsets of which the total product equals to the product of the primes in bitset i\n dp[0] = 1\n cnts = collections.Counter(nums)\n for x, cnt in cnts.iteritems():\n if x == 1 or any(x%(p*p) == 0 for p in primes if p*p <= x):\n continue\n mask = to_mask(primes, x)\n for i in range(len(dp)-1):\n if i&mask:\n continue\n dp[i|mask] = (dp[i|mask]+cnt*dp[i])%MOD\n return (pow(2, cnts[1], MOD))*(reduce(lambda total, x: (total+x)%MOD, dp, 0)-1)%MOD\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11336", "name": "LeetCode 1995: Count Special Quadruplets"}{"type": "message", "message": {"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 Special Quadruplets (Difficulty: Easy)\nTags: Array, Hash Table, Enumeration\n\nGiven a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:\n\nExample 1:\nInput: nums = [1,2,3,6]\nOutput: 1\nExplanation: The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.\n\nExample 2:\nInput: nums = [3,3,6,4,5]\nOutput: 0\nExplanation: There are no such quadruplets in [3,3,6,4,5].\n\nExample 3:\nInput: nums = [1,1,1,3,5]\nOutput: 4\nExplanation: The 4 quadruplets that satisfy the requirement are:\n- (0, 1, 2, 3): 1 + 1 + 1 == 3\n- (0, 1, 3, 4): 1 + 1 + 3 == 5\n- (0, 2, 3, 4): 1 + 1 + 3 == 5\n- (1, 2, 3, 4): 1 + 1 + 3 == 5\n\nConstraints:\n- 4 <= nums.length <= 50\n- 1 <= nums[i] <= 100"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def countQuadruplets(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result = 0\n lookup = collections.defaultdict(int)\n lookup[nums[-1]] = 1\n for c in reversed(range(2, len(nums)-1)):\n for b in range(1, c):\n for a in range(b):\n if nums[a]+nums[b]+nums[c] in lookup:\n result += lookup[nums[a]+nums[b]+nums[c]]\n lookup[nums[c]] += 1\n return result\n\n \n# Time: O(n^2) ~ O(n^4)\n# Space: O(n^2)\nimport collections\n\n\nclass Solution2(object):\n def countQuadruplets(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n lookup = collections.defaultdict(list)\n for d in range(3, len(nums)):\n for c in range(2, d):\n lookup[nums[d]-nums[c]].append(c)\n return sum(sum(b < c for c in lookup[nums[a]+nums[b]]) for b in range(1, len(nums)-2) for a in range(b))\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11337", "name": "LeetCode 1996: The Number Of Weak Characters In The 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: The Number of Weak Characters in the Game (Difficulty: Medium)\nTags: Array, Stack, Greedy, Sorting, Monotonic Stack\n\nYou are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game.\nA character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei.\nReturn the number of weak characters.\n\nExample 1:\nInput: properties = [[5,5],[6,3],[3,6]]\nOutput: 0\nExplanation: No character has strictly greater attack and defense than the other.\n\nExample 2:\nInput: properties = [[2,2],[3,3]]\nOutput: 1\nExplanation: The first character is weak because the second character has a strictly greater attack and defense.\n\nExample 3:\nInput: properties = [[1,5],[10,4],[4,3]]\nOutput: 1\nExplanation: The third character is weak because the second character has a strictly greater attack and defense.\n\nConstraints:\n- 2 <= properties.length <= 10^5\n- properties[i].length == 2\n- 1 <= attacki, defensei <= 10^5"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nclass Solution(object):\n def numberOfWeakCharacters(self, properties):\n \"\"\"\n :type properties: List[List[int]]\n :rtype: int\n \"\"\"\n properties.sort(cmp=lambda a, b: cmp(b[1], a[1]) if a[0] == b[0] else cmp(a[0], b[0]))\n result = max_d = 0\n for a, d in reversed(properties):\n if d < max_d:\n result += 1\n max_d = max(max_d, d)\n return result\n\n \n# Time: O(nlogn)\n# Space: O(n)\nimport collections\n\n\n# faster in sort by using more space\nclass Solution(object):\n def numberOfWeakCharacters(self, properties):\n \"\"\"\n :type properties: List[List[int]]\n :rtype: int\n \"\"\"\n lookup = collections.defaultdict(list)\n for a, d in properties:\n lookup[a].append(d)\n result = max_d = 0\n for a in sorted(lookup.iterkeys(), reverse=True):\n result += sum(d < max_d for d in lookup[a])\n max_d = max(max_d, max(lookup[a]))\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11338", "name": "LeetCode 1997: First Day Where You Have Been In All The 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: First Day Where You Have Been in All the Rooms (Difficulty: Medium)\nTags: Array, Dynamic Programming\n\nThere are n rooms you need to visit, labeled from 0 to n - 1. Each day is labeled, starting from 0. You will go in and visit one room a day.\nInitially on day 0, you visit room 0. The order you visit the rooms for the coming days is determined by the following rules and a given 0-indexed array nextVisit of length n:\nReturn the label of the first day where you have been in all the rooms. It can be shown that such a day exists. Since the answer may be very large, return it modulo 109 + 7.\n\nExample 1:\nInput: nextVisit = [0,0]\nOutput: 2\nExplanation:\n- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.\n On the next day you will visit room nextVisit[0] = 0\n- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.\n On the next day you will visit room (0 + 1) mod 2 = 1\n- On day 2, you visit room 1. This is the first day where you have been in all the rooms.\n\nExample 2:\nInput: nextVisit = [0,0,2]\nOutput: 6\nExplanation:\nYour room visiting order for each day is: [0,0,1,0,0,1,2,...].\nDay 6 is the first day where you have been in all the rooms.\n\nExample 3:\nInput: nextVisit = [0,1,2,0]\nOutput: 6\nExplanation:\nYour room visiting order for each day is: [0,0,1,1,2,2,3,...].\nDay 6 is the first day where you have been in all the rooms.\n\nConstraints:\n- n == nextVisit.length\n- 2 <= n <= 10^5\n- 0 <= nextVisit[i] <= i"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def firstDayBeenInAllRooms(self, nextVisit):\n \"\"\"\n :type nextVisit: List[int]\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n\n dp = [0]*len(nextVisit)\n for i in range(1, len(dp)):\n dp[i] = (dp[i-1]+1+(dp[i-1]-dp[nextVisit[i-1]])+1)%MOD\n return dp[-1]\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11339", "name": "LeetCode 1998: Gcd Sort 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: GCD Sort of an Array (Difficulty: Hard)\nTags: Array, Math, Union Find, Sorting, Number Theory\n\nYou are given an integer array nums, and you can perform the following operation any number of times on nums:\nReturn true if it is possible to sort nums in non-decreasing order using the above swap method, or false otherwise.\n\nExample 1:\nInput: nums = [7,21,3]\nOutput: true\nExplanation: We can sort [7,21,3] by performing the following operations:\n- Swap 7 and 21 because gcd(7,21) = 7. nums = [21,7,3]\n- Swap 21 and 3 because gcd(21,3) = 3. nums = [3,7,21]\n\nExample 2:\nInput: nums = [5,2,6,2]\nOutput: false\nExplanation: It is impossible to sort the array because 5 cannot be swapped with any other element.\n\nExample 3:\nInput: nums = [10,5,9,3,15]\nOutput: true\nWe can sort [10,5,9,3,15] by performing the following operations:\n- Swap 10 and 15 because gcd(10,15) = 5. nums = [15,5,9,3,10]\n- Swap 15 and 3 because gcd(15,3) = 3. nums = [3,5,9,15,10]\n- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,10,15]\n\nConstraints:\n- 1 <= nums.length <= 3 * 10^4\n- 2 <= nums[i] <= 10^5"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn + n * α(n) + m * log(logm)) ~= O(nlogn + m), m is the max of nums\n# Space: O(n + m)\n\nimport itertools\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 gcdSort(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n def modified_sieve_of_eratosthenes(n, lookup, uf): # Time: O(n * log(logn)), Space: O(n)\n if n < 2:\n return\n is_prime = [True]*(n+1)\n for i in range(2, len(is_prime)):\n if not is_prime[i]:\n continue\n for j in range(i+i, len(is_prime), i):\n is_prime[j] = False\n if j in lookup: # modified\n uf.union_set(i-1, j-1)\n\n max_num = max(nums)\n uf = UnionFind(max_num)\n modified_sieve_of_eratosthenes(max_num, set(nums), uf)\n return all(uf.find_set(a-1) == uf.find_set(b-1) for a, b in itertools.izip(nums, sorted(nums)))\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11342", "name": "LeetCode 2001: Number Of Pairs Of Interchangeable Rectangles"}{"type": "message", "message": {"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 Pairs of Interchangeable Rectangles (Difficulty: Medium)\nTags: Array, Hash Table, Math, Counting, Number Theory\n\nYou are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle.\nTwo rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division).\nReturn the number of pairs of interchangeable rectangles in rectangles.\n\nExample 1:\nInput: rectangles = [[4,8],[3,6],[10,20],[15,30]]\nOutput: 6\nExplanation: The following are the interchangeable pairs of rectangles by index (0-indexed):\n- Rectangle 0 with rectangle 1: 4/8 == 3/6.\n- Rectangle 0 with rectangle 2: 4/8 == 10/20.\n- Rectangle 0 with rectangle 3: 4/8 == 15/30.\n- Rectangle 1 with rectangle 2: 3/6 == 10/20.\n- Rectangle 1 with rectangle 3: 3/6 == 15/30.\n- Rectangle 2 with rectangle 3: 10/20 == 15/30.\n\nExample 2:\nInput: rectangles = [[4,5],[7,8]]\nOutput: 0\nExplanation: There are no interchangeable pairs of rectangles.\n\nConstraints:\n- n == rectangles.length\n- 1 <= n <= 10^5\n- rectangles[i].length == 2\n- 1 <= widthi, heighti <= 10^5"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\nimport fractions\n\n\nclass Solution(object):\n def interchangeableRectangles(self, rectangles):\n \"\"\"\n :type rectangles: List[List[int]]\n :rtype: int\n \"\"\"\n count = collections.defaultdict(int)\n for w, h in rectangles:\n g = fractions.gcd(w, h) # Time: O(logx) ~= O(1)\n count[(w//g, h//g)] += 1\n return sum(c*(c-1)//2 for c in count.itervalues())\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11343", "name": "LeetCode 2002: Maximum Product Of The Length Of Two 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: Maximum Product of the Length of Two Palindromic Subsequences (Difficulty: Medium)\nTags: String, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask\n\nGiven a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index.\nReturn the maximum possible product of the lengths of the two palindromic subsequences.\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.\n\nExample 1:\nInput: s = \"leetcodecom\"\nOutput: 9\nExplanation: An optimal solution is to choose \"ete\" for the 1st subsequence and \"cdc\" for the 2nd subsequence.\nThe product of their lengths is: 3 * 3 = 9.\n\nExample 2:\nInput: s = \"bb\"\nOutput: 1\nExplanation: An optimal solution is to choose \"b\" (the first character) for the 1st subsequence and \"b\" (the second character) for the 2nd subsequence.\nThe product of their lengths is: 1 * 1 = 1.\n\nExample 3:\nInput: s = \"accbcaxxcxx\"\nOutput: 25\nExplanation: An optimal solution is to choose \"accca\" for the 1st subsequence and \"xxcxx\" for the 2nd subsequence.\nThe product of their lengths is: 5 * 5 = 25.\n\nConstraints:\n- 2 <= s.length <= 12\n- s consists of lowercase English letters only."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(3^n)\n# Space: O(2^n)\n\nclass Solution(object):\n def maxProduct(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n def palindromic_subsequence_length(s, mask):\n result = 0\n left, right = 0, len(s)-1\n left_bit, right_bit = 1<<left, 1<<right\n while left <= right:\n if mask&left_bit == 0:\n left, left_bit = left+1, left_bit<<1\n elif mask&right_bit == 0:\n right, right_bit = right-1, right_bit>>1\n elif s[left] == s[right]:\n result += 1 if left == right else 2\n left, left_bit = left+1, left_bit<<1\n right, right_bit = right-1, right_bit>>1\n else:\n return 0\n return result\n \n dp = [palindromic_subsequence_length(s, mask) for mask in range(1<<len(s))]\n result = 0\n for mask in range(len(dp)):\n if dp[mask]*(len(s)-dp[mask]) <= result: # optimize\n continue\n # submask enumeration:\n # => 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 = inverse_mask = (len(dp)-1)^mask\n while submask:\n result = max(result, dp[mask]*dp[submask])\n submask = (submask-1)&inverse_mask\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11344", "name": "LeetCode 2003: Smallest Missing Genetic Value In Each Subtree"}{"type": "message", "message": {"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 Missing Genetic Value in Each Subtree (Difficulty: Hard)\nTags: Dynamic Programming, Tree, Depth-First Search, Union Find\n\nThere is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1.\nThere are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i.\nReturn an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i.\nThe subtree rooted at a node x contains node x and all of its descendant nodes.\n\nExample 1:\nInput: parents = [-1,0,0,2], nums = [1,2,3,4]\nOutput: [5,1,1,1]\nExplanation: The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.\n- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.\n- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.\n- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.\n\nExample 2:\nInput: parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]\nOutput: [7,1,1,4,2,1]\nExplanation: The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.\n- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.\n- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.\n- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.\n- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.\n- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.\n\nExample 3:\nInput: parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]\nOutput: [1,1,1,1,1,1,1]\nExplanation: The value 1 is missing from all the subtrees.\n\nConstraints:\n- n == parents.length == nums.length\n- 2 <= n <= 10^5\n- 0 <= parents[i] <= n - 1 for i != 0\n- parents[0] == -1\n- parents represents a valid tree.\n- 1 <= nums[i] <= 10^5\n- Each nums[i] is distinct."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def smallestMissingValueSubtree(self, parents, nums):\n \"\"\"\n :type parents: List[int]\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n def iter_dfs(adj, nums, i, lookup):\n stk = [i]\n while stk:\n i = stk.pop()\n if nums[i] in lookup:\n continue\n lookup.add(nums[i])\n for j in adj[i]:\n stk.append(j)\n\n result = [1]*len(parents)\n i = next((i for i in range(len(nums)) if nums[i] == 1), -1)\n if i == -1:\n return result\n adj = [[] for _ in range(len(parents))]\n for j in range(1, len(parents)):\n adj[parents[j]].append(j)\n lookup = set()\n miss = 1\n while i >= 0:\n iter_dfs(adj, nums, i, lookup)\n while miss in lookup:\n miss += 1\n result[i] = miss\n i = parents[i]\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11346", "name": "LeetCode 2006: Count Number Of Pairs With Absolute Difference 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: Count Number of Pairs With Absolute Difference K (Difficulty: Easy)\nTags: Array, Hash Table, Counting\n\nGiven an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.\nThe value of |x| is defined as:\n\nExample 1:\nInput: nums = [1,2,2,1], k = 1\nOutput: 4\nExplanation: The pairs with an absolute difference of 1 are:\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n\nExample 2:\nInput: nums = [1,3], k = 3\nOutput: 0\nExplanation: There are no pairs with an absolute difference of 3.\n\nExample 3:\nInput: nums = [3,2,1,5,4], k = 2\nOutput: 3\nExplanation: The pairs with an absolute difference of 2 are:\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n\nConstraints:\n- 1 <= nums.length <= 200\n- 1 <= nums[i] <= 100\n- 1 <= k <= 99"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def countKDifference(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n lookup = collections.defaultdict(int)\n result = 0\n for x in nums:\n if x-k in lookup:\n result += lookup[x-k]\n if x+k in lookup:\n result += lookup[x+k]\n lookup[x] += 1 \n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11347", "name": "LeetCode 2007: Find Original Array From Doubled 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 Original Array From Doubled Array (Difficulty: Medium)\nTags: Array, Hash Table, Greedy, Sorting\n\nAn integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array.\nGiven an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order.\n\nExample 1:\nInput: changed = [1,3,4,2,6,8]\nOutput: [1,3,4]\nExplanation: One possible original array could be [1,3,4]:\n- Twice the value of 1 is 1 * 2 = 2.\n- Twice the value of 3 is 3 * 2 = 6.\n- Twice the value of 4 is 4 * 2 = 8.\nOther original arrays could be [4,3,1] or [3,1,4].\n\nExample 2:\nInput: changed = [6,3,0,1]\nOutput: []\nExplanation: changed is not a doubled array.\n\nExample 3:\nInput: changed = [1]\nOutput: []\nExplanation: changed is not a doubled array.\n\nConstraints:\n- 1 <= changed.length <= 10^5\n- 0 <= changed[i] <= 10^5"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + klogk), k is the distinct number of changed\n# Space: O(k)\n\nclass Solution(object):\n def findOriginalArray(self, changed):\n \"\"\"\n :type changed: List[int]\n :rtype: List[int]\n \"\"\"\n if len(changed)%2:\n return []\n cnts = collections.Counter(changed)\n for x in sorted(cnts.iterkeys()):\n if cnts[x] > cnts[2*x]:\n return []\n cnts[2*x] -= cnts[x] if x else cnts[x]//2\n return list(cnts.elements())\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11348", "name": "LeetCode 2008: Maximum Earnings From Taxi"}{"type": "message", "message": {"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 Earnings From Taxi (Difficulty: Medium)\nTags: Array, Hash Table, Binary Search, Dynamic Programming, Sorting\n\nThere are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi.\nThe passengers are represented by a 0-indexed 2D integer array rides, where rides[i] = [starti, endi, tipi] denotes the ith passenger requesting a ride from point starti to point endi who is willing to give a tipi dollar tip.\nFor each passenger i you pick up, you earn endi - starti + tipi dollars. You may only drive at most one passenger at a time.\nGiven n and rides, return the maximum number of dollars you can earn by picking up the passengers optimally.\nNote: You may drop off a passenger and pick up a different passenger at the same point.\n\nExample 1:\nInput: n = 5, rides = [[2,5,4],[1,5,1]]\nOutput: 7\nExplanation: We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars.\n\nExample 2:\nInput: n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]]\nOutput: 20\nExplanation: We will pick up the following passengers:\n- Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars.\n- Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars.\n- Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars.\nWe earn 9 + 5 + 6 = 20 dollars in total.\n\nConstraints:\n- 1 <= n <= 10^5\n- 1 <= rides.length <= 3 * 10^4\n- rides[i].length == 3\n- 1 <= starti < endi <= n\n- 1 <= tipi <= 10^5"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n + mlogm), m is the number of rides\n# Space: O(n)\n\nclass Solution(object):\n def maxTaxiEarnings(self, n, rides):\n \"\"\"\n :type n: int\n :type rides: List[List[int]]\n :rtype: int\n \"\"\"\n rides.sort()\n dp = [0]*(n+1)\n j = 0\n for i in range(1, n+1):\n dp[i] = max(dp[i], dp[i-1])\n while j < len(rides) and rides[j][0] == i:\n dp[rides[j][1]] = max(dp[rides[j][1]], dp[i]+rides[j][1]-rides[j][0]+rides[j][2])\n j += 1\n return dp[-1]\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11349", "name": "LeetCode 2009: Minimum Number Of Operations To Make Array Continuous"}{"type": "message", "message": {"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 Array Continuous (Difficulty: Hard)\nTags: Array, Hash Table, Binary Search, Sliding Window\n\nYou are given an integer array nums. In one operation, you can replace any element in nums with any integer.\nnums is considered continuous if both of the following conditions are fulfilled:\nFor example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous.\nReturn the minimum number of operations to make nums continuous.\n\nExample 1:\nInput: nums = [4,2,5,3]\nOutput: 0\nExplanation: nums is already continuous.\n\nExample 2:\nInput: nums = [1,2,3,5,6]\nOutput: 1\nExplanation: One possible solution is to change the last element to 4.\nThe resulting array is [1,2,3,5,4], which is continuous.\n\nExample 3:\nInput: nums = [1,10,100,1000]\nOutput: 3\nExplanation: One possible solution is to:\n- Change the second element to 2.\n- Change the third element to 3.\n- Change the fourth element to 4.\nThe resulting array is [1,2,3,4], which is continuous.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- 1 <= 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 unique(nums):\n left = 0\n for right in range(1, len(nums)):\n if nums[left] != nums[right]:\n left += 1\n nums[left] = nums[right]\n return left\n\n def erase(nums, i):\n while len(nums) > i+1:\n nums.pop()\n\n n = len(nums)\n nums.sort()\n erase(nums, unique(nums))\n result = l = 0\n for i in range(len(nums)):\n if nums[i] <= nums[i-l]+n-1:\n l += 1\n return n-l\n\n\n# Time: O(nlogn)\n# Space: O(n)\nclass Solution2(object):\n def minOperations(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n n = len(nums)\n nums = sorted(set(nums))\n result = right = 0\n for left in range(len(nums)):\n while right < len(nums) and nums[right] <= nums[left]+n-1:\n right += 1\n result = max(result, right-left)\n return n-result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11351", "name": "LeetCode 2012: Sum Of Beauty In 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: Sum of Beauty in the Array (Difficulty: Medium)\nTags: Array\n\nYou are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals:\nReturn the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.\n\nExample 1:\nInput: nums = [1,2,3]\nOutput: 2\nExplanation: For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 2.\n\nExample 2:\nInput: nums = [2,4,6,4]\nOutput: 1\nExplanation: For each index i in the range 1 <= i <= 2:\n- The beauty of nums[1] equals 1.\n- The beauty of nums[2] equals 0.\n\nExample 3:\nInput: nums = [3,2,1]\nOutput: 0\nExplanation: For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 0.\n\nConstraints:\n- 3 <= nums.length <= 10^5\n- 1 <= nums[i] <= 10^5"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def sumOfBeauties(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n right = [nums[-1]]*len(nums)\n for i in reversed(range(2, len(nums)-1)):\n right[i] = min(right[i+1], nums[i])\n result, left = 0, nums[0]\n for i in range(1, len(nums)-1):\n if left < nums[i] < right[i+1]:\n result += 2\n elif nums[i-1] < nums[i] < nums[i+1]:\n result += 1\n left = max(left, nums[i])\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11352", "name": "LeetCode 2013: Detect 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: Detect Squares (Difficulty: Medium)\nTags: Array, Hash Table, Design, Counting\n\nYou are given a stream of points on the X-Y plane. Design an algorithm that:\nAn axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis.\nImplement the DetectSquares class:\n\nExample 1:\nInput\n[\"DetectSquares\", \"add\", \"add\", \"add\", \"count\", \"count\", \"add\", \"count\"]\n[[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]]\nOutput\n[null, null, null, null, 1, 0, null, 2]\n\nExplanation\nDetectSquares detectSquares = new DetectSquares();\ndetectSquares.add([3, 10]);\ndetectSquares.add([11, 2]);\ndetectSquares.add([3, 2]);\ndetectSquares.count([11, 10]); // return 1. You can choose:\n // - The first, second, and third points\ndetectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure.\ndetectSquares.add([11, 2]); // Adding duplicate points is allowed.\ndetectSquares.count([11, 10]); // return 2. You can choose:\n // - The first, second, and third points\n // - The first, third, and fourth points\n\nConstraints:\n- point.length == 2\n- 0 <= x, y <= 1000\n- At most 3000 calls in total will be made to add and count."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(1)\n# add: O(1)\n# count: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass DetectSquares(object):\n\n def __init__(self):\n self.__x_to_ys = collections.defaultdict(set)\n self.__point_counts = collections.defaultdict(int)\n\n def add(self, point):\n \"\"\"\n :type point: List[int]\n :rtype: None\n \"\"\"\n self.__x_to_ys[point[0]].add(point[1])\n self.__point_counts[tuple(point)] += 1\n \n\n def count(self, point):\n \"\"\"\n :type point: List[int]\n :rtype: int\n \"\"\"\n result = 0\n for y in self.__x_to_ys[point[0]]:\n if y == point[1]:\n continue\n dy = y-point[1]\n result += self.__point_counts[(point[0], y)]*self.__point_counts[(point[0]+dy, point[1])]*self.__point_counts[(point[0]+dy, y)]\n result += self.__point_counts[(point[0], y)]*self.__point_counts[(point[0]-dy, point[1])]*self.__point_counts[(point[0]-dy, y)]\n return result \n\n\n# Time: ctor: O(1)\n# add: O(1)\n# count: O(n)\n# Space: O(n)\nimport collections\n\n\nclass DetectSquares2(object):\n\n def __init__(self):\n self.__points = []\n self.__point_counts = collections.defaultdict(int)\n\n def add(self, point):\n \"\"\"\n :type point: List[int]\n :rtype: None\n \"\"\"\n self.__points.append(point)\n self.__point_counts[tuple(point)] += 1\n\n def count(self, point):\n \"\"\"\n :type point: List[int]\n :rtype: int\n \"\"\"\n result = 0\n for x, y in self.__points:\n if not (point[0] != x and point[1] != y and (abs(point[0]-x) == abs(point[1]-y))):\n continue\n result += self.__point_counts[(point[0], y)]*self.__point_counts[(x, point[1])]\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11353", "name": "LeetCode 2014: Longest Subsequence Repeated K Times"}{"type": "message", "message": {"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 Subsequence Repeated k Times (Difficulty: Hard)\nTags: String, Backtracking, Greedy, Counting, Enumeration\n\nYou are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s.\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\nA subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times.\nReturn the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.\n\nExample 1:\nInput: s = \"letsleetcode\", k = 2\nOutput: \"let\"\nExplanation: There are two longest subsequences repeated 2 times: \"let\" and \"ete\".\n\"let\" is the lexicographically largest one.\n\nExample 2:\nInput: s = \"bb\", k = 2\nOutput: \"b\"\nExplanation: The longest subsequence repeated 2 times is \"b\".\n\nExample 3:\nInput: s = \"ab\", k = 2\nOutput: \"\"\nExplanation: There is no subsequence repeated 2 times. Empty string is returned.\n\nConstraints:\n- n == s.length\n- 2 <= k <= 2000\n- 2 <= n < min(2001, k * 8)\n- s consists of lowercase English letters."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * (n/k)!)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def longestSubsequenceRepeatedK(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n def check(s, k, curr):\n if not curr:\n return True\n i = 0\n for c in s:\n if c != curr[i]:\n continue\n i += 1\n if i != len(curr):\n continue\n i = 0\n k -= 1\n if not k:\n return True\n return False\n\n def backtracking(s, k, curr, cnts, result):\n if not check(s, k, curr):\n return\n if len(curr) > len(result):\n result[:] = curr\n for c in reversed(string.ascii_lowercase):\n if cnts[c] < k:\n continue\n cnts[c] -= k\n curr.append(c)\n backtracking(s, k, curr, cnts, result)\n curr.pop()\n cnts[c] += k\n \n cnts = collections.Counter(s)\n new_s = []\n for c in s:\n if cnts[c] < k:\n continue\n new_s.append(c)\n result =[]\n backtracking(new_s, k, [], cnts, result)\n return \"\".join(result)\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11355", "name": "LeetCode 2016: Maximum Difference Between Increasing 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: Maximum Difference Between Increasing Elements (Difficulty: Easy)\nTags: Array\n\nGiven a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j].\nReturn the maximum difference. If no such i and j exists, return -1.\n\nExample 1:\nInput: nums = [7,1,5,4]\nOutput: 4\nExplanation:\nThe maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.\nNote that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid.\n\nExample 2:\nInput: nums = [9,4,3,2]\nOutput: -1\nExplanation:\nThere is no i and j such that i < j and nums[i] < nums[j].\n\nExample 3:\nInput: nums = [1,5,2,10]\nOutput: 9\nExplanation:\nThe maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9.\n\nConstraints:\n- n == nums.length\n- 2 <= n <= 1000\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 maximumDifference(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result, prefix = 0, float(\"inf\")\n for x in nums: \n result = max(result, x-prefix)\n prefix = min(prefix, x)\n return result if result else -1\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11356", "name": "LeetCode 2017: Grid 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: Grid Game (Difficulty: Medium)\nTags: Array, Matrix, Prefix Sum\n\nYou are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix.\nBoth robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)).\nAt the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its path. Note that their paths may intersect with one another.\nThe first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot.\n\nExample 1:\nInput: grid = [[2,5,4],[1,5,1]]\nOutput: 4\nExplanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 0 + 4 + 0 = 4 points.\n\nExample 2:\nInput: grid = [[3,3,1],[8,5,2]]\nOutput: 4\nExplanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 3 + 1 + 0 = 4 points.\n\nExample 3:\nInput: grid = [[1,3,1,15],[1,3,3,1]]\nOutput: 7\nExplanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points.\n\nConstraints:\n- grid.length == 2\n- n == grid[r].length\n- 1 <= n <= 5 * 10^4\n- 1 <= grid[r][c] <= 10^5"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def gridGame(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n result = float(\"inf\")\n left, right = 0, sum(grid[0])\n for a, b in itertools.izip(grid[0], grid[1]):\n right -= a\n result = min(result, max(left, right))\n left += b\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11357", "name": "LeetCode 2018: Check If Word Can Be Placed In Crossword"}{"type": "message", "message": {"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 Can Be Placed In Crossword (Difficulty: Medium)\nTags: Array, Matrix, Enumeration\n\nYou are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells.\nA word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if:\nGiven a string word, return true if word can be placed in board, or false otherwise.\n\nExample 1:\nInput: board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \"c\", \" \"]], word = \"abc\"\nOutput: true\nExplanation: The word \"abc\" can be placed as shown above (top to bottom).\n\nExample 2:\nInput: board = [[\" \", \"#\", \"a\"], [\" \", \"#\", \"c\"], [\" \", \"#\", \"a\"]], word = \"ac\"\nOutput: false\nExplanation: It is impossible to place the word because there will always be a space/letter above or below it.\n\nExample 3:\nInput: board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \" \", \"c\"]], word = \"ca\"\nOutput: true\nExplanation: The word \"ca\" can be placed as shown above (right to left).\n\nConstraints:\n- m == board.length\n- n == board[i].length\n- 1 <= m * n <= 2 * 10^5\n- board[i][j] will be ' ', '#', or a lowercase English letter.\n- 1 <= word.length <= max(m, n)\n- word will contain only lowercase English letters."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def placeWordInCrossword(self, board, word):\n \"\"\"\n :type board: List[List[str]]\n :type word: str\n :rtype: bool\n \"\"\"\n def get_val(mat, i, j, transposed):\n return mat[i][j] if not transposed else mat[j][i]\n\n def get_vecs(mat, transposed):\n for i in range(len(mat) if not transposed else len(mat[0])):\n yield (get_val(mat, i, j, transposed) for j in range(len(mat[0]) if not transposed else len(mat)))\n\n for direction in (lambda x: iter(x), reversed):\n for transposed in range(2):\n for row in get_vecs(board, transposed):\n it, matched = direction(word), True\n for c in row:\n if c == '#':\n if next(it, None) is None and matched:\n return True\n it, matched = direction(word), True\n continue\n if not matched:\n continue\n nc = next(it, None)\n matched = (nc is not None) and c in (nc, ' ')\n if (next(it, None) is None) and matched:\n return True\n return False\n\n\n# Time: O(m * n)\n# Space: O(m * n)\nclass Solution2(object):\n def placeWordInCrossword(self, board, word):\n \"\"\"\n :type board: List[List[str]]\n :type word: str\n :rtype: bool\n \"\"\"\n words = [word, word[::-1]]\n for mat in (board, zip(*board)):\n for row in mat:\n blocks = ''.join(row).split('#')\n for s in blocks:\n if len(s) != len(word):\n continue\n for w in words:\n if all(s[i] in (w[i], ' ') for i in range(len(s))):\n return True\n return False\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11358", "name": "LeetCode 2019: The Score Of Students Solving Math 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: The Score of Students Solving Math Expression (Difficulty: Hard)\nTags: Array, Math, String, Dynamic Programming, Stack, Memoization\n\nYou are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations:\nYou are given an integer array answers of length n, which are the submitted answers of the students in no particular order. You are asked to grade the answers, by following these rules:\nReturn the sum of the points of the students.\n\nExample 1:\nInput: s = \"7+3*1*2\", answers = [20,13,42]\nOutput: 7\nExplanation: As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]\nA student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42]\nThe points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.\n\nExample 2:\nInput: s = \"3+5*2\", answers = [13,0,10,13,13,16,16]\nOutput: 19\nExplanation: The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]\nA student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16]\nThe points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.\n\nExample 3:\nInput: s = \"6+0*1\", answers = [12,9,6,4,8,6]\nOutput: 10\nExplanation: The correct answer of the expression is 6.\nIf a student had incorrectly done (6+0)*1, the answer would also be 6.\nBy the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.\nThe points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.\n\nConstraints:\n- 3 <= s.length <= 31\n- s represents a valid expression that contains only digits 0-9, '+', and '*' only.\n- All the integer operands in the expression are in the inclusive range [0, 9].\n- 1 <= The count of all operators ('+' and '*') in the math expression <= 15\n- Test data are generated such that the correct answer of the expression is in the range of [0, 1000].\n- n == answers.length\n- 1 <= n <= 10^4\n- 0 <= answers[i] <= 1000"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n^3 * a^2)\n# Space: O(n^2)\n\nclass Solution(object):\n def scoreOfStudents(self, s, answers):\n \"\"\"\n :type s: str\n :type answers: List[int]\n :rtype: int\n \"\"\"\n MAX_ANS = 1000\n n = (len(s)+1)//2\n dp = [[set() for _ in range(n)] for _ in range(n)]\n for i in range(n):\n dp[i][i].add(int(s[i*2]))\n for l in range(1, n):\n for left in range(n-l):\n right = left+l\n for k in range(left, right):\n if s[2*k+1] == '+':\n dp[left][right].update((x+y for x in dp[left][k] for y in dp[k+1][right] if x+y <= MAX_ANS))\n else:\n dp[left][right].update((x*y for x in dp[left][k] for y in dp[k+1][right] if x*y <= MAX_ANS))\n target = eval(s)\n return sum(5 if ans == target else 2 if ans in dp[0][-1] else 0 for ans in answers)\n\n\n# Time: O(n^3 * a^2)\n# Space: O(n^2)\nclass Solution2(object):\n def scoreOfStudents(self, s, answers):\n \"\"\"\n :type s: str\n :type answers: List[int]\n :rtype: int\n \"\"\"\n MAX_ANS = 1000\n def evaluate(s):\n def compute(operands, operators):\n right, left = operands.pop(), operands.pop()\n operands.append(ops[operators.pop()](left, right))\n\n ops = {'+':operator.add, '*':operator.mul}\n precedence = {'+':0, '*':1}\n operands, operators, operand = [], [], 0\n for c in s:\n if c.isdigit():\n operands.append(int(c))\n else:\n while operators and precedence[operators[-1]] >= precedence[c]:\n compute(operands, operators)\n operators.append(c)\n while operators:\n compute(operands, operators)\n return operands[-1]\n\n n = (len(s)+1)//2\n dp = [[set() for _ in range(n)] for _ in range(n)]\n for i in range(n):\n dp[i][i].add(int(s[i*2]))\n for l in range(1, n):\n for left in range(n-l):\n right = left+l\n for k in range(left, right):\n if s[2*k+1] == '+':\n dp[left][right].update((x+y for x in dp[left][k] for y in dp[k+1][right] if x+y <= MAX_ANS))\n else:\n dp[left][right].update((x*y for x in dp[left][k] for y in dp[k+1][right] if x*y <= MAX_ANS))\n target = evaluate(s)\n return sum(5 if ans == target else 2 if ans in dp[0][-1] else 0 for ans in answers)\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11360", "name": "LeetCode 2022: Convert 1D Array Into 2D 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: Convert 1D Array Into 2D Array (Difficulty: Easy)\nTags: Array, Matrix, Simulation\n\nYou are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original.\nThe elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on.\nReturn an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.\n\nExample 1:\nInput: original = [1,2,3,4], m = 2, n = 2\nOutput: [[1,2],[3,4]]\nExplanation: The constructed 2D array should contain 2 rows and 2 columns.\nThe first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.\nThe second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.\n\nExample 2:\nInput: original = [1,2,3], m = 1, n = 3\nOutput: [[1,2,3]]\nExplanation: The constructed 2D array should contain 1 row and 3 columns.\nPut all three elements in original into the first row of the constructed 2D array.\n\nExample 3:\nInput: original = [1,2], m = 1, n = 1\nOutput: []\nExplanation: There are 2 elements in original.\nIt is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.\n\nConstraints:\n- 1 <= original.length <= 5 * 10^4\n- 1 <= original[i] <= 10^5\n- 1 <= m, n <= 4 * 10^4"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n)\n# Space: O(1)\n\nclass Solution(object):\n def construct2DArray(self, original, m, n):\n \"\"\"\n :type original: List[int]\n :type m: int\n :type n: int\n :rtype: List[List[int]]\n \"\"\"\n return [original[i:i+n] for i in range(0, len(original), n)] if len(original) == m*n else []\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11361", "name": "LeetCode 2023: Number Of Pairs Of Strings With Concatenation Equal 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 Pairs of Strings With Concatenation Equal to Target (Difficulty: Medium)\nTags: Array, Hash Table, String, Counting\n\nGiven an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.\n\nExample 1:\nInput: nums = [\"777\",\"7\",\"77\",\"77\"], target = \"7777\"\nOutput: 4\nExplanation: Valid pairs are:\n- (0, 1): \"777\" + \"7\"\n- (1, 0): \"7\" + \"777\"\n- (2, 3): \"77\" + \"77\"\n- (3, 2): \"77\" + \"77\"\n\nExample 2:\nInput: nums = [\"123\",\"4\",\"12\",\"34\"], target = \"1234\"\nOutput: 2\nExplanation: Valid pairs are:\n- (0, 1): \"123\" + \"4\"\n- (2, 3): \"12\" + \"34\"\n\nExample 3:\nInput: nums = [\"1\",\"1\",\"1\"], target = \"11\"\nOutput: 6\nExplanation: Valid pairs are:\n- (0, 1): \"1\" + \"1\"\n- (1, 0): \"1\" + \"1\"\n- (0, 2): \"1\" + \"1\"\n- (2, 0): \"1\" + \"1\"\n- (1, 2): \"1\" + \"1\"\n- (2, 1): \"1\" + \"1\"\n\nConstraints:\n- 2 <= nums.length <= 100\n- 1 <= nums[i].length <= 100\n- 2 <= target.length <= 100\n- nums[i] and target consist of digits.\n- nums[i] and target do not have leading zeros."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * l), n is the size of nums, l is the average length of the digit string in nums\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def numOfPairs(self, nums, target):\n \"\"\"\n :type nums: List[str]\n :type target: str\n :rtype: int\n \"\"\"\n lookup = collections.Counter()\n result = 0\n for num in nums:\n cnt1, cnt2 = lookup[-(len(target)-len(num))], lookup[len(target)-len(num)]\n if target.startswith(num):\n result += cnt1\n lookup[len(num)] += 1\n if target.endswith(num):\n result += cnt2\n lookup[-len(num)] += 1\n return result\n\n\n# Time: O(n * l), n is the size of nums, l is the average length of the digit string in nums\n# Space: O(n)\nimport collections\n\n\nclass Solution2(object):\n def numOfPairs(self, nums, target):\n \"\"\"\n :type nums: List[str]\n :type target: str\n :rtype: int\n \"\"\"\n prefix, suffix = collections.Counter(), collections.Counter()\n result = 0\n for num in nums:\n if target.startswith(num):\n result += suffix[len(target)-len(num)]\n if target.endswith(num):\n result += prefix[len(target)-len(num)]\n if target.startswith(num):\n prefix[len(num)] += 1\n if target.endswith(num):\n suffix[len(num)] += 1\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11362", "name": "LeetCode 2024: Maximize The Confusion Of An 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: Maximize the Confusion of an Exam (Difficulty: Medium)\nTags: String, Binary Search, Sliding Window, Prefix Sum\n\nA teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).\nYou are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation:\nReturn the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times.\n\nExample 1:\nInput: answerKey = \"TTFF\", k = 2\nOutput: 4\nExplanation: We can replace both the 'F's with 'T's to make answerKey = \"TTTT\".\nThere are four consecutive 'T's.\n\nExample 2:\nInput: answerKey = \"TFFT\", k = 1\nOutput: 3\nExplanation: We can replace the first 'T' with an 'F' to make answerKey = \"FFFT\".\nAlternatively, we can replace the second 'T' with an 'F' to make answerKey = \"TFFF\".\nIn both cases, there are three consecutive 'F's.\n\nExample 3:\nInput: answerKey = \"TTFTTFTT\", k = 1\nOutput: 5\nExplanation: We can replace the first 'F' to make answerKey = \"TTTTTFTT\"\nAlternatively, we can replace the second 'F' to make answerKey = \"TTFTTTTT\". \nIn both cases, there are five consecutive 'T's.\n\nConstraints:\n- n == answerKey.length\n- 1 <= n <= 5 * 10^4\n- answerKey[i] is either 'T' or 'F'\n- 1 <= k <= n"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def maxConsecutiveAnswers(self, answerKey, k):\n \"\"\"\n :type answerKey: str\n :type k: int\n :rtype: int\n \"\"\"\n result = max_count = 0\n count = collections.Counter()\n for i in range(len(answerKey)):\n count[answerKey[i]] += 1\n max_count = max(max_count, count[answerKey[i]])\n if result-max_count >= k:\n count[answerKey[i-result]] -= 1\n else:\n result += 1\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11363", "name": "LeetCode 2025: Maximum Number Of Ways To Partition 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 Number of Ways to Partition an Array (Difficulty: Hard)\nTags: Array, Hash Table, Counting, Enumeration, Prefix Sum\n\nYou are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions:\nYou are also given an integer k. You can choose to change the value of one element of nums to k, or to leave the array unchanged.\nReturn the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element.\n\nExample 1:\nInput: nums = [2,-1,2], k = 3\nOutput: 1\nExplanation: One optimal approach is to change nums[0] to k. The array becomes [3,-1,2].\nThere is one way to partition the array:\n- For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.\n\nExample 2:\nInput: nums = [0,0,0], k = 1\nOutput: 2\nExplanation: The optimal approach is to leave the array unchanged.\nThere are two ways to partition the array:\n- For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0.\n- For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.\n\nExample 3:\nInput: nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33\nOutput: 4\nExplanation: One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14].\nThere are four ways to partition the array.\n\nConstraints:\n- n == nums.length\n- 2 <= n <= 10^5\n- -10^5 <= k, 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 waysToPartition(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n total = sum(nums)\n right = collections.Counter()\n prefix = 0\n for i in range(len(nums)-1):\n prefix += nums[i]\n right[prefix-(total-prefix)] += 1\n result = right[0]\n left = collections.Counter()\n prefix = 0\n for x in nums:\n result = max(result, left[k-x]+right[-(k-x)])\n prefix += x\n left[prefix-(total-prefix)] += 1\n right[prefix-(total-prefix)] -= 1\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11364", "name": "LeetCode 2027: Minimum Moves To Convert 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 Moves to Convert String (Difficulty: Easy)\nTags: String, Greedy\n\nYou are given a string s consisting of n characters which are either 'X' or 'O'.\nA move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same.\nReturn the minimum number of moves required so that all the characters of s are converted to 'O'.\n\nExample 1:\nInput: s = \"XXX\"\nOutput: 1\nExplanation: XXX -> OOO\nWe select all the 3 characters and convert them in one move.\n\nExample 2:\nInput: s = \"XXOX\"\nOutput: 2\nExplanation: XXOX -> OOOX -> OOOO\nWe select the first 3 characters in the first move, and convert them to 'O'.\nThen we select the last 3 characters and convert them so that the final string contains all 'O's.\n\nExample 3:\nInput: s = \"OOOO\"\nOutput: 0\nExplanation: There are no 'X's in s to convert.\n\nConstraints:\n- 3 <= s.length <= 1000\n- s[i] is either 'X' or 'O'."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def minimumMoves(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result = i = 0\n while i < len(s):\n if s[i] == 'X':\n result += 1\n i += 3\n else:\n i += 1\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11365", "name": "LeetCode 2028: Find Missing Observations"}{"type": "message", "message": {"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 Missing Observations (Difficulty: Medium)\nTags: Array, Math, Simulation\n\nYou have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls.\nYou are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n.\nReturn an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array.\nThe average value of a set of k numbers is the sum of the numbers divided by k.\nNote that mean is an integer, so the sum of the n + m rolls should be divisible by n + m.\n\nExample 1:\nInput: rolls = [3,2,4,3], mean = 4, n = 2\nOutput: [6,6]\nExplanation: The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.\n\nExample 2:\nInput: rolls = [1,5,6], mean = 3, n = 4\nOutput: [2,3,2,2]\nExplanation: The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.\n\nExample 3:\nInput: rolls = [1,2,3,4], mean = 6, n = 4\nOutput: []\nExplanation: It is impossible for the mean to be 6 no matter what the 4 missing rolls are.\n\nConstraints:\n- m == rolls.length\n- 1 <= n, m <= 10^5\n- 1 <= rolls[i], mean <= 6"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def missingRolls(self, rolls, mean, n):\n \"\"\"\n :type rolls: List[int]\n :type mean: int\n :type n: int\n :rtype: List[int]\n \"\"\"\n MAX_V = 6\n MIN_V = 1\n total = sum(rolls)\n missing = mean*(n+len(rolls))-total\n if missing < MIN_V*n or missing > MAX_V*n:\n return []\n q, r = divmod(missing, n)\n return [q+int(i < r) for i in range(n)]\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def missingRolls(self, rolls, mean, n):\n \"\"\"\n :type rolls: List[int]\n :type mean: int\n :type n: int\n :rtype: List[int]\n \"\"\"\n MAX_V = 6\n MIN_V = 1\n total = sum(rolls)\n missing = mean*(n+len(rolls))-total\n if missing < MIN_V*n or missing > MAX_V*n:\n return []\n q, r = divmod(missing-MIN_V*n, (MAX_V-MIN_V))\n return [MAX_V if i < q else MIN_V+r if i == q else MIN_V for i in range(n)]\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11366", "name": "LeetCode 2029: Stone Game Ix"}{"type": "message", "message": {"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 IX (Difficulty: Medium)\nTags: Array, Math, Greedy, Counting, Game Theory\n\nAlice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone.\nAlice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3. Bob will win automatically if there are no remaining stones (even if it is Alice's turn).\nAssuming both players play optimally, return true if Alice wins and false if Bob wins.\n\nExample 1:\nInput: stones = [2,1]\nOutput: true\nExplanation: The game will be played as follows:\n- Turn 1: Alice can remove either stone.\n- Turn 2: Bob removes the remaining stone. \nThe sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game.\n\nExample 2:\nInput: stones = [2]\nOutput: false\nExplanation: Alice will remove the only stone, and the sum of the values on the removed stones is 2. \nSince all the stones are removed and the sum of values is not divisible by 3, Bob wins the game.\n\nExample 3:\nInput: stones = [5,1,2,4,3]\nOutput: false\nExplanation: Bob will always win. One possible way for Bob to win is shown below:\n- Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1.\n- Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4.\n- Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8.\n- Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10.\n- Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15.\nAlice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game.\n\nConstraints:\n- 1 <= stones.length <= 10^5\n- 1 <= stones[i] <= 10^4"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nimport collections\n\n\nclass Solution(object):\n def stoneGameIX(self, stones):\n \"\"\"\n :type stones: List[int]\n :rtype: bool\n \"\"\"\n count = collections.Counter(x%3 for x in stones)\n if count[0]%2 == 0:\n # iff both counts are not zero, then alice takes the least one at first, the remains are deterministic for bob to lose:\n # - assumed count[1] is the least one:\n # 1(,1,2)*,2,(,2)* => bob loses\n # ^\n # - assumed count[2] is the least one:\n # 2(,2,1)*,1,(,1)* => bob loses\n # ^\n return count[1] and count[2]\n # iff abs(count[1] - count[2]) >= 3, then alice takes the most one at first, the remains are deterministic for bob to lose:\n # - assumed count[1] is the most one\n # 1(,1,2)*,0,1(,2,1)*,1,(,1)* => bob loses\n # ^\n # 1(,1,2)*,1,0,1,(,1)* => bob loses\n # ^\n # - assumed count[2] is the most one\n # 2(,2,1)*,0,2(,1,2)*,2,(,2)* => bob loses\n # ^\n # 2(,2,1)*,2,0,2,(,2)* => bob loses\n # ^\n return abs(count[1]-count[2]) >= 3 \n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11367", "name": "LeetCode 2030: Smallest K Length Subsequence With Occurrences Of A Letter"}{"type": "message", "message": {"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 K-Length Subsequence With Occurrences of a Letter (Difficulty: Hard)\nTags: String, Stack, Greedy, Monotonic Stack\n\nYou are given a string s, an integer k, a letter letter, and an integer repetition.\nReturn the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times.\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\nA string a is lexicographically smaller than a string b 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.\n\nExample 1:\nInput: s = \"leet\", k = 3, letter = \"e\", repetition = 1\nOutput: \"eet\"\nExplanation: There are four subsequences of length 3 that have the letter 'e' appear at least 1 time:\n- \"lee\" (from \"leet\")\n- \"let\" (from \"leet\")\n- \"let\" (from \"leet\")\n- \"eet\" (from \"leet\")\nThe lexicographically smallest subsequence among them is \"eet\".\n\nExample 2:\nInput: s = \"leetcode\", k = 4, letter = \"e\", repetition = 2\nOutput: \"ecde\"\nExplanation: \"ecde\" is the lexicographically smallest subsequence of length 4 that has the letter \"e\" appear at least 2 times.\n\nExample 3:\nInput: s = \"bb\", k = 2, letter = \"b\", repetition = 2\nOutput: \"bb\"\nExplanation: \"bb\" is the only subsequence of length 2 that has the letter \"b\" appear at least 2 times.\n\nConstraints:\n- 1 <= repetition <= k <= s.length <= 5 * 10^4\n- s consists of lowercase English letters.\n- letter is a lowercase English letter, and appears in s at least repetition times."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nclass Solution(object):\n def smallestSubsequence(self, s, k, letter, repetition):\n \"\"\"\n :type s: str\n :type k: int\n :type letter: str\n :type repetition: int\n :rtype: str\n \"\"\"\n stk = []\n suffix = [0]*(len(s)+1)\n for i in reversed(range(len(suffix)-1)):\n suffix[i] = suffix[i+1]+(s[i] == letter)\n for i, c in enumerate(s): \n while stk and stk[-1] > c and len(stk)+(len(s)-i) > k and (stk[-1] != letter or repetition+1 <= suffix[i]):\n repetition += (stk.pop() == letter)\n if len(stk) < min(k-(repetition-(c == letter)), k):\n repetition -= (c == letter)\n stk.append(c)\n return \"\".join(stk)\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11369", "name": "LeetCode 2032: Two Out 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: Two Out of Three (Difficulty: Easy)\nTags: Array, Hash Table, Bit Manipulation\n\nExample 1:\nInput: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]\nOutput: [3,2]\nExplanation: The values that are present in at least two arrays are:\n- 3, in all three arrays.\n- 2, in nums1 and nums2.\n\nExample 2:\nInput: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]\nOutput: [2,3,1]\nExplanation: The values that are present in at least two arrays are:\n- 2, in nums2 and nums3.\n- 3, in nums1 and nums2.\n- 1, in nums1 and nums3.\n\nExample 3:\nInput: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]\nOutput: []\nExplanation: No value is present in at least two arrays.\n\nConstraints:\n- 1 <= nums1.length, nums2.length, nums3.length <= 100\n- 1 <= nums1[i], nums2[j], nums3[k] <= 100"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(min(n, r)), r is the range size of nums\n\nimport collections\n\n\nclass Solution(object):\n def twoOutOfThree(self, nums1, nums2, nums3):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :type nums3: List[int]\n :rtype: List[int]\n \"\"\"\n K = 2\n cnt = collections.Counter()\n for nums in nums1, nums2, nums3:\n cnt.update(set(nums))\n return [x for x, c in cnt.iteritems() if c >= K]\n\n\n# Time: O(n)\n# Space: O(min(n, r)), r is the range size of nums\nimport collections\n\n\nclass Solution2(object):\n def twoOutOfThree(self, nums1, nums2, nums3):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :type nums3: List[int]\n :rtype: List[int]\n \"\"\"\n K = 2\n cnt = collections.Counter()\n result = []\n for nums in nums1, nums2, nums3:\n for x in set(nums):\n cnt[x] += 1\n if cnt[x] == K:\n result.append(x)\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11370", "name": "LeetCode 2033: Minimum Operations To Make A Uni Value 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 Operations to Make a Uni-Value Grid (Difficulty: Medium)\nTags: Array, Math, Sorting, Matrix\n\nYou are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid.\nA uni-value grid is a grid where all the elements of it are equal.\nReturn the minimum number of operations to make the grid uni-value. If it is not possible, return -1.\n\nExample 1:\nInput: grid = [[2,4],[6,8]], x = 2\nOutput: 4\nExplanation: We can make every element equal to 4 by doing the following: \n- Add x to 2 once.\n- Subtract x from 6 once.\n- Subtract x from 8 twice.\nA total of 4 operations were used.\n\nExample 2:\nInput: grid = [[1,5],[2,3]], x = 1\nOutput: 5\nExplanation: We can make every element equal to 3.\n\nExample 3:\nInput: grid = [[1,2],[3,4]], x = 2\nOutput: -1\nExplanation: It is impossible to make every element equal.\n\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 10^5\n- 1 <= m * n <= 10^5\n- 1 <= x, grid[i][j] <= 10^4"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(m * n) on average\n# Space: O(m * n)\n\nimport random\n\nclass Solution(object):\n def minOperations(self, grid, x):\n \"\"\"\n :type grid: List[List[int]]\n :type x: 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 nums = [v for row in grid for v in row]\n if len(set(v%x for v in nums)) > 1:\n return -1\n nth_element(nums, len(nums)//2)\n median = nums[len(nums)//2]\n return sum(abs(v-median)//x for v in nums)\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11371", "name": "LeetCode 2034: Stock Price Fluctuation"}{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}{"type": "message", "message": {"role": "user", "content": "Problem: Stock Price Fluctuation (Difficulty: Medium)\nTags: Hash Table, Design, Heap (Priority Queue), Data Stream, Ordered Set\n\nYou are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp.\nUnfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record.\nDesign an algorithm that:\nImplement the StockPrice class:\n\nExample 1:\nInput\n[\"StockPrice\", \"update\", \"update\", \"current\", \"maximum\", \"update\", \"maximum\", \"update\", \"minimum\"]\n[[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]\nOutput\n[null, null, null, 5, 10, null, 5, null, 2]\n\nExplanation\nStockPrice stockPrice = new StockPrice();\nstockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].\nstockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5].\nstockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5.\nstockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1.\nstockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3.\n // Timestamps are [1,2] with corresponding prices [3,5].\nstockPrice.maximum(); // return 5, the maximum price is 5 after the correction.\nstockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2].\nstockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4.\n\nConstraints:\n- 1 <= timestamp, price <= 10^9\n- At most 105 calls will be made in total to update, current, maximum, and minimum.\n- current, maximum, and minimum will be called only after update has been called at least once."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(1)\n# update: O(logn)\n# current: O(1)\n# max: O(1)\n# min: O(1)\n# Space: O(n)\n\nfrom sortedcontainers import SortedList\n\n\nclass StockPrice(object):\n\n def __init__(self):\n self.__curr = 0\n self.__lookup = {}\n self.__sl_by_price = SortedList()\n\n def update(self, timestamp, price):\n \"\"\"\n :type timestamp: int\n :type price: int\n :rtype: None\n \"\"\"\n if timestamp > self.__curr:\n self.__curr = timestamp\n if timestamp in self.__lookup:\n self.__sl_by_price.remove(self.__lookup[timestamp])\n self.__lookup[timestamp] = price\n self.__sl_by_price.add(price)\n\n def current(self):\n \"\"\"\n :rtype: int\n \"\"\"\n return self.__lookup[self.__curr]\n\n def maximum(self):\n \"\"\"\n :rtype: int\n \"\"\"\n return next(reversed(self.__sl_by_price))\n\n def minimum(self):\n \"\"\"\n :rtype: int\n \"\"\"\n return next(iter(self.__sl_by_price))\n\n\n# Time: ctor: O(1)\n# update: O(logn)\n# current: O(1)\n# max: O(logn) on average\n# min: O(logn) on average\n# Space: O(n)\nimport heapq\n\n\nclass StockPrice2(object):\n\n def __init__(self):\n self.__curr = 0\n self.__lookup = {}\n self.__min_heap = []\n self.__max_heap = []\n\n def update(self, timestamp, price):\n \"\"\"\n :type timestamp: int\n :type price: int\n :rtype: None\n \"\"\"\n def full_delete(heap, sign): # Time: O(n), Space: O(n)\n heap[:] = [x for x in set(heap) if sign*x[0] == self.__lookup[x[1]]]\n heapq.heapify(heap)\n\n if timestamp > self.__curr:\n self.__curr = timestamp\n self.__lookup[timestamp] = price\n heapq.heappush(self.__min_heap, (price, timestamp))\n heapq.heappush(self.__max_heap, (-price, timestamp))\n if len(self.__min_heap) > 2*len(self.__lookup): # avoid too much expired or duplicated data\n full_delete(self.__min_heap, 1)\n full_delete(self.__max_heap, -1)\n\n def current(self):\n \"\"\"\n :rtype: int\n \"\"\"\n return self.__lookup[self.__curr]\n\n def maximum(self):\n \"\"\"\n :rtype: int\n \"\"\"\n while self.__max_heap and self.__lookup[self.__max_heap[0][1]] != -self.__max_heap[0][0]: # lazy delete\n heapq.heappop(self.__max_heap)\n return -self.__max_heap[0][0]\n\n def minimum(self):\n \"\"\"\n :rtype: int\n \"\"\"\n while self.__min_heap and self.__lookup[self.__min_heap[0][1]] != self.__min_heap[0][0]: # lazy delete\n heapq.heappop(self.__min_heap)\n return self.__min_heap[0][0]\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11372", "name": "LeetCode 2035: Partition Array Into Two Arrays To Minimize 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: Partition Array Into Two Arrays to Minimize Sum Difference (Difficulty: Hard)\nTags: Array, Two Pointers, Binary Search, Dynamic Programming, Bit Manipulation, Ordered Set, Bitmask\n\nYou are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums, put each element of nums into one of the two arrays.\nReturn the minimum possible absolute difference.\n\nExample 1:\nInput: nums = [3,9,7,3]\nOutput: 2\nExplanation: One optimal partition is: [3,9] and [7,3].\nThe absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.\n\nExample 2:\nInput: nums = [-36,36]\nOutput: 72\nExplanation: One optimal partition is: [-36] and [36].\nThe absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.\n\nExample 3:\nInput: nums = [2,-1,0,4,-2,-9]\nOutput: 0\nExplanation: One optimal partition is: [2,4,-9] and [-1,0,-2].\nThe absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.\n\nConstraints:\n- 1 <= n <= 15\n- nums.length == 2 * n\n- -107 <= nums[i] <= 10^7"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * 2^n)\n# Space: O(2^n)\n\nimport itertools\nimport bisect\n\n\nclass Solution(object):\n def minimumDifference(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n left, right = nums[:len(nums)//2], nums[len(nums)//2:]\n total1, total2 = sum(left), sum(right)\n result = float(\"inf\")\n for k in range(len(left)+1): \n sums = sorted(2*sum(comb)-total1 for comb in itertools.combinations(left, k))\n for comb in itertools.combinations(right, len(left)-k): \n diff = 2*sum(comb)-total2\n i = bisect.bisect_left(sums, -diff)\n if i < len(sums):\n result = min(result, abs(sums[i]+diff))\n if i > 0:\n result = min(result, abs(sums[i-1]+diff))\n return result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11374", "name": "LeetCode 2037: Minimum Number Of Moves To Seat Everyone"}{"type": "message", "message": {"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 Moves to Seat Everyone (Difficulty: Easy)\nTags: Array, Greedy, Sorting, Counting Sort\n\nThere are n availabe seats and n students standing in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student.\nYou may perform the following move any number of times:\nReturn the minimum number of moves required to move each student to a seat such that no two students are in the same seat.\nNote that there may be multiple seats or students in the same position at the beginning.\n\nExample 1:\nInput: seats = [3,1,5], students = [2,7,4]\nOutput: 4\nExplanation: The students are moved as follows:\n- The first student is moved from position 2 to position 1 using 1 move.\n- The second student is moved from position 7 to position 5 using 2 moves.\n- The third student is moved from position 4 to position 3 using 1 move.\nIn total, 1 + 2 + 1 = 4 moves were used.\n\nExample 2:\nInput: seats = [4,1,5,9], students = [1,3,2,6]\nOutput: 7\nExplanation: The students are moved as follows:\n- The first student is not moved.\n- The second student is moved from position 3 to position 4 using 1 move.\n- The third student is moved from position 2 to position 5 using 3 moves.\n- The fourth student is moved from position 6 to position 9 using 3 moves.\nIn total, 0 + 1 + 3 + 3 = 7 moves were used.\n\nExample 3:\nInput: seats = [2,2,6,6], students = [1,3,2,6]\nOutput: 4\nExplanation: Note that there are two seats at position 2 and two seats at position 6.\nThe students are moved as follows:\n- The first student is moved from position 1 to position 2 using 1 move.\n- The second student is moved from position 3 to position 6 using 3 moves.\n- The third student is not moved.\n- The fourth student is not moved.\nIn total, 1 + 3 + 0 + 0 = 4 moves were used.\n\nConstraints:\n- n == seats.length == students.length\n- 1 <= n <= 100\n- 1 <= seats[i], students[j] <= 100"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(nlogn)\n# Space: O(1)\n\nimport itertools\n\n\nclass Solution(object):\n def minMovesToSeat(self, seats, students):\n \"\"\"\n :type seats: List[int]\n :type students: List[int]\n :rtype: int\n \"\"\"\n seats.sort()\n students.sort()\n return sum(abs(a-b) for a, b in itertools.izip(seats, students))\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11375", "name": "LeetCode 2038: Remove Colored Pieces If Both Neighbors Are The Same Color"}{"type": "message", "message": {"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 Colored Pieces if Both Neighbors are the Same Color (Difficulty: Medium)\nTags: Math, String, Greedy, Game Theory\n\nThere are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece.\nAlice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.\nAssuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins.\n\nExample 1:\nInput: colors = \"AAABABB\"\nOutput: true\nExplanation:\nAAABABB -> AABABB\nAlice moves first.\nShe removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.\n\nNow it's Bob's turn.\nBob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.\nThus, Alice wins, so return true.\n\nExample 2:\nInput: colors = \"AA\"\nOutput: false\nExplanation:\nAlice has her turn first.\nThere are only two 'A's and both are on the edge of the line, so she cannot move on her turn.\nThus, Bob wins, so return false.\n\nExample 3:\nInput: colors = \"ABBBBBBBAAA\"\nOutput: false\nExplanation:\nABBBBBBBAAA -> ABBBBBBBAA\nAlice moves first.\nHer only option is to remove the second to last 'A' from the right.\n\nABBBBBBBAA -> ABBBBBBAA\nNext is Bob's turn.\nHe has many options for which 'B' piece to remove. He can pick any.\n\nOn Alice's second turn, she has no more pieces that she can remove.\nThus, Bob wins, so return false.\n\nConstraints:\n- 1 <= colors.length <= 10^5\n- colors consists of only the letters 'A' and 'B'"}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def winnerOfGame(self, colors):\n \"\"\"\n :type colors: str\n :rtype: bool\n \"\"\"\n cnt1 = cnt2 = 0\n for i in range(1, len(colors)-1):\n if not (colors[i-1] == colors[i] == colors[i+1]):\n continue\n if colors[i] == 'A':\n cnt1 += 1\n else:\n cnt2 += 1\n return cnt1 > cnt2\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11376", "name": "LeetCode 2039: The Time When The Network Becomes Idle"}{"type": "message", "message": {"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 Time When the Network Becomes Idle (Difficulty: Medium)\nTags: Array, Breadth-First Search, Graph\n\nThere is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n.\nAll servers are connected, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels.\nThe server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally, so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through.\nAt the beginning of second 0, each data server sends its message to be processed. Starting from second 1, at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server:\nThe network becomes idle when there are no messages passing between servers or arriving at servers.\nReturn the earliest second starting from which the network becomes idle.\n\nExample 1:\nInput: edges = [[0,1],[1,2]], patience = [0,2,1]\nOutput: 8\nExplanation:\nAt (the beginning of) second 0,\n- Data server 1 sends its message (denoted 1A) to the master server.\n- Data server 2 sends its message (denoted 2A) to the master server.\n\nAt second 1,\n- Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back.\n- Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message.\n- Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B).\n\nAt second 2,\n- The reply 1A arrives at server 1. No more resending will occur from server 1.\n- Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back.\n- Server 2 resends the message (denoted 2C).\n...\nAt second 4,\n- The reply 2A arrives at server 2. No more resending will occur from server 2.\n...\nAt second 7, reply 2D arrives at server 2.\n\nStarting from the beginning of the second 8, there are no messages passing between servers or arriving at servers.\nThis is the time when the network becomes idle.\n\nExample 2:\nInput: edges = [[0,1],[0,2],[1,2]], patience = [0,10,10]\nOutput: 3\nExplanation: Data servers 1 and 2 receive a reply back at the beginning of second 2.\nFrom the beginning of the second 3, the network becomes idle.\n\nConstraints:\n- n == patience.length\n- 2 <= n <= 10^5\n- patience[0] == 0\n- 1 <= patience[i] <= 10^5 for 1 <= i < n\n- 1 <= edges.length <= min(105, n * (n - 1) / 2)\n- edges[i].length == 2\n- 0 <= ui, vi < n\n- ui != vi\n- There are no duplicate edges.\n- Each server can directly or indirectly reach another server."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(|V| + |E|) = O(|E|) since graph is connected, O(|E|) >= O(|V|) \n# Space: O(|V| + |E|) = O(|E|)\n\nclass Solution(object):\n def networkBecomesIdle(self, edges, patience):\n \"\"\"\n :type edges: List[List[int]]\n :type patience: List[int]\n :rtype: int\n \"\"\"\n adj = [[] for _ in range(len(patience))]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n q = [0]\n lookup = [False]*len(patience)\n lookup[0] = True\n step = 1\n result = 0\n while q:\n new_q = []\n for u in q:\n for v in adj[u]:\n if lookup[v]:\n continue\n lookup[v] = True\n new_q.append(v)\n result = max(result, ((step*2)-1)//patience[v]*patience[v] + (step*2))\n q = new_q\n step += 1\n return 1+result\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11377", "name": "LeetCode 2040: Kth Smallest Product Of Two Sorted 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: Kth Smallest Product of Two Sorted Arrays (Difficulty: Hard)\nTags: Array, Binary Search\n\nExample 1:\nInput: nums1 = [2,5], nums2 = [3,4], k = 2\nOutput: 8\nExplanation: The 2 smallest products are:\n- nums1[0] * nums2[0] = 2 * 3 = 6\n- nums1[0] * nums2[1] = 2 * 4 = 8\nThe 2nd smallest product is 8.\n\nExample 2:\nInput: nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6\nOutput: 0\nExplanation: The 6 smallest products are:\n- nums1[0] * nums2[1] = (-4) * 4 = -16\n- nums1[0] * nums2[0] = (-4) * 2 = -8\n- nums1[1] * nums2[1] = (-2) * 4 = -8\n- nums1[1] * nums2[0] = (-2) * 2 = -4\n- nums1[2] * nums2[0] = 0 * 2 = 0\n- nums1[2] * nums2[1] = 0 * 4 = 0\nThe 6th smallest product is 0.\n\nExample 3:\nInput: nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3\nOutput: -6\nExplanation: The 3 smallest products are:\n- nums1[0] * nums2[4] = (-2) * 5 = -10\n- nums1[0] * nums2[3] = (-2) * 4 = -8\n- nums1[4] * nums2[0] = 2 * (-3) = -6\nThe 3rd smallest product is -6.\n\nConstraints:\n- 1 <= nums1.length, nums2.length <= 5 * 10^4\n- -10^5 <= nums1[i], nums2[j] <= 10^5\n- 1 <= k <= nums1.length * nums2.length\n- nums1 and nums2 are sorted."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O((m + n) * logr), r is the range size of [min(products), max(products)]\n# Space: O(1)\n\nclass Solution(object):\n def kthSmallestProduct(self, nums1, nums2, k):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n def check(nums1, nums2, k, neg_cnt, target):\n cnt = 0\n left, right = 0, len(nums2)-1\n direction = reversed if target >= 0 else lambda x: x\n for i in direction(range(neg_cnt)):\n while left < len(nums2) and nums1[i]*nums2[left] > target:\n left += 1\n cnt += (len(nums2)-1)-left+1\n direction = (lambda x: x) if target >= 0 else reversed\n for i in direction(range(neg_cnt, len(nums1))): \n if nums1[i] == 0: \n if target >= 0:\n cnt += len(nums2)\n continue\n while right >= 0 and nums1[i]*nums2[right] > target:\n right -= 1\n cnt += right-0+1\n return cnt >= k\n\n neg_cnt = sum(x < 0 for x in nums1)\n left = min(nums1[i]*nums2[j] for i in (0, -1) for j in (0, -1))\n right = max(nums1[i]*nums2[j] for i in (0, -1) for j in (0, -1))\n while left <= right:\n mid = left + (right-left)//2\n if check(nums1, nums2, k, neg_cnt, mid):\n right = mid-1\n else:\n left = mid+1\n return left\n"}}1234{"type": "session", "harness": "opencode", "id": "cp-11378", "name": "LeetCode 2042: Check If Numbers Are Ascending 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 Numbers Are Ascending in a Sentence (Difficulty: Easy)\nTags: String\n\nA sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters.\nGiven a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s).\nReturn true if so, or false otherwise.\n\nExample 1:\nInput: s = \"1 box has 3 blue 4 red 6 green and 12 yellow marbles\"\nOutput: true\nExplanation: The numbers in s are: 1, 3, 4, 6, 12.\nThey are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12.\n\nExample 2:\nInput: s = \"hello world 5 x 5\"\nOutput: false\nExplanation: The numbers in s are: 5, 5. They are not strictly increasing.\n\nExample 3:\nInput: s = \"sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s\"\nOutput: false\nExplanation: The numbers in s are: 7, 51, 50, 60. They are not strictly increasing.\n\nConstraints:\n- 3 <= s.length <= 200\n- s consists of lowercase English letters, spaces, and digits from 0 to 9, inclusive.\n- The number of tokens in s is between 2 and 100, inclusive.\n- The tokens in s are separated by a single space.\n- There are at least two numbers in s.\n- Each number in s is a positive number less than 100, with no leading zeros.\n- s contains no leading or trailing spaces."}}{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def areNumbersAscending(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n prev = curr = -1\n for i, c in enumerate(s):\n if c.isdigit():\n curr = max(curr, 0)*10+int(c)\n continue\n if prev != -1 and curr != -1 and prev >= curr:\n return False\n if curr != -1:\n prev = curr\n curr = -1 \n return curr == -1 or prev < curr\n\n\n# Time: O(n)\n# Space: O(n)\nclass Solution2(object):\n def areNumbersAscending(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n nums = [int(x) for x in s.split() if x.isdigit()]\n return all(nums[i] < nums[i+1] for i in range(len(nums)-1))\n"}}cp/cp-11316.jsonlAdded+4
cp/cp-11318.jsonlAdded+4
cp/cp-11319.jsonlAdded+4
cp/cp-11320.jsonlAdded+4
cp/cp-11321.jsonlAdded+4
cp/cp-11323.jsonlAdded+4
cp/cp-11324.jsonlAdded+4
cp/cp-11325.jsonlAdded+4
cp/cp-11328.jsonlAdded+4
cp/cp-11329.jsonlAdded+4
cp/cp-11330.jsonlAdded+4
cp/cp-11332.jsonlAdded+4
cp/cp-11333.jsonlAdded+4
cp/cp-11334.jsonlAdded+4
cp/cp-11335.jsonlAdded+4
cp/cp-11336.jsonlAdded+4
cp/cp-11337.jsonlAdded+4
cp/cp-11338.jsonlAdded+4
cp/cp-11339.jsonlAdded+4
cp/cp-11342.jsonlAdded+4
cp/cp-11343.jsonlAdded+4
cp/cp-11344.jsonlAdded+4
cp/cp-11346.jsonlAdded+4
cp/cp-11347.jsonlAdded+4
cp/cp-11348.jsonlAdded+4
cp/cp-11349.jsonlAdded+4
cp/cp-11351.jsonlAdded+4
cp/cp-11352.jsonlAdded+4
cp/cp-11353.jsonlAdded+4
cp/cp-11355.jsonlAdded+4
cp/cp-11356.jsonlAdded+4
cp/cp-11357.jsonlAdded+4
cp/cp-11358.jsonlAdded+4
cp/cp-11360.jsonlAdded+4
cp/cp-11361.jsonlAdded+4
cp/cp-11362.jsonlAdded+4
cp/cp-11363.jsonlAdded+4
cp/cp-11364.jsonlAdded+4
cp/cp-11365.jsonlAdded+4
cp/cp-11366.jsonlAdded+4
cp/cp-11367.jsonlAdded+4
cp/cp-11369.jsonlAdded+4
cp/cp-11370.jsonlAdded+4
cp/cp-11371.jsonlAdded+4
cp/cp-11372.jsonlAdded+4
cp/cp-11374.jsonlAdded+4
cp/cp-11375.jsonlAdded+4
cp/cp-11376.jsonlAdded+4
cp/cp-11377.jsonlAdded+4
cp/cp-11378.jsonlAdded+4