diff --git "a/data/leetcode.jsonl" "b/data/leetcode.jsonl" new file mode 100644--- /dev/null +++ "b/data/leetcode.jsonl" @@ -0,0 +1,210 @@ +{"task_num": 4, "task_title": "Median of Two Sorted Arrays", "difficulty": 3, "func_name": "findMedianSortedArrays", "description": "Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively,\nreturn the median of the two sorted arrays.\n\nThe overall run time complexity should be `O(log (m+n))`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n n1 = len(nums1)\n n2 = len(nums2)\n if n1 > n2:\n return self.findMedianSortedArrays(nums2, nums1)\n\n l = 0\n r = n1\n\n while l <= r:\n partition1 = (l + r) // 2\n partition2 = (n1 + n2 + 1) // 2 - partition1\n maxLeft1 = -2**31 if partition1 == 0 else nums1[partition1 - 1]\n maxLeft2 = -2**31 if partition2 == 0 else nums2[partition2 - 1]\n minRight1 = 2**31 - 1 if partition1 == n1 else nums1[partition1]\n minRight2 = 2**31 - 1 if partition2 == n2 else nums2[partition2]\n if maxLeft1 <= minRight2 and maxLeft2 <= minRight1:\n if (n1 + n2) % 2 == 0:\n return (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) * 0.5\n else:\n return max(maxLeft1, maxLeft2)\n elif maxLeft1 > minRight2:\n r = partition1 - 1\n else:\n l = partition1 + 1\n", "java_solution": "class Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n final int n1 = nums1.length;\n final int n2 = nums2.length;\n if (n1 > n2)\n return findMedianSortedArrays(nums2, nums1);\n\n int l = 0;\n int r = n1;\n\n while (l <= r) {\n final int partition1 = (l + r) / 2;\n final int partition2 = (n1 + n2 + 1) / 2 - partition1;\n final int maxLeft1 = partition1 == 0 ? Integer.MIN_VALUE : nums1[partition1 - 1];\n final int maxLeft2 = partition2 == 0 ? Integer.MIN_VALUE : nums2[partition2 - 1];\n final int minRight1 = partition1 == n1 ? Integer.MAX_VALUE : nums1[partition1];\n final int minRight2 = partition2 == n2 ? Integer.MAX_VALUE : nums2[partition2];\n if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1)\n return (n1 + n2) % 2 == 0\n ? (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) * 0.5\n : Math.max(maxLeft1, maxLeft2);\n else if (maxLeft1 > minRight2)\n r = partition1 - 1;\n else\n l = partition1 + 1;\n }\n\n throw new IllegalArgumentException();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n double findMedianSortedArrays(vector& nums1, vector& nums2) {\n const int n1 = nums1.size();\n const int n2 = nums2.size();\n if (n1 > n2)\n return findMedianSortedArrays(nums2, nums1);\n\n int l = 0;\n int r = n1;\n\n while (l <= r) {\n const int partition1 = (l + r) / 2;\n const int partition2 = (n1 + n2 + 1) / 2 - partition1;\n const int maxLeft1 = partition1 == 0 ? INT_MIN : nums1[partition1 - 1];\n const int maxLeft2 = partition2 == 0 ? INT_MIN : nums2[partition2 - 1];\n const int minRight1 = partition1 == n1 ? INT_MAX : nums1[partition1];\n const int minRight2 = partition2 == n2 ? INT_MAX : nums2[partition2];\n if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1)\n return (n1 + n2) % 2 == 0\n ? (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) * 0.5\n : max(maxLeft1, maxLeft2);\n else if (maxLeft1 > minRight2)\n r = partition1 - 1;\n else\n l = partition1 + 1;\n }\n\n throw;\n }\n};\n"} +{"task_num": 10, "task_title": "Regular Expression Matching", "difficulty": 3, "func_name": "isMatch", "description": "Given an input string `s` and a pattern `p`, implement regular expression\nmatching with support for `'.'` and `'*'` where:\n\n* `'.'` Matches any single character.\u200b\u200b\u200b\u200b\n* `'*'` Matches zero or more of the preceding element.\n\nThe matching should cover the entire input string (not partial).\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n m = len(s)\n n = len(p)\n dp = [[False] * (n + 1) for _ in range(m + 1)]\n dp[0][0] = True\n\n def isMatch(i: int, j: int) -> bool:\n return j >= 0 and p[j] == '.' or s[i] == p[j]\n\n for j, c in enumerate(p):\n if c == '*' and dp[0][j - 1]:\n dp[0][j + 1] = True\n\n for i in range(m):\n for j in range(n):\n if p[j] == '*':\n noRepeat = dp[i + 1][j - 1]\n doRepeat = isMatch(i, j - 1) and dp[i][j + 1]\n dp[i + 1][j + 1] = noRepeat or doRepeat\n elif isMatch(i, j):\n dp[i + 1][j + 1] = dp[i][j]\n\n return dp[m][n]\n", "java_solution": "class Solution {\n public boolean isMatch(String s, String p) {\n final int m = s.length();\n final int n = p.length();\n // dp[i][j] := true if s[0..i) matches p[0..j)\n boolean[][] dp = new boolean[m + 1][n + 1];\n dp[0][0] = true;\n\n for (int j = 0; j < p.length(); ++j)\n if (p.charAt(j) == '*' && dp[0][j - 1])\n dp[0][j + 1] = true;\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (p.charAt(j) == '*') {\n // The minimum index of '*' is 1.\n final boolean noRepeat = dp[i + 1][j - 1];\n final boolean doRepeat = isMatch(s, i, p, j - 1) && dp[i][j + 1];\n dp[i + 1][j + 1] = noRepeat || doRepeat;\n } else if (isMatch(s, i, p, j)) {\n dp[i + 1][j + 1] = dp[i][j];\n }\n\n return dp[m][n];\n }\n\n private boolean isMatch(final String s, int i, final String p, int j) {\n return j >= 0 && p.charAt(j) == '.' || s.charAt(i) == p.charAt(j);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool isMatch(string s, string p) {\n const int m = s.length();\n const int n = p.length();\n // dp[i][j] := true if s[0..i) matches p[0..j)\n vector> dp(m + 1, vector(n + 1));\n dp[0][0] = true;\n\n auto isMatch = [&](int i, int j) -> bool {\n return j >= 0 && p[j] == '.' || s[i] == p[j];\n };\n\n for (int j = 0; j < p.length(); ++j)\n if (p[j] == '*' && dp[0][j - 1])\n dp[0][j + 1] = true;\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (p[j] == '*') {\n // The minimum index of '*' is 1.\n const bool noRepeat = dp[i + 1][j - 1];\n const bool doRepeat = isMatch(i, j - 1) && dp[i][j + 1];\n dp[i + 1][j + 1] = noRepeat || doRepeat;\n } else if (isMatch(i, j)) {\n dp[i + 1][j + 1] = dp[i][j];\n }\n\n return dp[m][n];\n }\n};\n"} +{"task_num": 15, "task_title": "3Sum", "difficulty": 2, "func_name": "threeSum", "description": "Given an integer array nums, return all the triplets `[nums[i], nums[j],\nnums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] +\nnums[k] == 0`.\n\nNotice that the solution set must not contain duplicate triplets.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n if len(nums) < 3:\n return []\n\n ans = []\n\n nums.sort()\n\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n\n l = i + 1\n r = len(nums) - 1\n while l < r:\n summ = nums[i] + nums[l] + nums[r]\n if summ == 0:\n ans.append((nums[i], nums[l], nums[r]))\n l += 1\n r -= 1\n while nums[l] == nums[l - 1] and l < r:\n l += 1\n while nums[r] == nums[r + 1] and l < r:\n r -= 1\n elif summ < 0:\n l += 1\n else:\n r -= 1\n\n return ans\n", "java_solution": "class Solution {\n public List> threeSum(int[] nums) {\n if (nums.length < 3)\n return new ArrayList<>();\n\n List> ans = new ArrayList<>();\n\n Arrays.sort(nums);\n\n for (int i = 0; i + 2 < nums.length; ++i) {\n if (i > 0 && nums[i] == nums[i - 1])\n continue;\n // Choose nums[i] as the first number in the triplet, then search the\n // remaining numbers in [i + 1, n - 1].\n int l = i + 1;\n int r = nums.length - 1;\n while (l < r) {\n final int sum = nums[i] + nums[l] + nums[r];\n if (sum == 0) {\n ans.add(Arrays.asList(nums[i], nums[l++], nums[r--]));\n while (l < r && nums[l] == nums[l - 1])\n ++l;\n while (l < r && nums[r] == nums[r + 1])\n --r;\n } else if (sum < 0) {\n ++l;\n } else {\n --r;\n }\n }\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector> threeSum(vector& nums) {\n if (nums.size() < 3)\n return {};\n\n vector> ans;\n\n ranges::sort(nums);\n\n for (int i = 0; i + 2 < nums.size(); ++i) {\n if (i > 0 && nums[i] == nums[i - 1])\n continue;\n // Choose nums[i] as the first number in the triplet, then search the\n // remaining numbers in [i + 1, n - 1].\n int l = i + 1;\n int r = nums.size() - 1;\n while (l < r) {\n const int sum = nums[i] + nums[l] + nums[r];\n if (sum == 0) {\n ans.push_back({nums[i], nums[l++], nums[r--]});\n while (l < r && nums[l] == nums[l - 1])\n ++l;\n while (l < r && nums[r] == nums[r + 1])\n --r;\n } else if (sum < 0) {\n ++l;\n } else {\n --r;\n }\n }\n }\n\n return ans;\n }\n};\n"} +{"task_num": 44, "task_title": "Wildcard Matching", "difficulty": 3, "func_name": "isMatch", "description": "Given an input string (`s`) and a pattern (`p`), implement wildcard pattern\nmatching with support for `'?'` and `'*'` where:\n\n* `'?'` Matches any single character.\n* `'*'` Matches any sequence of characters (including the empty sequence).\n\nThe matching should cover the entire input string (not partial).\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n m = len(s)\n n = len(p)\n dp = [[False] * (n + 1) for _ in range(m + 1)]\n dp[0][0] = True\n\n def isMatch(i: int, j: int) -> bool:\n return i >= 0 and p[j] == '?' or s[i] == p[j]\n\n for j, c in enumerate(p):\n if c == '*':\n dp[0][j + 1] = dp[0][j]\n\n for i in range(m):\n for j in range(n):\n if p[j] == '*':\n matchEmpty = dp[i + 1][j]\n matchSome = dp[i][j + 1]\n dp[i + 1][j + 1] = matchEmpty or matchSome\n elif isMatch(i, j):\n dp[i + 1][j + 1] = dp[i][j]\n\n return dp[m][n]\n", "java_solution": "class Solution {\n public boolean isMatch(String s, String p) {\n final int m = s.length();\n final int n = p.length();\n // dp[i][j] := true if s[0..i) matches p[0..j)\n boolean[][] dp = new boolean[m + 1][n + 1];\n dp[0][0] = true;\n\n for (int j = 0; j < p.length(); ++j)\n if (p.charAt(j) == '*')\n dp[0][j + 1] = dp[0][j];\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (p.charAt(j) == '*') {\n final boolean matchEmpty = dp[i + 1][j];\n final boolean matchSome = dp[i][j + 1];\n dp[i + 1][j + 1] = matchEmpty || matchSome;\n } else if (isMatch(s, i, p, j)) {\n dp[i + 1][j + 1] = dp[i][j];\n }\n\n return dp[m][n];\n }\n\n private boolean isMatch(final String s, int i, final String p, int j) {\n return j >= 0 && p.charAt(j) == '?' || s.charAt(i) == p.charAt(j);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool isMatch(string s, string p) {\n const int m = s.length();\n const int n = p.length();\n // dp[i][j] := true if s[0..i) matches p[0..j)\n vector> dp(m + 1, vector(n + 1));\n dp[0][0] = true;\n\n auto isMatch = [&](int i, int j) -> bool {\n return j >= 0 && p[j] == '?' || s[i] == p[j];\n };\n\n for (int j = 0; j < p.length(); ++j)\n if (p[j] == '*')\n dp[0][j + 1] = dp[0][j];\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (p[j] == '*') {\n const bool matchEmpty = dp[i + 1][j];\n const bool matchSome = dp[i][j + 1];\n dp[i + 1][j + 1] = matchEmpty || matchSome;\n } else if (isMatch(i, j)) {\n dp[i + 1][j + 1] = dp[i][j];\n }\n\n return dp[m][n];\n }\n};\n"} +{"task_num": 54, "task_title": "Spiral Matrix", "difficulty": 2, "func_name": "spiralOrder", "description": "Given an `m x n` `matrix`, return all elements of the `matrix` in spiral\norder.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n if not matrix:\n return []\n\n m = len(matrix)\n n = len(matrix[0])\n ans = []\n r1 = 0\n c1 = 0\n r2 = m - 1\n c2 = n - 1\n\n while len(ans) < m * n:\n j = c1\n while j <= c2 and len(ans) < m * n:\n ans.append(matrix[r1][j])\n j += 1\n i = r1 + 1\n while i <= r2 - 1 and len(ans) < m * n:\n ans.append(matrix[i][c2])\n i += 1\n j = c2\n while j >= c1 and len(ans) < m * n:\n ans.append(matrix[r2][j])\n j -= 1\n i = r2 - 1\n while i >= r1 + 1 and len(ans) < m * n:\n ans.append(matrix[i][c1])\n i -= 1\n r1 += 1\n c1 += 1\n r2 -= 1\n c2 -= 1\n\n return ans\n", "java_solution": "class Solution {\n public List spiralOrder(int[][] matrix) {\n if (matrix.length == 0)\n return new ArrayList<>();\n\n final int m = matrix.length;\n final int n = matrix[0].length;\n List ans = new ArrayList<>();\n int r1 = 0;\n int c1 = 0;\n int r2 = m - 1;\n int c2 = n - 1;\n\n // Repeatedly add matrix[r1..r2][c1..c2] to `ans`.\n while (ans.size() < m * n) {\n for (int j = c1; j <= c2 && ans.size() < m * n; ++j)\n ans.add(matrix[r1][j]);\n for (int i = r1 + 1; i <= r2 - 1 && ans.size() < m * n; ++i)\n ans.add(matrix[i][c2]);\n for (int j = c2; j >= c1 && ans.size() < m * n; --j)\n ans.add(matrix[r2][j]);\n for (int i = r2 - 1; i >= r1 + 1 && ans.size() < m * n; --i)\n ans.add(matrix[i][c1]);\n ++r1;\n ++c1;\n --r2;\n --c2;\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector spiralOrder(vector>& matrix) {\n if (matrix.empty())\n return {};\n\n const int m = matrix.size();\n const int n = matrix[0].size();\n vector ans;\n int r1 = 0;\n int c1 = 0;\n int r2 = m - 1;\n int c2 = n - 1;\n\n // Repeatedly add matrix[r1..r2][c1..c2] to `ans`.\n while (ans.size() < m * n) {\n for (int j = c1; j <= c2 && ans.size() < m * n; ++j)\n ans.push_back(matrix[r1][j]);\n for (int i = r1 + 1; i <= r2 - 1 && ans.size() < m * n; ++i)\n ans.push_back(matrix[i][c2]);\n for (int j = c2; j >= c1 && ans.size() < m * n; --j)\n ans.push_back(matrix[r2][j]);\n for (int i = r2 - 1; i >= r1 + 1 && ans.size() < m * n; --i)\n ans.push_back(matrix[i][c1]);\n ++r1, ++c1, --r2, --c2;\n }\n\n return ans;\n }\n};\n"} +{"task_num": 65, "task_title": "Valid Number", "difficulty": 3, "func_name": "isNumber", "description": "A valid number can be split up into these components (in order):\n\n1. A decimal number or an integer.\n2. (Optional) An `'e'` or `'E'`, followed by an integer.\n\nA decimal number can be split up into these components (in order):\n\n1. (Optional) A sign character (either `'+'` or `'-'`).\n2. One of the following formats: \n1. One or more digits, followed by a dot `'.'`.\n2. One or more digits, followed by a dot `'.'`, followed by one or more digits.\n3. A dot `'.'`, followed by one or more digits.\n\nAn integer can be split up into these components (in order):\n\n1. (Optional) A sign character (either `'+'` or `'-'`).\n2. One or more digits.\n\nFor example, all the following are valid numbers: `[\"2\", \"0089\", \"-0.1\",\n\"+3.14\", \"4.\", \"-.9\", \"2e10\", \"-90E3\", \"3e+7\", \"+6e-1\", \"53.5e93\",\n\"-123.456e789\"]`, while the following are not valid numbers: `[\"abc\", \"1a\",\n\"1e\", \"e3\", \"99e2.5\", \"--6\", \"-+3\", \"95a54e53\"]`.\n\nGiven a string `s`, return `true` if `s` is a valid number.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def isNumber(self, s: str) -> bool:\n s = s.strip()\n if not s:\n return False\n\n seenNum = False\n seenDot = False\n seenE = False\n\n for i, c in enumerate(s):\n if c == '.':\n if seenDot or seenE:\n return False\n seenDot = True\n elif c == 'e' or c == 'E':\n if seenE or not seenNum:\n return False\n seenE = True\n seenNum = False\n elif c in '+-':\n if i > 0 and s[i - 1] not in 'eE':\n return False\n seenNum = False\n else:\n if not c.isdigit():\n return False\n seenNum = True\n\n return seenNum\n", "java_solution": "class Solution {\n public boolean isNumber(String s) {\n s = s.trim();\n if (s.isEmpty())\n return false;\n\n boolean seenNum = false;\n boolean seenDot = false;\n boolean seenE = false;\n\n for (int i = 0; i < s.length(); ++i) {\n switch (s.charAt(i)) {\n case '.':\n if (seenDot || seenE)\n return false;\n seenDot = true;\n break;\n case 'e':\n case 'E':\n if (seenE || !seenNum)\n return false;\n seenE = true;\n seenNum = false;\n break;\n case '+':\n case '-':\n if (i > 0 && s.charAt(i - 1) != 'e' && s.charAt(i - 1) != 'E')\n return false;\n seenNum = false;\n break;\n default:\n if (!Character.isDigit(s.charAt(i)))\n return false;\n seenNum = true;\n }\n }\n\n return seenNum;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool isNumber(string s) {\n trim(s);\n if (s.empty())\n return false;\n\n bool seenNum = false;\n bool seenDot = false;\n bool seenE = false;\n\n for (int i = 0; i < s.length(); ++i) {\n switch (s[i]) {\n case '.':\n if (seenDot || seenE)\n return false;\n seenDot = true;\n break;\n case 'e':\n case 'E':\n if (seenE || !seenNum)\n return false;\n seenE = true;\n seenNum = false;\n break;\n case '+':\n case '-':\n if (i > 0 && s[i - 1] != 'e' && s[i - 1] != 'E')\n return false;\n seenNum = false;\n break;\n default:\n if (!isdigit(s[i]))\n return false;\n seenNum = true;\n }\n }\n\n return seenNum;\n }\n\n private:\n void trim(string& s) {\n s.erase(0, s.find_first_not_of(' '));\n s.erase(s.find_last_not_of(' ') + 1);\n }\n};\n"} +{"task_num": 73, "task_title": "Set Matrix Zeroes", "difficulty": 2, "func_name": "setZeroes", "description": "Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire\nrow and column to `0`'s.\n\nYou must do it in place.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n m = len(matrix)\n n = len(matrix[0])\n shouldFillFirstRow = 0 in matrix[0]\n shouldFillFirstCol = 0 in list(zip(*matrix))[0]\n\n for i in range(1, m):\n for j in range(1, n):\n if matrix[i][j] == 0:\n matrix[i][0] = 0\n matrix[0][j] = 0\n\n for i in range(1, m):\n for j in range(1, n):\n if matrix[i][0] == 0 or matrix[0][j] == 0:\n matrix[i][j] = 0\n\n if shouldFillFirstRow:\n matrix[0] = [0] * n\n\n if shouldFillFirstCol:\n for row in matrix:\n row[0] = 0\n", "java_solution": "class Solution {\n public void setZeroes(int[][] matrix) {\n final int m = matrix.length;\n final int n = matrix[0].length;\n boolean shouldFillFirstRow = false;\n boolean shouldFillFirstCol = false;\n\n for (int j = 0; j < n; ++j)\n if (matrix[0][j] == 0) {\n shouldFillFirstRow = true;\n break;\n }\n\n for (int i = 0; i < m; ++i)\n if (matrix[i][0] == 0) {\n shouldFillFirstCol = true;\n break;\n }\n\n // Store the information in the first row and the first column.\n for (int i = 1; i < m; ++i)\n for (int j = 1; j < n; ++j)\n if (matrix[i][j] == 0) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n\n // Fill 0s for the matrix except the first row and the first column.\n for (int i = 1; i < m; ++i)\n for (int j = 1; j < n; ++j)\n if (matrix[i][0] == 0 || matrix[0][j] == 0)\n matrix[i][j] = 0;\n\n // Fill 0s for the first row if needed.\n if (shouldFillFirstRow)\n for (int j = 0; j < n; ++j)\n matrix[0][j] = 0;\n\n // Fill 0s for the first column if needed.\n if (shouldFillFirstCol)\n for (int i = 0; i < m; ++i)\n matrix[i][0] = 0;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n void setZeroes(vector>& matrix) {\n const int m = matrix.size();\n const int n = matrix[0].size();\n bool shouldFillFirstRow = false;\n bool shouldFillFirstCol = false;\n\n for (int j = 0; j < n; ++j)\n if (matrix[0][j] == 0) {\n shouldFillFirstRow = true;\n break;\n }\n\n for (int i = 0; i < m; ++i)\n if (matrix[i][0] == 0) {\n shouldFillFirstCol = true;\n break;\n }\n\n // Store the information in the first row and the first column.\n for (int i = 1; i < m; ++i)\n for (int j = 1; j < n; ++j)\n if (matrix[i][j] == 0) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n\n // Fill 0s for the matrix except the first row and the first column.\n for (int i = 1; i < m; ++i)\n for (int j = 1; j < n; ++j)\n if (matrix[i][0] == 0 || matrix[0][j] == 0)\n matrix[i][j] = 0;\n\n // Fill 0s for the first row if needed.\n if (shouldFillFirstRow)\n for (int j = 0; j < n; ++j)\n matrix[0][j] = 0;\n\n // Fill 0s for the first column if needed.\n if (shouldFillFirstCol)\n for (int i = 0; i < m; ++i)\n matrix[i][0] = 0;\n }\n};\n"} +{"task_num": 97, "task_title": "Interleaving String", "difficulty": 2, "func_name": "isInterleave", "description": "Given strings `s1`, `s2`, and `s3`, find whether `s3` is formed by an\ninterleaving of `s1` and `s2`.\n\nAn interleaving of two strings `s` and `t` is a configuration where `s` and\n`t` are divided into `n` and `m` substrings respectively, such that:\n\n* `s = s1 + s2 + ... + sn`\n* `t = t1 + t2 + ... + tm`\n* `|n - m| <= 1`\n* The interleaving is `s1 + t1 + s2 + t2 + s3 + t3 + ...` or `t1 + s1 + t2 + s2 + t3 + s3 + ...`\n\nNote: `a + b` is the concatenation of strings `a` and `b`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n m = len(s1)\n n = len(s2)\n if m + n != len(s3):\n return False\n\n dp=[]\n for _ in range(m + 1):\n dp.append([False] * (n + 1))\n dp[0][0] = True\n\n for i in range(1, m + 1):\n dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1]\n\n for j in range(1, n + 1):\n dp[0][j] = dp[0][j - 1] and s2[j - 1] == s3[j - 1]\n\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n dp[i][j] = (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or (dp[i][j - 1] and s2[j - 1] == s3[i + j - 1])\n\n return dp[m][n]\n", "java_solution": "class Solution {\n public boolean isInterleave(String s1, String s2, String s3) {\n final int m = s1.length();\n final int n = s2.length();\n if (m + n != s3.length())\n return false;\n\n // dp[i][j] := true if s3[0..i + j) is formed by the interleaving of\n // s1[0..i) and s2[0..j)\n boolean[][] dp = new boolean[m + 1][n + 1];\n dp[0][0] = true;\n\n for (int i = 1; i <= m; ++i)\n dp[i][0] = dp[i - 1][0] && s1.charAt(i - 1) == s3.charAt(i - 1);\n\n for (int j = 1; j <= n; ++j)\n dp[0][j] = dp[0][j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1);\n\n for (int i = 1; i <= m; ++i)\n for (int j = 1; j <= n; ++j)\n dp[i][j] = dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1) ||\n dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1);\n\n return dp[m][n];\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool isInterleave(string s1, string s2, string s3) {\n const int m = s1.length();\n const int n = s2.length();\n if (m + n != s3.length())\n return false;\n\n // dp[i][j] := true if s3[0..i + j) is formed by the interleaving of\n // s1[0..i) and s2[0..j)\n vector> dp(m + 1, vector(n + 1));\n dp[0][0] = true;\n\n for (int i = 1; i <= m; ++i)\n dp[i][0] = dp[i - 1][0] && s1[i - 1] == s3[i - 1];\n\n for (int j = 1; j <= n; ++j)\n dp[0][j] = dp[0][j - 1] && s2[j - 1] == s3[j - 1];\n\n for (int i = 1; i <= m; ++i)\n for (int j = 1; j <= n; ++j)\n dp[i][j] = dp[i - 1][j] && s1[i - 1] == s3[i + j - 1] ||\n dp[i][j - 1] && s2[j - 1] == s3[i + j - 1];\n\n return dp[m][n];\n }\n};\n"} +{"task_num": 126, "task_title": "Word Ladder II", "difficulty": 3, "func_name": "findLadders", "description": "A transformation sequence from word `beginWord` to word `endWord` using a\ndictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... ->\nsk` such that:\n\n* Every adjacent pair of words differs by a single letter.\n* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.\n* `sk == endWord`\n\nGiven two words, `beginWord` and `endWord`, and a dictionary `wordList`,\nreturn all the shortest transformation sequences from `beginWord` to\n`endWord`, or an empty list if no such sequence exists. Each sequence should\nbe returned as a list of the words `[beginWord, s1, s2, ..., sk]`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator, Set\n\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n from collections import deque\n def connected(a: str, b: str) -> bool:\n k = 0\n for i in range(len(a)):\n if a[i] != b[i]:\n k += 1\n return k == 1\n\n if endWord not in wordList:\n return []\n\n visited = set([beginWord])\n\n q = deque([beginWord])\n nodes = []\n find = False\n\n while q and not find:\n nodes.append(q.copy())\n n = len(q)\n for _ in range(n):\n word = q.popleft()\n for item in wordList:\n if item in visited:\n continue\n if not connected(word, item):\n continue\n if item == endWord:\n find = True\n break\n visited.add(item)\n q.append(item)\n if find:\n break\n\n if not find:\n return []\n\n ans = []\n\n def backtracking(word, level: int, steps: List[str]):\n if word == beginWord:\n ans.append(steps[::-1])\n return\n if level < 0:\n return\n for item in nodes[level]:\n if connected(item, word):\n steps.append(item)\n backtracking(item, level-1, steps)\n steps.pop()\n\n backtracking(endWord, len(nodes)-1, [endWord])\n return ans\n", "java_solution": "class Solution {\n public List> findLadders(String beginWord, String endWord, List wordList) {\n Set wordSet = new HashSet<>(wordList);\n if (!wordSet.contains(endWord))\n return new ArrayList<>();\n\n // {\"hit\": [\"hot\"], \"hot\": [\"dot\", \"lot\"], ...}\n Map> graph = new HashMap<>();\n\n // Build the graph from the beginWord to the endWord.\n if (!bfs(beginWord, endWord, wordSet, graph))\n return new ArrayList<>();\n\n List> ans = new ArrayList<>();\n List path = new ArrayList<>(List.of(beginWord));\n dfs(graph, beginWord, endWord, path, ans);\n return ans;\n }\n\n private boolean bfs(final String beginWord, final String endWord, Set wordSet,\n Map> graph) {\n Set currentLevelWords = new HashSet<>();\n currentLevelWords.add(beginWord);\n boolean reachEndWord = false;\n\n while (!currentLevelWords.isEmpty()) {\n for (final String word : currentLevelWords)\n wordSet.remove(word);\n Set nextLevelWords = new HashSet<>();\n for (final String parent : currentLevelWords) {\n graph.putIfAbsent(parent, new ArrayList<>());\n for (final String child : getChildren(parent, wordSet)) {\n if (wordSet.contains(child)) {\n nextLevelWords.add(child);\n graph.get(parent).add(child);\n }\n if (child.equals(endWord))\n reachEndWord = true;\n }\n }\n if (reachEndWord)\n return true;\n currentLevelWords = nextLevelWords;\n }\n\n return false;\n }\n\n private List getChildren(final String parent, Set wordSet) {\n List children = new ArrayList<>();\n StringBuilder sb = new StringBuilder(parent);\n\n for (int i = 0; i < sb.length(); ++i) {\n final char cache = sb.charAt(i);\n for (char c = 'a'; c <= 'z'; ++c) {\n if (c == cache)\n continue;\n sb.setCharAt(i, c);\n final String child = sb.toString();\n if (wordSet.contains(child))\n children.add(child);\n }\n sb.setCharAt(i, cache);\n }\n\n return children;\n }\n\n private void dfs(Map> graph, final String word, final String endWord,\n List path, List> ans) {\n if (word.equals(endWord)) {\n ans.add(new ArrayList<>(path));\n return;\n }\n if (!graph.containsKey(word))\n return;\n\n for (final String child : graph.get(word)) {\n path.add(child);\n dfs(graph, child, endWord, path, ans);\n path.remove(path.size() - 1);\n }\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector> findLadders(string beginWord, string endWord,\n vector& wordList) {\n unordered_set wordSet{wordList.begin(), wordList.end()};\n if (!wordSet.contains(endWord))\n return {};\n\n // {\"hit\": [\"hot\"], \"hot\": [\"dot\", \"lot\"], ...}\n unordered_map> graph;\n\n // Build the graph from the beginWord to the endWord.\n if (!bfs(beginWord, endWord, wordSet, graph))\n return {};\n\n vector> ans;\n dfs(graph, beginWord, endWord, {beginWord}, ans);\n return ans;\n }\n\n private:\n bool bfs(const string& beginWord, const string& endWord,\n unordered_set& wordSet,\n unordered_map>& graph) {\n unordered_set currentLevelWords{beginWord};\n\n while (!currentLevelWords.empty()) {\n for (const string& word : currentLevelWords)\n wordSet.erase(word);\n unordered_set nextLevelWords;\n bool reachEndWord = false;\n for (const string& parent : currentLevelWords) {\n vector children;\n getChildren(parent, wordSet, children);\n for (const string& child : children) {\n if (wordSet.contains(child)) {\n nextLevelWords.insert(child);\n graph[parent].push_back(child);\n }\n if (child == endWord)\n reachEndWord = true;\n }\n }\n if (reachEndWord)\n return true;\n currentLevelWords = std::move(nextLevelWords);\n }\n\n return false;\n }\n\n void getChildren(const string& parent, const unordered_set& wordSet,\n vector& children) {\n string s(parent);\n\n for (int i = 0; i < s.length(); ++i) {\n const char cache = s[i];\n for (char c = 'a'; c <= 'z'; ++c) {\n if (c == cache)\n continue;\n s[i] = c;\n if (wordSet.contains(s))\n children.push_back(s);\n }\n s[i] = cache;\n }\n }\n\n void dfs(const unordered_map>& graph,\n const string& word, const string& endWord, vector&& path,\n vector>& ans) {\n if (word == endWord) {\n ans.push_back(path);\n return;\n }\n if (!graph.contains(word))\n return;\n\n for (const string& child : graph.at(word)) {\n path.push_back(child);\n dfs(graph, child, endWord, std::move(path), ans);\n path.pop_back();\n }\n }\n};\n"} +{"task_num": 130, "task_title": "Surrounded Regions", "difficulty": 2, "func_name": "solve", "description": "Given an `m x n` matrix `board` containing `'X'` and `'O'`, capture all\nregions that are 4-directionally surrounded by `'X'`.\n\nA region is captured by flipping all `'O'`s into `'X'`s in that surrounded\nregion.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n if not board:\n return\n\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(board)\n n = len(board[0])\n q = collections.deque()\n\n for i in range(m):\n for j in range(n):\n if i * j == 0 or i == m - 1 or j == n - 1:\n if board[i][j] == 'O':\n q.append((i, j))\n board[i][j] = '*'\n\n while q:\n i, j = q.popleft()\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if board[x][y] != 'O':\n continue\n q.append((x, y))\n board[x][y] = '*'\n\n for row in board:\n for i, c in enumerate(row):\n if c == '*':\n row[i] = 'O'\n else:\n row[i] = 'X'\n", "java_solution": "class Solution {\n public void solve(char[][] board) {\n if (board.length == 0)\n return;\n\n final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n final int m = board.length;\n final int n = board[0].length;\n Queue> q = new ArrayDeque<>();\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (i * j == 0 || i == m - 1 || j == n - 1)\n if (board[i][j] == 'O') {\n q.offer(new Pair<>(i, j));\n board[i][j] = '*';\n }\n\n // Mark the grids that stretch from the four sides with '*'.\n while (!q.isEmpty()) {\n final int i = q.peek().getKey();\n final int j = q.poll().getValue();\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (board[x][y] != 'O')\n continue;\n q.offer(new Pair<>(x, y));\n board[x][y] = '*';\n }\n }\n\n for (char[] row : board)\n for (int i = 0; i < row.length; ++i)\n if (row[i] == '*')\n row[i] = 'O';\n else if (row[i] == 'O')\n row[i] = 'X';\n }\n}\n", "cpp_solution": "class Solution {\n public:\n void solve(vector>& board) {\n if (board.empty())\n return;\n\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n const int m = board.size();\n const int n = board[0].size();\n\n queue> q;\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (i * j == 0 || i == m - 1 || j == n - 1)\n if (board[i][j] == 'O') {\n q.emplace(i, j);\n board[i][j] = '*';\n }\n\n // Mark the grids that stretch from the four sides with '*'.\n while (!q.empty()) {\n const auto [i, j] = q.front();\n q.pop();\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (board[x][y] != 'O')\n continue;\n q.emplace(x, y);\n board[x][y] = '*';\n }\n }\n\n for (vector& row : board)\n for (char& c : row)\n if (c == '*')\n c = 'O';\n else if (c == 'O')\n c = 'X';\n }\n};\n"} +{"task_num": 132, "task_title": "Palindrome Partitioning II", "difficulty": 3, "func_name": "minCut", "description": "Given a string `s`, partition `s` such that every substring of the partition\nis a palindrome.\n\nReturn the minimum cuts needed for a palindrome partitioning of `s`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minCut(self, s: str) -> int:\n n = len(s)\n isPalindrome=[]\n for _ in range(n):\n isPalindrome.append([True] * n)\n dp = [n] * n\n\n for l in range(2, n + 1):\n i = 0\n for j in range(l - 1, n):\n isPalindrome[i][j] = s[i] == s[j] and isPalindrome[i + 1][j - 1]\n i += 1\n\n for i in range(n):\n if isPalindrome[0][i]:\n dp[i] = 0\n continue\n\n for j in range(i):\n if isPalindrome[j + 1][i]:\n dp[i] = min(dp[i], dp[j] + 1)\n\n return dp[-1]\n", "java_solution": "class Solution {\n public int minCut(String s) {\n final int n = s.length();\n // isPalindrome[i][j] := true if s[i..j] is a palindrome\n boolean[][] isPalindrome = new boolean[n][n];\n for (boolean[] row : isPalindrome)\n Arrays.fill(row, true);\n // dp[i] := the minimum cuts needed for a palindrome partitioning of s[0..i]\n int[] dp = new int[n];\n Arrays.fill(dp, n);\n\n for (int l = 2; l <= n; ++l)\n for (int i = 0, j = l - 1; j < n; ++i, ++j)\n isPalindrome[i][j] = s.charAt(i) == s.charAt(j) && isPalindrome[i + 1][j - 1];\n\n for (int i = 0; i < n; ++i) {\n if (isPalindrome[0][i]) {\n dp[i] = 0;\n continue;\n }\n\n // Try all the possible partitions.\n for (int j = 0; j < i; ++j)\n if (isPalindrome[j + 1][i])\n dp[i] = Math.min(dp[i], dp[j] + 1);\n }\n\n return dp[n - 1];\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minCut(string s) {\n const int n = s.length();\n // isPalindrome[i][j] := true if s[i..j] is a palindrome\n vector> isPalindrome(n, vector(n, true));\n // dp[i] := the minimum cuts needed for a palindrome partitioning of s[0..i]\n vector dp(n, n);\n\n for (int l = 2; l <= n; ++l)\n for (int i = 0, j = l - 1; j < n; ++i, ++j)\n isPalindrome[i][j] = s[i] == s[j] && isPalindrome[i + 1][j - 1];\n\n for (int i = 0; i < n; ++i) {\n if (isPalindrome[0][i]) {\n dp[i] = 0;\n continue;\n }\n\n // Try all the possible partitions.\n for (int j = 0; j < i; ++j)\n if (isPalindrome[j + 1][i])\n dp[i] = min(dp[i], dp[j] + 1);\n }\n\n return dp.back();\n }\n};\n"} +{"task_num": 218, "task_title": "The Skyline Problem", "difficulty": 3, "func_name": "getSkyline", "description": "A city's skyline is the outer contour of the silhouette formed by all the\nbuildings in that city when viewed from a distance. Given the locations and\nheights of all the buildings, return the skyline formed by these buildings\ncollectively.\n\nThe geometric information of each building is given in the array `buildings`\nwhere `buildings[i] = [lefti, righti, heighti]`:\n\n* `lefti` is the x coordinate of the left edge of the `ith` building.\n* `righti` is the x coordinate of the right edge of the `ith` building.\n* `heighti` is the height of the `ith` building.\n\nYou may assume all buildings are perfect rectangles grounded on an absolutely\nflat surface at height `0`.\n\nThe skyline should be represented as a list of \"key points\" sorted by their\nx-coordinate in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left\nendpoint of some horizontal segment in the skyline except the last point in\nthe list, which always has a y-coordinate `0` and is used to mark the\nskyline's termination where the rightmost building ends. Any ground between\nthe leftmost and rightmost buildings should be part of the skyline's contour.\n\nNote: There must be no consecutive horizontal lines of equal height in the\noutput skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is\nnot acceptable; the three lines of height 5 should be merged into one in the\nfinal output as such: `[...,[2 3],[4 5],[12 7],...]`\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:\n n = len(buildings)\n if n == 0:\n return []\n if n == 1:\n left, right, height = buildings[0]\n return [[left, height], [right, 0]]\n\n left = self.getSkyline(buildings[:n // 2])\n right = self.getSkyline(buildings[n // 2:])\n return self._merge(left, right)\n\n def _merge(self, left: List[List[int]], right: List[List[int]]) -> List[List[int]]:\n ans = []\n i = 0\n j = 0\n leftY = 0\n rightY = 0\n\n while i < len(left) and j < len(right):\n if left[i][0] < right[j][0]:\n leftY = left[i][1]\n self._addPoint(ans, left[i][0], max(left[i][1], rightY))\n i += 1\n else:\n rightY = right[j][1]\n self._addPoint(ans, right[j][0], max(right[j][1], leftY))\n j += 1\n\n while i < len(left):\n self._addPoint(ans, left[i][0], left[i][1])\n i += 1\n\n while j < len(right):\n self._addPoint(ans, right[j][0], right[j][1])\n j += 1\n\n return ans\n\n def _addPoint(self, ans: List[List[int]], x: int, y: int) -> None:\n if ans and ans[-1][0] == x:\n ans[-1][1] = y\n return\n if ans and ans[-1][1] == y:\n return\n ans.append([x, y])\n", "java_solution": "class Solution {\n public List> getSkyline(int[][] buildings) {\n final int n = buildings.length;\n if (n == 0)\n return new ArrayList<>();\n if (n == 1) {\n final int left = buildings[0][0];\n final int right = buildings[0][1];\n final int height = buildings[0][2];\n List> ans = new ArrayList<>();\n ans.add(new ArrayList<>(List.of(left, height)));\n ans.add(new ArrayList<>(List.of(right, 0)));\n return ans;\n }\n\n List> leftSkyline = getSkyline(Arrays.copyOfRange(buildings, 0, n / 2));\n List> rightSkyline = getSkyline(Arrays.copyOfRange(buildings, n / 2, n));\n return merge(leftSkyline, rightSkyline);\n }\n\n private List> merge(List> left, List> right) {\n List> ans = new ArrayList<>();\n int i = 0; // left's index\n int j = 0; // right's index\n int leftY = 0;\n int rightY = 0;\n\n while (i < left.size() && j < right.size())\n // Choose the point with the smaller x.\n if (left.get(i).get(0) < right.get(j).get(0)) {\n leftY = left.get(i).get(1); // Update the ongoing `leftY`.\n addPoint(ans, left.get(i).get(0), Math.max(left.get(i++).get(1), rightY));\n } else {\n rightY = right.get(j).get(1); // Update the ongoing `rightY`.\n addPoint(ans, right.get(j).get(0), Math.max(right.get(j++).get(1), leftY));\n }\n\n while (i < left.size())\n addPoint(ans, left.get(i).get(0), left.get(i++).get(1));\n\n while (j < right.size())\n addPoint(ans, right.get(j).get(0), right.get(j++).get(1));\n\n return ans;\n }\n\n private void addPoint(List> ans, int x, int y) {\n if (!ans.isEmpty() && ans.get(ans.size() - 1).get(0) == x) {\n ans.get(ans.size() - 1).set(1, y);\n return;\n }\n if (!ans.isEmpty() && ans.get(ans.size() - 1).get(1) == y)\n return;\n ans.add(new ArrayList<>(List.of(x, y)));\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector> getSkyline(const vector>& buildings) {\n const int n = buildings.size();\n if (n == 0)\n return {};\n if (n == 1) {\n const int left = buildings[0][0];\n const int right = buildings[0][1];\n const int height = buildings[0][2];\n return {{left, height}, {right, 0}};\n }\n\n const vector> left =\n getSkyline({buildings.begin(), buildings.begin() + n / 2});\n const vector> right =\n getSkyline({buildings.begin() + n / 2, buildings.end()});\n return merge(left, right);\n }\n\n private:\n vector> merge(const vector>& left,\n const vector>& right) {\n vector> ans;\n int i = 0; // left's index\n int j = 0; // right's index\n int leftY = 0;\n int rightY = 0;\n\n while (i < left.size() && j < right.size())\n // Choose the point with the smaller x.\n if (left[i][0] < right[j][0]) {\n leftY = left[i][1]; // Update the ongoing `leftY`.\n addPoint(ans, left[i][0], max(left[i++][1], rightY));\n } else {\n rightY = right[j][1]; // Update the ongoing `rightY`.\n addPoint(ans, right[j][0], max(right[j++][1], leftY));\n }\n\n while (i < left.size())\n addPoint(ans, left[i][0], left[i++][1]);\n\n while (j < right.size())\n addPoint(ans, right[j][0], right[j++][1]);\n\n return ans;\n }\n\n void addPoint(vector>& ans, int x, int y) {\n if (!ans.empty() && ans.back()[0] == x) {\n ans.back()[1] = y;\n return;\n }\n if (!ans.empty() && ans.back()[1] == y)\n return;\n ans.push_back({x, y});\n }\n};\n"} +{"task_num": 227, "task_title": "Basic Calculator II", "difficulty": 2, "func_name": "calculate", "description": "Given a string `s` which represents an expression, evaluate this expression\nand return its value.\n\nThe integer division should truncate toward zero.\n\nYou may assume that the given expression is always valid. All intermediate\nresults will be in the range of `[-231, 231 - 1]`.\n\nNote: You are not allowed to use any built-in function which evaluates strings\nas mathematical expressions, such as `eval()`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def calculate(self, s: str) -> int:\n ans = 0\n prevNum = 0\n currNum = 0\n op = '+'\n\n for i, c in enumerate(s):\n if c.isdigit():\n currNum = currNum * 10 + int(c)\n if not c.isdigit() and c != ' ' or i == len(s) - 1:\n if op == '+' or op == '-':\n ans += prevNum\n prevNum = currNum if op == '+' else -currNum\n elif op == '*':\n prevNum = prevNum * currNum\n elif op == '/':\n if prevNum < 0:\n prevNum = math.ceil(prevNum / currNum)\n else:\n prevNum = prevNum // currNum\n op = c\n currNum = 0\n\n return ans + prevNum\n", "java_solution": "class Solution {\n public int calculate(String s) {\n Deque nums = new ArrayDeque<>();\n Deque ops = new ArrayDeque<>();\n\n for (int i = 0; i < s.length(); ++i) {\n final char c = s.charAt(i);\n if (Character.isDigit(c)) {\n int num = c - '0';\n while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) {\n num = num * 10 + (s.charAt(i + 1) - '0');\n ++i;\n }\n nums.push(num);\n } else if (c == '+' || c == '-' || c == '*' || c == '/') {\n while (!ops.isEmpty() && compare(ops.peek(), c))\n nums.push(calculate(ops.pop(), nums.pop(), nums.pop()));\n ops.push(c);\n }\n }\n\n while (!ops.isEmpty())\n nums.push(calculate(ops.pop(), nums.pop(), nums.pop()));\n\n return nums.peek();\n }\n\n private int calculate(char op, int b, int a) {\n switch (op) {\n case '+':\n return a + b;\n case '-':\n return a - b;\n case '*':\n return a * b;\n case '/':\n return a / b;\n }\n throw new IllegalArgumentException();\n }\n\n // Returns true if priority(op1) >= priority(op2).\n private boolean compare(char op1, char op2) {\n return op1 == '*' || op1 == '/' || op2 == '+' || op2 == '-';\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int calculate(string s) {\n stack nums;\n stack ops;\n\n for (int i = 0; i < s.length(); ++i) {\n const char c = s[i];\n if (isdigit(c)) {\n int num = c - '0';\n while (i + 1 < s.length() && isdigit(s[i + 1])) {\n num = num * 10 + (s[i + 1] - '0');\n ++i;\n }\n nums.push(num);\n } else if (c == '+' || c == '-' || c == '*' || c == '/') {\n while (!ops.empty() && compare(ops.top(), c))\n nums.push(calculate(pop(ops), pop(nums), pop(nums)));\n ops.push(c);\n }\n }\n\n while (!ops.empty())\n nums.push(calculate(pop(ops), pop(nums), pop(nums)));\n\n return nums.top();\n }\n\n private:\n int calculate(char op, int b, int a) {\n switch (op) {\n case '+':\n return a + b;\n case '-':\n return a - b;\n case '*':\n return a * b;\n case '/':\n return a / b;\n }\n throw;\n }\n\n // Returns true if priority(op1) >= priority(op2).\n bool compare(char op1, char op2) {\n return op1 == '*' || op1 == '/' || op2 == '+' || op2 == '-';\n }\n\n char pop(stack& ops) {\n const char op = ops.top();\n ops.pop();\n return op;\n }\n\n int pop(stack& nums) {\n const int num = nums.top();\n nums.pop();\n return num;\n }\n};\n"} +{"task_num": 289, "task_title": "Game of Life", "difficulty": 2, "func_name": "gameOfLife", "description": "According to Wikipedia's article: \"The Game of Life, also known simply as\nLife, is a cellular automaton devised by the British mathematician John Horton\nConway in 1970.\"\n\nThe board is made up of an `m x n` grid of cells, where each cell has an\ninitial state: live (represented by a `1`) or dead (represented by a `0`).\nEach cell interacts with its eight neighbors (horizontal, vertical, diagonal)\nusing the following four rules (taken from the above Wikipedia article):\n\n1. Any live cell with fewer than two live neighbors dies as if caused by under-population.\n2. Any live cell with two or three live neighbors lives on to the next generation.\n3. Any live cell with more than three live neighbors dies, as if by over-population.\n4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.\n\nThe next state is created by applying the above rules simultaneously to every\ncell in the current state, where births and deaths occur simultaneously. Given\nthe current state of the `m x n` grid `board`, return the next state.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def gameOfLife(self, board: List[List[int]]) -> None:\n m = len(board)\n n = len(board[0])\n\n for i in range(m):\n for j in range(n):\n ones = 0\n for x in range(max(0, i - 1), min(m, i + 2)):\n for y in range(max(0, j - 1), min(n, j + 2)):\n ones += board[x][y] & 1\n\n if board[i][j] == 1 and (ones == 3 or ones == 4):\n board[i][j] |= 0b10\n\n if board[i][j] == 0 and ones == 3:\n board[i][j] |= 0b10\n\n for i in range(m):\n for j in range(n):\n board[i][j] >>= 1\n", "java_solution": "class Solution {\n public void gameOfLife(int[][] board) {\n final int m = board.length;\n final int n = board[0].length;\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j) {\n int ones = 0;\n for (int x = Math.max(0, i - 1); x < Math.min(m, i + 2); ++x)\n for (int y = Math.max(0, j - 1); y < Math.min(n, j + 2); ++y)\n ones += board[x][y] & 1;\n // Any live cell with two or three live neighbors lives on to the next\n // generation.\n if (board[i][j] == 1 && (ones == 3 || ones == 4))\n board[i][j] |= 0b10;\n // Any dead cell with exactly three live neighbors becomes a live cell,\n // as if by reproduction.\n if (board[i][j] == 0 && ones == 3)\n board[i][j] |= 0b10;\n }\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n board[i][j] >>= 1;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n void gameOfLife(vector>& board) {\n const int m = board.size();\n const int n = board[0].size();\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j) {\n int ones = 0;\n for (int x = max(0, i - 1); x < min(m, i + 2); ++x)\n for (int y = max(0, j - 1); y < min(n, j + 2); ++y)\n ones += board[x][y] & 1;\n // Any live cell with two or three live neighbors lives on to the next\n // generation.\n if (board[i][j] == 1 && (ones == 3 || ones == 4))\n board[i][j] |= 0b10;\n // Any dead cell with exactly three live neighbors becomes a live cell,\n // as if by reproduction.\n if (board[i][j] == 0 && ones == 3)\n board[i][j] |= 0b10;\n }\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n board[i][j] >>= 1;\n }\n};\n"} +{"task_num": 310, "task_title": "Minimum Height Trees", "difficulty": 2, "func_name": "findMinHeightTrees", "description": "A tree is an undirected graph in which any two vertices are connected by\nexactly one path. In other words, any connected graph without simple cycles is\na tree.\n\nGiven a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n -\n1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected\nedge between the two nodes `ai` and `bi` in the tree, you can choose any node\nof the tree as the root. When you select a node `x` as the root, the result\ntree has height `h`. Among all possible rooted trees, those with minimum\nheight (i.e. `min(h)`) are called minimum height trees (MHTs).\n\nReturn a list of all MHTs' root labels. You can return the answer in any\norder.\n\nThe height of a rooted tree is the number of edges on the longest downward\npath between the root and a leaf.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n if n == 1 or not edges:\n return [0]\n\n ans = []\n graph = collections.defaultdict(set)\n\n for u, v in edges:\n graph[u].add(v)\n graph[v].add(u)\n\n for label, children in graph.items():\n if len(children) == 1:\n ans.append(label)\n\n while n > 2:\n n -= len(ans)\n nextLeaves = []\n for leaf in ans:\n u = next(iter(graph[leaf]))\n graph[u].remove(leaf)\n if len(graph[u]) == 1:\n nextLeaves.append(u)\n ans = nextLeaves\n\n return ans\n", "java_solution": "class Solution {\n public List findMinHeightTrees(int n, int[][] edges) {\n if (n == 0 || edges.length == 0)\n return List.of(0);\n\n List ans = new ArrayList<>();\n Map> graph = new HashMap<>();\n\n for (int i = 0; i < n; ++i)\n graph.put(i, new HashSet<>());\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n graph.get(u).add(v);\n graph.get(v).add(u);\n }\n\n for (Map.Entry> entry : graph.entrySet()) {\n final int label = entry.getKey();\n Set children = entry.getValue();\n if (children.size() == 1)\n ans.add(label);\n }\n\n while (n > 2) {\n n -= ans.size();\n List nextLeaves = new ArrayList<>();\n for (final int leaf : ans) {\n final int u = (int) graph.get(leaf).iterator().next();\n graph.get(u).remove(leaf);\n if (graph.get(u).size() == 1)\n nextLeaves.add(u);\n }\n ans = nextLeaves;\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector findMinHeightTrees(int n, vector>& edges) {\n if (n == 1 || edges.empty())\n return {0};\n\n vector ans;\n unordered_map> graph;\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n graph[u].insert(v);\n graph[v].insert(u);\n }\n\n for (const auto& [label, children] : graph)\n if (children.size() == 1)\n ans.push_back(label);\n\n while (n > 2) {\n n -= ans.size();\n vector nextLeaves;\n for (const int leaf : ans) {\n const int u = *graph[leaf].begin();\n graph[u].erase(leaf);\n if (graph[u].size() == 1)\n nextLeaves.push_back(u);\n }\n ans = nextLeaves;\n }\n\n return ans;\n }\n};\n"} +{"task_num": 327, "task_title": "Count of Range Sum", "difficulty": 3, "func_name": "countRangeSum", "description": "Given an integer array `nums` and two integers `lower` and `upper`, return the\nnumber of range sums that lie in `[lower, upper]` inclusive.\n\nRange sum `S(i, j)` is defined as the sum of the elements in `nums` between\nindices `i` and `j` inclusive, where `i <= j`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:\n n = len(nums)\n self.ans = 0\n prefix = [0] + list(itertools.accumulate(nums))\n\n self._mergeSort(prefix, 0, n, lower, upper)\n return self.ans\n\n def _mergeSort(self, prefix: List[int], l: int, r: int, lower: int, upper: int) -> None:\n if l >= r:\n return\n\n m = (l + r) // 2\n self._mergeSort(prefix, l, m, lower, upper)\n self._mergeSort(prefix, m + 1, r, lower, upper)\n self._merge(prefix, l, m, r, lower, upper)\n\n def _merge(self, prefix: List[int], l: int, m: int, r: int, lower: int, upper: int) -> None:\n lo = m + 1\n hi = m + 1\n\n for i in range(l, m + 1):\n while lo <= r and prefix[lo] - prefix[i] < lower:\n lo += 1\n while hi <= r and prefix[hi] - prefix[i] <= upper:\n hi += 1\n self.ans += hi - lo\n\n sorted = [0] * (r - l + 1)\n k = 0\n i = l\n j = m + 1\n\n while i <= m and j <= r:\n if prefix[i] < prefix[j]:\n sorted[k] = prefix[i]\n k += 1\n i += 1\n else:\n sorted[k] = prefix[j]\n k += 1\n j += 1\n\n while i <= m:\n sorted[k] = prefix[i]\n k += 1\n i += 1\n\n while j <= r:\n sorted[k] = prefix[j]\n k += 1\n j += 1\n\n prefix[l:l + len(sorted)] = sorted\n", "java_solution": "class Solution {\n public int countRangeSum(int[] nums, int lower, int upper) {\n final int n = nums.length;\n long[] prefix = new long[n + 1];\n\n for (int i = 0; i < n; ++i)\n prefix[i + 1] = (long) nums[i] + prefix[i];\n\n mergeSort(prefix, 0, n, lower, upper);\n return ans;\n }\n\n private int ans = 0;\n\n private void mergeSort(long[] prefix, int l, int r, int lower, int upper) {\n if (l >= r)\n return;\n\n final int m = (l + r) / 2;\n mergeSort(prefix, l, m, lower, upper);\n mergeSort(prefix, m + 1, r, lower, upper);\n merge(prefix, l, m, r, lower, upper);\n }\n\n private void merge(long[] prefix, int l, int m, int r, int lower, int upper) {\n int lo = m + 1; // the first index s.t. prefix[lo] - prefix[i] >= lower\n int hi = m + 1; // the first index s.t. prefix[hi] - prefix[i] > upper\n\n // For each index i in range [l, m], add hi - lo to `ans`.\n for (int i = l; i <= m; ++i) {\n while (lo <= r && prefix[lo] - prefix[i] < lower)\n ++lo;\n while (hi <= r && prefix[hi] - prefix[i] <= upper)\n ++hi;\n ans += hi - lo;\n }\n\n long[] sorted = new long[r - l + 1];\n int k = 0; // sorted's index\n int i = l; // left's index\n int j = m + 1; // right's index\n\n while (i <= m && j <= r)\n if (prefix[i] < prefix[j])\n sorted[k++] = prefix[i++];\n else\n sorted[k++] = prefix[j++];\n\n // Put the possible remaining left part into the sorted array.\n while (i <= m)\n sorted[k++] = prefix[i++];\n\n // Put the possible remaining right part into the sorted array.\n while (j <= r)\n sorted[k++] = prefix[j++];\n\n System.arraycopy(sorted, 0, prefix, l, sorted.length);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int countRangeSum(vector& nums, int lower, int upper) {\n const int n = nums.size();\n int ans = 0;\n vector prefix{0};\n\n for (int i = 0; i < n; ++i)\n prefix.push_back(prefix.back() + nums[i]);\n\n mergeSort(prefix, 0, n, lower, upper, ans);\n return ans;\n }\n\n private:\n void mergeSort(vector& prefix, int l, int r, int lower, int upper,\n int& ans) {\n if (l >= r)\n return;\n\n const int m = (l + r) / 2;\n mergeSort(prefix, l, m, lower, upper, ans);\n mergeSort(prefix, m + 1, r, lower, upper, ans);\n merge(prefix, l, m, r, lower, upper, ans);\n }\n\n void merge(vector& prefix, int l, int m, int r, int lower, int upper,\n int& ans) {\n int lo = m + 1; // the first index s.t. prefix[lo] - prefix[i] >= lower\n int hi = m + 1; // the first index s.t. prefix[hi] - prefix[i] > upper\n\n // For each index i in range [l, m], add hi - lo to `ans`.\n for (int i = l; i <= m; ++i) {\n while (lo <= r && prefix[lo] - prefix[i] < lower)\n ++lo;\n while (hi <= r && prefix[hi] - prefix[i] <= upper)\n ++hi;\n ans += hi - lo;\n }\n\n vector sorted(r - l + 1);\n int k = 0; // sorted's index\n int i = l; // left's index\n int j = m + 1; // right's index\n\n while (i <= m && j <= r)\n if (prefix[i] < prefix[j])\n sorted[k++] = prefix[i++];\n else\n sorted[k++] = prefix[j++];\n\n // Put the possible remaining left part into the sorted array.\n while (i <= m)\n sorted[k++] = prefix[i++];\n\n // Put the possible remaining right part into the sorted array.\n while (j <= r)\n sorted[k++] = prefix[j++];\n\n copy(sorted.begin(), sorted.end(), prefix.begin() + l);\n }\n};\n"} +{"task_num": 335, "task_title": "Self Crossing", "difficulty": 3, "func_name": "isSelfCrossing", "description": "You are given an array of integers `distance`.\n\nYou start at the point `(0, 0)` on an X-Y plane, and you move `distance[0]`\nmeters to the north, then `distance[1]` meters to the west, `distance[2]`\nmeters to the south, `distance[3]` meters to the east, and so on. In other\nwords, after each move, your direction changes counter-clockwise.\n\nReturn `true` if your path crosses itself or `false` if it does not.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def isSelfCrossing(self, x: List[int]) -> bool:\n if len(x) <= 3:\n return False\n\n for i in range(3, len(x)):\n if x[i - 2] <= x[i] and x[i - 1] <= x[i - 3]:\n return True\n if i >= 4 and x[i - 1] == x[i - 3] and x[i - 2] <= x[i] + x[i - 4]:\n return True\n if i >= 5 and x[i - 4] <= x[i - 2] and x[i - 2] <= x[i] + x[i - 4] and x[i - 1] <= x[i - 3] and x[i - 3] <= x[i - 1] + x[i - 5]:\n return True\n\n return False\n", "java_solution": "class Solution {\n public boolean isSelfCrossing(int[] x) {\n if (x.length <= 3)\n return false;\n\n for (int i = 3; i < x.length; ++i) {\n if (x[i - 2] <= x[i] && x[i - 1] <= x[i - 3])\n return true;\n if (i >= 4 && x[i - 1] == x[i - 3] && x[i - 2] <= x[i] + x[i - 4])\n return true;\n if (i >= 5 && x[i - 4] <= x[i - 2] && x[i - 2] <= x[i] + x[i - 4] && x[i - 1] <= x[i - 3] &&\n x[i - 3] <= x[i - 1] + x[i - 5])\n return true;\n }\n\n return false;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool isSelfCrossing(vector& x) {\n if (x.size() <= 3)\n return false;\n\n for (int i = 3; i < x.size(); ++i) {\n if (x[i - 2] <= x[i] && x[i - 1] <= x[i - 3])\n return true;\n if (i >= 4 && x[i - 1] == x[i - 3] && x[i - 2] <= x[i] + x[i - 4])\n return true;\n if (i >= 5 && x[i - 4] <= x[i - 2] && x[i - 2] <= x[i] + x[i - 4] &&\n x[i - 1] <= x[i - 3] && x[i - 3] <= x[i - 1] + x[i - 5])\n return true;\n }\n\n return false;\n }\n};\n"} +{"task_num": 336, "task_title": "Palindrome Pairs", "difficulty": 3, "func_name": "palindromePairs", "description": "You are given a 0-indexed array of unique strings `words`.\n\nA palindrome pair is a pair of integers `(i, j)` such that:\n\n* `0 <= i, j < words.length`,\n* `i != j`, and\n* `words[i] + words[j]` (the concatenation of the two strings) is a palindrome.\n\nReturn an array of all the palindrome pairs of `words`.\n\nYou must write an algorithm with `O(sum of words[i].length)` runtime\ncomplexity.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def palindromePairs(self, words: List[str]) -> List[List[int]]:\n ans = []\n dict = {word[::-1]: i for i, word in enumerate(words)}\n\n for i, word in enumerate(words):\n if \"\" in dict and dict[\"\"] != i and word == word[::-1]:\n ans.append([i, dict[\"\"]])\n\n for j in range(1, len(word) + 1):\n l = word[:j]\n r = word[j:]\n if l in dict and dict[l] != i and r == r[::-1]:\n ans.append([i, dict[l]])\n if r in dict and dict[r] != i and l == l[::-1]:\n ans.append([dict[r], i])\n\n return ans\n", "java_solution": "class Solution {\n public List> palindromePairs(String[] words) {\n List> ans = new ArrayList<>();\n Map map = new HashMap<>(); // {reversed word: its index}\n\n for (int i = 0; i < words.length; ++i)\n map.put(new StringBuilder(words[i]).reverse().toString(), i);\n\n for (int i = 0; i < words.length; ++i) {\n final String word = words[i];\n // a special case to prevent duplicate calculation\n if (map.containsKey(\"\") && map.get(\"\") != i && isPalindrome(word))\n ans.add(Arrays.asList(i, map.get(\"\")));\n for (int j = 1; j <= word.length(); ++j) {\n final String l = word.substring(0, j);\n final String r = word.substring(j);\n if (map.containsKey(l) && map.get(l) != i && isPalindrome(r))\n ans.add(Arrays.asList(i, map.get(l)));\n if (map.containsKey(r) && map.get(r) != i && isPalindrome(l))\n ans.add(Arrays.asList(map.get(r), i));\n }\n }\n\n return ans;\n }\n\n private boolean isPalindrome(final String word) {\n int l = 0;\n int r = word.length() - 1;\n while (l < r)\n if (word.charAt(l++) != word.charAt(r--))\n return false;\n return true;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector> palindromePairs(vector& words) {\n vector> ans;\n unordered_map map; // {reversed word: its index}\n\n for (int i = 0; i < words.size(); ++i) {\n string word = words[i];\n ranges::reverse(word);\n map[word] = i;\n }\n\n for (int i = 0; i < words.size(); ++i) {\n const string& word = words[i];\n // a special case to prevent duplicate calculation\n if (const auto it = map.find(\"\");\n it != map.cend() && it->second != i && isPalindrome(word))\n ans.push_back({i, it->second});\n for (int j = 1; j <= word.length(); ++j) {\n const string& l = word.substr(0, j);\n const string& r = word.substr(j);\n if (const auto it = map.find(l);\n it != map.cend() && it->second != i && isPalindrome(r))\n ans.push_back({i, it->second});\n if (const auto it = map.find(r);\n it != map.cend() && it->second != i && isPalindrome(l))\n ans.push_back({it->second, i});\n }\n }\n\n return ans;\n }\n\n private:\n bool isPalindrome(const string& word) {\n int l = 0;\n int r = word.length() - 1;\n while (l < r)\n if (word[l++] != word[r--])\n return false;\n return true;\n }\n};\n"} +{"task_num": 391, "task_title": "Perfect Rectangle", "difficulty": 3, "func_name": "isRectangleCover", "description": "Given an array `rectangles` where `rectangles[i] = [xi, yi, ai, bi]`\nrepresents an axis-aligned rectangle. The bottom-left point of the rectangle\nis `(xi, yi)` and the top-right point of it is `(ai, bi)`.\n\nReturn `true` if all the rectangles together form an exact cover of a\nrectangular region.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator, Set\n\nclass Solution:\n def isRectangleCover(self, rectangles: List[List[int]]) -> bool:\n area = 0\n x1 = math.inf\n y1 = math.inf\n x2 = -math.inf\n y2 = -math.inf\n corners: Set[Tuple[int, int]] = set()\n\n for x, y, a, b in rectangles:\n area += (a - x) * (b - y)\n x1 = min(x1, x)\n y1 = min(y1, y)\n x2 = max(x2, a)\n y2 = max(y2, b)\n\n for point in [(x, y), (x, b), (a, y), (a, b)]:\n if point in corners:\n corners.remove(point)\n else:\n corners.add(point)\n\n if len(corners) != 4:\n return False\n if (x1, y1) not in corners or (x1, y2) not in corners or (x2, y1) not in corners or (x2, y2) not in corners:\n return False\n return area == (x2 - x1) * (y2 - y1)\n", "java_solution": "class Solution {\n public boolean isRectangleCover(int[][] rectangles) {\n int area = 0;\n int x1 = Integer.MAX_VALUE;\n int y1 = Integer.MAX_VALUE;\n int x2 = Integer.MIN_VALUE;\n int y2 = Integer.MIN_VALUE;\n Set corners = new HashSet<>();\n\n for (int[] r : rectangles) {\n area += (r[2] - r[0]) * (r[3] - r[1]);\n x1 = Math.min(x1, r[0]);\n y1 = Math.min(y1, r[1]);\n x2 = Math.max(x2, r[2]);\n y2 = Math.max(y2, r[3]);\n\n // the four points of the current rectangle\n String[] points = new String[] {r[0] + \" \" + r[1], //\n r[0] + \" \" + r[3], //\n r[2] + \" \" + r[1], //\n r[2] + \" \" + r[3]};\n for (final String point : points)\n if (!corners.add(point))\n corners.remove(point);\n }\n\n if (corners.size() != 4)\n return false;\n if (!corners.contains(x1 + \" \" + y1) || //\n !corners.contains(x1 + \" \" + y2) || //\n !corners.contains(x2 + \" \" + y1) || //\n !corners.contains(x2 + \" \" + y2))\n return false;\n return area == (x2 - x1) * (y2 - y1);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool isRectangleCover(vector>& rectangles) {\n int area = 0;\n int x1 = INT_MAX;\n int y1 = INT_MAX;\n int x2 = INT_MIN;\n int y2 = INT_MIN;\n unordered_set corners;\n\n for (const vector& r : rectangles) {\n area += (r[2] - r[0]) * (r[3] - r[1]);\n x1 = min(x1, r[0]);\n y1 = min(y1, r[1]);\n x2 = max(x2, r[2]);\n y2 = max(y2, r[3]);\n\n // the four points of the current rectangle\n const vector points{to_string(r[0]) + \" \" + to_string(r[1]),\n to_string(r[0]) + \" \" + to_string(r[3]),\n to_string(r[2]) + \" \" + to_string(r[1]),\n to_string(r[2]) + \" \" + to_string(r[3])};\n for (const string& point : points)\n if (!corners.insert(point).second)\n corners.erase(point);\n }\n\n if (corners.size() != 4)\n return false;\n if (!corners.contains(to_string(x1) + \" \" + to_string(y1)) ||\n !corners.contains(to_string(x1) + \" \" + to_string(y2)) ||\n !corners.contains(to_string(x2) + \" \" + to_string(y1)) ||\n !corners.contains(to_string(x2) + \" \" + to_string(y2)))\n return false;\n return area == (x2 - x1) * (y2 - y1);\n }\n};\n"} +{"task_num": 402, "task_title": "Remove K Digits", "difficulty": 2, "func_name": "removeKdigits", "description": "Given string num representing a non-negative integer `num`, and an integer\n`k`, return the smallest possible integer after removing `k` digits from\n`num`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def removeKdigits(self, num: str, k: int) -> str:\n if len(num) == k:\n return '0'\n\n ans = []\n stack = []\n\n for i, digit in enumerate(num):\n while k > 0 and stack and stack[-1] > digit:\n stack.pop()\n k -= 1\n stack.append(digit)\n\n for _ in range(k):\n stack.pop()\n\n for c in stack:\n if c == '0' and not ans:\n continue\n ans.append(c)\n\n return ''.join(ans) if ans else '0'\n", "java_solution": "class Solution {\n public String removeKdigits(String num, int k) {\n if (num.length() == k)\n return \"0\";\n\n StringBuilder sb = new StringBuilder();\n LinkedList stack = new LinkedList<>();\n\n for (int i = 0; i < num.length(); ++i) {\n while (k > 0 && !stack.isEmpty() && stack.getLast() > num.charAt(i)) {\n stack.pollLast();\n --k;\n }\n stack.addLast(num.charAt(i));\n }\n\n while (k-- > 0)\n stack.pollLast();\n\n for (final char c : stack) {\n if (c == '0' && sb.length() == 0)\n continue;\n sb.append(c);\n }\n\n return sb.length() == 0 ? \"0\" : sb.toString();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n string removeKdigits(string num, int k) {\n if (num.length() == k)\n return \"0\";\n\n string ans;\n vector stack;\n\n for (int i = 0; i < num.length(); ++i) {\n while (k > 0 && !stack.empty() && stack.back() > num[i]) {\n stack.pop_back();\n --k;\n }\n stack.push_back(num[i]);\n }\n\n while (k-- > 0)\n stack.pop_back();\n\n for (const char c : stack) {\n if (c == '0' && ans.empty())\n continue;\n ans += c;\n }\n\n return ans.empty() ? \"0\" : ans;\n }\n};\n"} +{"task_num": 407, "task_title": "Trapping Rain Water II", "difficulty": 3, "func_name": "trapRainWater", "description": "Given an `m x n` integer matrix `heightMap` representing the height of each\nunit cell in a 2D elevation map, return the volume of water it can trap after\nraining.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def trapRainWater(self, heightMap: List[List[int]]) -> int:\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(heightMap)\n n = len(heightMap[0])\n ans = 0\n minHeap = []\n seen = set()\n\n for i in range(m):\n heapq.heappush(minHeap, (heightMap[i][0], i, 0))\n heapq.heappush(minHeap, (heightMap[i][n - 1], i, n - 1))\n seen.add((i, 0))\n seen.add((i, n - 1))\n\n for j in range(1, n - 1):\n heapq.heappush(minHeap, (heightMap[0][j], 0, j))\n heapq.heappush(minHeap, (heightMap[m - 1][j], m - 1, j))\n seen.add((0, j))\n seen.add((m - 1, j))\n\n while minHeap:\n h, i, j = heapq.heappop(minHeap)\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if (x, y) in seen:\n continue\n if heightMap[x][y] < h:\n ans += h - heightMap[x][y]\n heapq.heappush(minHeap, (h, x, y))\n else:\n heapq.heappush(minHeap, (heightMap[x][y], x, y))\n seen.add((x, y))\n\n return ans\n", "java_solution": "class Solution {\n public int trapRainWater(int[][] heightMap) {\n // h := heightMap[i][j] or the height after filling water\n record T(int i, int j, int h) {}\n final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n final int m = heightMap.length;\n final int n = heightMap[0].length;\n int ans = 0;\n Queue minHeap = new PriorityQueue<>(Comparator.comparingInt(T::h));\n boolean[][] seen = new boolean[m][n];\n\n for (int i = 0; i < m; ++i) {\n minHeap.offer(new T(i, 0, heightMap[i][0]));\n minHeap.offer(new T(i, n - 1, heightMap[i][n - 1]));\n seen[i][0] = true;\n seen[i][n - 1] = true;\n }\n\n for (int j = 1; j < n - 1; ++j) {\n minHeap.offer(new T(0, j, heightMap[0][j]));\n minHeap.offer(new T(m - 1, j, heightMap[m - 1][j]));\n seen[0][j] = true;\n seen[m - 1][j] = true;\n }\n\n while (!minHeap.isEmpty()) {\n final int i = minHeap.peek().i;\n final int j = minHeap.peek().j;\n final int h = minHeap.poll().h;\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n if (heightMap[x][y] < h) {\n ans += h - heightMap[x][y];\n minHeap.offer(new T(x, y, h)); // Fill water in grid[x][y].\n } else {\n minHeap.offer(new T(x, y, heightMap[x][y]));\n }\n seen[x][y] = true;\n }\n }\n\n return ans;\n }\n}\n", "cpp_solution": "struct T {\n int i;\n int j;\n int h; // heightMap[i][j] or the height after filling water\n T(int i_, int j_, int h_) : i(i_), j(j_), h(h_) {}\n};\n\nclass Solution {\n public:\n int trapRainWater(vector>& heightMap) {\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n const int m = heightMap.size();\n const int n = heightMap[0].size();\n int ans = 0;\n auto compare = [](const T& a, const T& b) { return a.h > b.h; };\n priority_queue, decltype(compare)> minHeap(compare);\n vector> seen(m, vector(n));\n\n for (int i = 0; i < m; ++i) {\n minHeap.emplace(i, 0, heightMap[i][0]);\n minHeap.emplace(i, n - 1, heightMap[i][n - 1]);\n seen[i][0] = true;\n seen[i][n - 1] = true;\n }\n\n for (int j = 1; j < n - 1; ++j) {\n minHeap.emplace(0, j, heightMap[0][j]);\n minHeap.emplace(m - 1, j, heightMap[m - 1][j]);\n seen[0][j] = true;\n seen[m - 1][j] = true;\n }\n\n while (!minHeap.empty()) {\n const auto [i, j, h] = minHeap.top();\n minHeap.pop();\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n if (heightMap[x][y] < h) {\n ans += h - heightMap[x][y];\n minHeap.emplace(x, y, h); // Fill water in grid[x][y].\n } else {\n minHeap.emplace(x, y, heightMap[x][y]);\n }\n seen[x][y] = true;\n }\n }\n\n return ans;\n }\n};\n"} +{"task_num": 417, "task_title": "Pacific Atlantic Water Flow", "difficulty": 2, "func_name": "pacificAtlantic", "description": "There is an `m x n` rectangular island that borders both the Pacific Ocean and\nAtlantic Ocean. The Pacific Ocean touches the island's left and top edges, and\nthe Atlantic Ocean touches the island's right and bottom edges.\n\nThe island is partitioned into a grid of square cells. You are given an `m x\nn` integer matrix `heights` where `heights[r][c]` represents the height above\nsea level of the cell at coordinate `(r, c)`.\n\nThe island receives a lot of rain, and the rain water can flow to neighboring\ncells directly north, south, east, and west if the neighboring cell's height\nis less than or equal to the current cell's height. Water can flow from any\ncell adjacent to an ocean into the ocean.\n\nReturn a 2D list of grid coordinates `result` where `result[i] = [ri, ci]`\ndenotes that rain water can flow from cell `(ri, ci)` to both the Pacific and\nAtlantic oceans.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(heights)\n n = len(heights[0])\n qP = collections.deque()\n qA = collections.deque()\n seenP = [[False] * n for _ in range(m)]\n seenA = [[False] * n for _ in range(m)]\n\n for i in range(m):\n qP.append((i, 0))\n qA.append((i, n - 1))\n seenP[i][0] = True\n seenA[i][n - 1] = True\n\n for j in range(n):\n qP.append((0, j))\n qA.append((m - 1, j))\n seenP[0][j] = True\n seenA[m - 1][j] = True\n\n def bfs(q: collections.deque, seen: List[List[bool]]):\n while q:\n i, j = q.popleft()\n h = heights[i][j]\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if seen[x][y] or heights[x][y] < h:\n continue\n q.append((x, y))\n seen[x][y] = True\n\n bfs(qP, seenP)\n bfs(qA, seenA)\n\n res=[]\n for i in range(m):\n for j in range(n):\n if seenP[i][j] and seenA[i][j]:\n res.append([i, j])\n return res\n", "java_solution": "class Solution {\n public List> pacificAtlantic(int[][] heights) {\n final int m = heights.length;\n final int n = heights[0].length;\n List> ans = new ArrayList<>();\n Queue> qP = new ArrayDeque<>();\n Queue> qA = new ArrayDeque<>();\n boolean[][] seenP = new boolean[m][n];\n boolean[][] seenA = new boolean[m][n];\n\n for (int i = 0; i < m; ++i) {\n qP.offer(new Pair<>(i, 0));\n qA.offer(new Pair<>(i, n - 1));\n seenP[i][0] = true;\n seenA[i][n - 1] = true;\n }\n\n for (int j = 0; j < n; ++j) {\n qP.offer(new Pair<>(0, j));\n qA.offer(new Pair<>(m - 1, j));\n seenP[0][j] = true;\n seenA[m - 1][j] = true;\n }\n\n bfs(heights, qP, seenP);\n bfs(heights, qA, seenA);\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (seenP[i][j] && seenA[i][j])\n ans.add(new ArrayList<>(List.of(i, j)));\n\n return ans;\n }\n\n private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n private void bfs(int[][] heights, Queue> q, boolean[][] seen) {\n while (!q.isEmpty()) {\n final int i = q.peek().getKey();\n final int j = q.poll().getValue();\n final int h = heights[i][j];\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == heights.length || y < 0 || y == heights[0].length)\n continue;\n if (seen[x][y] || heights[x][y] < h)\n continue;\n q.offer(new Pair<>(x, y));\n seen[x][y] = true;\n }\n }\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector> pacificAtlantic(vector>& heights) {\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n const int m = heights.size();\n const int n = heights[0].size();\n vector> ans;\n queue> qP;\n queue> qA;\n vector> seenP(m, vector(n));\n vector> seenA(m, vector(n));\n\n auto bfs = [&](queue>& q, vector>& seen) {\n while (!q.empty()) {\n const auto [i, j] = q.front();\n q.pop();\n const int h = heights[i][j];\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (seen[x][y] || heights[x][y] < h)\n continue;\n q.emplace(x, y);\n seen[x][y] = true;\n }\n }\n };\n\n for (int i = 0; i < m; ++i) {\n qP.emplace(i, 0);\n qA.emplace(i, n - 1);\n seenP[i][0] = true;\n seenA[i][n - 1] = true;\n }\n\n for (int j = 0; j < n; ++j) {\n qP.emplace(0, j);\n qA.emplace(m - 1, j);\n seenP[0][j] = true;\n seenA[m - 1][j] = true;\n }\n\n bfs(qP, seenP);\n bfs(qA, seenA);\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (seenP[i][j] && seenA[i][j])\n ans.push_back({i, j});\n\n return ans;\n }\n};\n"} +{"task_num": 420, "task_title": "Strong Password Checker", "difficulty": 3, "func_name": "strongPasswordChecker", "description": "A password is considered strong if the below conditions are all met:\n\n* It has at least `6` characters and at most `20` characters.\n* It contains at least one lowercase letter, at least one uppercase letter, and at least one digit.\n* It does not contain three repeating characters in a row (i.e., `\"Baaabb0\"` is weak, but `\"Baaba0\"` is strong).\n\nGiven a string `password`, return the minimum number of steps required to make\n`password` strong. if `password` is already strong, return `0`.\n\nIn one step, you can:\n\n* Insert one character to `password`,\n* Delete one character from `password`, or\n* Replace one character of `password` with another character.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def strongPasswordChecker(self, password: str) -> int:\n n = len(password)\n missing = self._getMissing(password)\n replaces = 0\n oneSeq = 0\n twoSeq = 0\n\n i = 2\n while i < n:\n if password[i] == password[i - 1] and password[i - 1] == password[i - 2]:\n length = 2\n while i < n and password[i] == password[i - 1]:\n length += 1\n i += 1\n replaces += length // 3\n if length % 3 == 0:\n oneSeq += 1\n if length % 3 == 1:\n twoSeq += 1\n else:\n i += 1\n\n if n < 6:\n return max(6 - n, missing)\n if n <= 20:\n return max(replaces, missing)\n\n deletes = n - 20\n replaces -= min(oneSeq, deletes)\n replaces -= min(max(deletes - oneSeq, 0), twoSeq * 2) // 2\n replaces -= max(deletes - oneSeq - twoSeq * 2, 0) // 3\n return deletes + max(replaces, missing)\n\n def _getMissing(self, password: str) -> int:\n return 3 - any(c.isupper() for c in password) - any(c.islower() for c in password) - any(c.isdigit() for c in password)\n", "java_solution": "class Solution {\n public int strongPasswordChecker(String password) {\n final int n = password.length();\n final int missing = getMissing(password);\n // the number of replacements to deal with 3 repeating characters\n int replaces = 0;\n // the number of sequences that can be substituted with 1 deletions, (3k)-seqs\n int oneSeq = 0;\n // the number of sequences that can be substituted with 2 deletions, (3k + 1)-seqs\n int twoSeq = 0;\n\n for (int i = 2; i < n;)\n if (password.charAt(i) == password.charAt(i - 1) &&\n password.charAt(i - 1) == password.charAt(i - 2)) {\n int length = 2; // the length of the repeating password\n while (i < n && password.charAt(i) == password.charAt(i - 1)) {\n ++length;\n ++i;\n }\n replaces += length / 3; // 'aaaaaaa' -> 'aaxaaxa'\n if (length % 3 == 0)\n ++oneSeq;\n if (length % 3 == 1)\n ++twoSeq;\n } else {\n ++i;\n }\n\n if (n < 6)\n return Math.max(6 - n, missing);\n if (n <= 20)\n return Math.max(replaces, missing);\n\n final int deletes = n - 20;\n // Each replacement in (3k)-seqs can be substituted with 1 deletions.\n replaces -= Math.min(oneSeq, deletes);\n // Each replacement in (3k + 1)-seqs can be substituted with 2 deletions.\n replaces -= Math.min(Math.max(deletes - oneSeq, 0), twoSeq * 2) / 2;\n // Each replacement in other seqs can be substituted with 3 deletions.\n replaces -= Math.max(deletes - oneSeq - twoSeq * 2, 0) / 3;\n return deletes + Math.max(replaces, missing);\n }\n\n private int getMissing(final String password) {\n return 3 - //\n (password.chars().anyMatch(Character::isUpperCase) ? 1 : 0) -\n (password.chars().anyMatch(Character::isLowerCase) ? 1 : 0) -\n (password.chars().anyMatch(Character::isDigit) ? 1 : 0);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int strongPasswordChecker(string password) {\n const int n = password.length();\n const int missing = getMissing(password);\n // the number of replacements to deal with 3 repeating characters\n int replaces = 0;\n // the number of sequences that can be substituted with 1 deletions,\n // (3k)-seqs\n int oneSeq = 0;\n // the number of sequences that can be substituted with 2 deletions,\n // (3k + 1)-seqs\n int twoSeq = 0;\n\n for (int i = 2; i < n;)\n if (password[i] == password[i - 1] &&\n password[i - 1] == password[i - 2]) {\n int length = 2; // the length of the repeating password\n while (i < n && password[i] == password[i - 1]) {\n ++length;\n ++i;\n }\n replaces += length / 3; // 'aaaaaaa' -> 'aaxaaxa'\n if (length % 3 == 0)\n ++oneSeq;\n if (length % 3 == 1)\n ++twoSeq;\n } else {\n ++i;\n }\n\n if (n < 6)\n return max(6 - n, missing);\n if (n <= 20)\n return max(replaces, missing);\n\n const int deletes = n - 20;\n // Each replacement in (3k)-seqs can be substituted with 1 deletions.\n replaces -= min(oneSeq, deletes);\n // Each replacement in (3k + 1)-seqs can be substituted with 2 deletions.\n replaces -= min(max(deletes - oneSeq, 0), twoSeq * 2) / 2;\n // Each replacement in other seqs can be substituted with 3 deletions.\n replaces -= max(deletes - oneSeq - twoSeq * 2, 0) / 3;\n return deletes + max(replaces, missing);\n }\n\n private:\n int getMissing(const string& password) {\n return 3 - //\n ranges::any_of(password, [](char c) { return isupper(c); }) -\n ranges::any_of(password, [](char c) { return islower(c); }) -\n ranges::any_of(password, [](char c) { return isdigit(c); });\n }\n};\n"} +{"task_num": 423, "task_title": "Reconstruct Original Digits from English", "difficulty": 2, "func_name": "originalDigits", "description": "Given a string `s` containing an out-of-order English representation of digits\n`0-9`, return the digits in ascending order.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def originalDigits(self, s: str) -> str:\n count = [0] * 10\n\n for c in s:\n if c == 'z':\n count[0] += 1\n if c == 'o':\n count[1] += 1\n if c == 'w':\n count[2] += 1\n if c == 'h':\n count[3] += 1\n if c == 'u':\n count[4] += 1\n if c == 'f':\n count[5] += 1\n if c == 'x':\n count[6] += 1\n if c == 's':\n count[7] += 1\n if c == 'g':\n count[8] += 1\n if c == 'i':\n count[9] += 1\n\n count[1] -= count[0] + count[2] + count[4]\n count[3] -= count[8]\n count[5] -= count[4]\n count[7] -= count[6]\n count[9] -= count[5] + count[6] + count[8]\n\n return ''.join(chr(i + ord('0')) for i, c in enumerate(count) for j in range(c))\n", "java_solution": "class Solution {\n public String originalDigits(String s) {\n StringBuilder sb = new StringBuilder();\n int[] count = new int[10];\n\n for (final char c : s.toCharArray()) {\n if (c == 'z')\n ++count[0];\n if (c == 'o')\n ++count[1];\n if (c == 'w')\n ++count[2];\n if (c == 'h')\n ++count[3];\n if (c == 'u')\n ++count[4];\n if (c == 'f')\n ++count[5];\n if (c == 'x')\n ++count[6];\n if (c == 's')\n ++count[7];\n if (c == 'g')\n ++count[8];\n if (c == 'i')\n ++count[9];\n }\n\n count[1] -= count[0] + count[2] + count[4];\n count[3] -= count[8];\n count[5] -= count[4];\n count[7] -= count[6];\n count[9] -= count[5] + count[6] + count[8];\n\n for (int i = 0; i < 10; ++i)\n for (int j = 0; j < count[i]; ++j)\n sb.append(i);\n\n return sb.toString();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n string originalDigits(string s) {\n string ans;\n vector count(10);\n\n for (const char c : s) {\n if (c == 'z')\n ++count[0];\n if (c == 'o')\n ++count[1];\n if (c == 'w')\n ++count[2];\n if (c == 'h')\n ++count[3];\n if (c == 'u')\n ++count[4];\n if (c == 'f')\n ++count[5];\n if (c == 'x')\n ++count[6];\n if (c == 's')\n ++count[7];\n if (c == 'g')\n ++count[8];\n if (c == 'i')\n ++count[9];\n }\n\n count[1] -= count[0] + count[2] + count[4];\n count[3] -= count[8];\n count[5] -= count[4];\n count[7] -= count[6];\n count[9] -= count[5] + count[6] + count[8];\n\n for (int i = 0; i < 10; ++i)\n for (int j = 0; j < count[i]; ++j)\n ans += i + '0';\n\n return ans;\n }\n};\n"} +{"task_num": 457, "task_title": "Circular Array Loop", "difficulty": 2, "func_name": "circularArrayLoop", "description": "You are playing a game involving a circular array of non-zero integers `nums`.\nEach `nums[i]` denotes the number of indices forward/backward you must move if\nyou are located at index `i`:\n\n* If `nums[i]` is positive, move `nums[i]` steps forward, and\n* If `nums[i]` is negative, move `nums[i]` steps backward.\n\nSince the array is circular, you may assume that moving forward from the last\nelement puts you on the first element, and moving backwards from the first\nelement puts you on the last element.\n\nA cycle in the array consists of a sequence of indices `seq` of length `k`\nwhere:\n\n* Following the movement rules above results in the repeating index sequence `seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...`\n* Every `nums[seq[j]]` is either all positive or all negative.\n* `k > 1`\n\nReturn `true` if there is a cycle in `nums`, or `false` otherwise.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def circularArrayLoop(self, nums: List[int]) -> bool:\n def advance(i: int) -> int:\n return (i + nums[i]) % len(nums)\n\n if len(nums) < 2:\n return False\n\n for i, num in enumerate(nums):\n if num == 0:\n continue\n\n slow = i\n fast = advance(slow)\n while num * nums[fast] > 0 and num * nums[advance(fast)] > 0:\n if slow == fast:\n if slow == advance(slow):\n break\n return True\n slow = advance(slow)\n fast = advance(advance(fast))\n\n slow = i\n sign = num\n while sign * nums[slow] > 0:\n next = advance(slow)\n nums[slow] = 0\n slow = next\n\n return False\n", "java_solution": "class Solution {\n public boolean circularArrayLoop(int[] nums) {\n if (nums.length < 2)\n return false;\n\n for (int i = 0; i < nums.length; ++i) {\n if (nums[i] == 0)\n continue;\n int slow = i;\n int fast = advance(nums, slow);\n while (nums[i] * nums[fast] > 0 && nums[i] * nums[advance(nums, fast)] > 0) {\n if (slow == fast) {\n if (slow == advance(nums, slow))\n break;\n return true;\n }\n slow = advance(nums, slow);\n fast = advance(nums, advance(nums, fast));\n }\n\n slow = i;\n final int sign = nums[i];\n while (sign * nums[slow] > 0) {\n final int next = advance(nums, slow);\n nums[slow] = 0;\n slow = next;\n }\n }\n\n return false;\n }\n\n private int advance(int[] nums, int i) {\n final int n = nums.length;\n final int val = (i + nums[i]) % n;\n return i + nums[i] >= 0 ? val : n + val;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool circularArrayLoop(vector& nums) {\n const int n = nums.size();\n if (n < 2)\n return false;\n\n auto advance = [&](int i) {\n const int val = (i + nums[i]) % n;\n return i + nums[i] >= 0 ? val : n + val;\n };\n\n for (int i = 0; i < n; ++i) {\n if (nums[i] == 0)\n continue;\n int slow = i;\n int fast = advance(slow);\n while (nums[i] * nums[fast] > 0 && nums[i] * nums[advance(fast)] > 0) {\n if (slow == fast) {\n if (slow == advance(slow))\n break;\n return true;\n }\n slow = advance(slow);\n fast = advance(advance(fast));\n }\n\n slow = i;\n const int sign = nums[i];\n while (sign * nums[slow] > 0) {\n const int next = advance(slow);\n nums[slow] = 0;\n slow = next;\n }\n }\n\n return false;\n }\n};\n"} +{"task_num": 524, "task_title": "Longest Word in Dictionary through Deleting", "difficulty": 2, "func_name": "findLongestWord", "description": "Given a string `s` and a string array `dictionary`, return the longest string\nin the dictionary that can be formed by deleting some of the given string\ncharacters. If there is more than one possible result, return the longest word\nwith the smallest lexicographical order. If there is no possible result,\nreturn the empty string.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def findLongestWord(self, s: str, d: List[str]) -> str:\n ans = ''\n\n for word in d:\n i = 0\n for c in s:\n if i < len(word) and c == word[i]:\n i += 1\n if i == len(word):\n if len(word) > len(ans) or len(word) == len(ans) and word < ans:\n ans = word\n\n return ans\n", "java_solution": "class Solution {\n public String findLongestWord(String s, List d) {\n String ans = \"\";\n\n for (final String word : d)\n if (isSubsequence(word, s))\n if (word.length() > ans.length() ||\n word.length() == ans.length() && word.compareTo(ans) < 0)\n ans = word;\n\n return ans;\n }\n\n // Returns true if a is a subsequence of b.\n private boolean isSubsequence(final String a, final String b) {\n int i = 0;\n for (final char c : b.toCharArray())\n if (i < a.length() && c == a.charAt(i))\n ++i;\n return i == a.length();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n string findLongestWord(string s, vector& d) {\n string ans;\n\n for (const string& word : d)\n if (isSubsequence(word, s))\n if (word.length() > ans.length() ||\n word.length() == ans.length() && word.compare(ans) < 0)\n ans = word;\n\n return ans;\n }\n\n private:\n // Returns true if a is a subsequence of b.\n bool isSubsequence(const string& a, const string& b) {\n int i = 0;\n for (const char c : b)\n if (i < a.length() && c == a[i])\n ++i;\n return i == a.length();\n };\n};\n"} +{"task_num": 542, "task_title": "01 Matrix", "difficulty": 2, "func_name": "updateMatrix", "description": "Given an `m x n` binary matrix `mat`, return the distance of the nearest `0`\nfor each cell.\n\nThe distance between two adjacent cells is `1`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(mat)\n n = len(mat[0])\n q = collections.deque()\n seen = [[False] * n for _ in range(m)]\n\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 0:\n q.append((i, j))\n seen[i][j] = True\n\n while q:\n i, j = q.popleft()\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if seen[x][y]:\n continue\n mat[x][y] = mat[i][j] + 1\n q.append((x, y))\n seen[x][y] = True\n\n return mat\n", "java_solution": "class Solution {\n public int[][] updateMatrix(int[][] mat) {\n final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n final int m = mat.length;\n final int n = mat[0].length;\n Queue> q = new ArrayDeque<>();\n boolean[][] seen = new boolean[m][n];\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (mat[i][j] == 0) {\n q.offer(new Pair<>(i, j));\n seen[i][j] = true;\n }\n\n while (!q.isEmpty()) {\n final int i = q.peek().getKey();\n final int j = q.poll().getValue();\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n mat[x][y] = mat[i][j] + 1;\n q.offer(new Pair<>(x, y));\n seen[x][y] = true;\n }\n }\n\n return mat;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector> updateMatrix(vector>& mat) {\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n const int m = mat.size();\n const int n = mat[0].size();\n queue> q;\n vector> seen(m, vector(n));\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (mat[i][j] == 0) {\n q.emplace(i, j);\n seen[i][j] = true;\n }\n\n while (!q.empty()) {\n const auto [i, j] = q.front();\n q.pop();\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n mat[x][y] = mat[i][j] + 1;\n q.emplace(x, y);\n seen[x][y] = true;\n }\n }\n\n return mat;\n }\n};\n"} +{"task_num": 547, "task_title": "Friend Circles", "difficulty": 2, "func_name": "findCircleNum", "description": "There are `n` cities. Some of them are connected, while some are not. If city\n`a` is connected directly with city `b`, and city `b` is connected directly\nwith city `c`, then city `a` is connected indirectly with city `c`.\n\nA province is a group of directly or indirectly connected cities and no other\ncities outside of the group.\n\nYou are given an `n x n` matrix `isConnected` where `isConnected[i][j] = 1` if\nthe `ith` city and the `jth` city are directly connected, and\n`isConnected[i][j] = 0` otherwise.\n\nReturn the total number of provinces.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.count = n\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n self.count -= 1\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def findCircleNum(self, isConnected: List[List[int]]) -> int:\n n = len(isConnected)\n uf = UnionFind(n)\n\n for i in range(n):\n for j in range(i, n):\n if isConnected[i][j] == 1:\n uf.unionByRank(i, j)\n\n return uf.count\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n count = n;\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public void unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n --count;\n }\n\n public int getCount() {\n return count;\n }\n\n private int count;\n private int[] id;\n private int[] rank;\n\n private int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n}\n\nclass Solution {\n public int findCircleNum(int[][] isConnected) {\n final int n = isConnected.length;\n UnionFind uf = new UnionFind(n);\n\n for (int i = 0; i < n; ++i)\n for (int j = i; j < n; ++j)\n if (isConnected[i][j] == 1)\n uf.unionByRank(i, j);\n\n return uf.getCount();\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : count(n), id(n), rank(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n void unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n --count;\n }\n\n int getCount() const {\n return count;\n }\n\n private:\n int count;\n vector id;\n vector rank;\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n};\n\nclass Solution {\n public:\n int findCircleNum(vector>& isConnected) {\n const int n = isConnected.size();\n UnionFind uf(n);\n\n for (int i = 0; i < n; ++i)\n for (int j = i; j < n; ++j)\n if (isConnected[i][j] == 1)\n uf.unionByRank(i, j);\n\n return uf.getCount();\n }\n};\n"} +{"task_num": 581, "task_title": "Shortest Unsorted Continuous Subarray", "difficulty": 2, "func_name": "findUnsortedSubarray", "description": "Given an integer array `nums`, you need to find one continuous subarray such\nthat if you only sort this subarray in non-decreasing order, then the whole\narray will be sorted in non-decreasing order.\n\nReturn the shortest such subarray and output its length.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def findUnsortedSubarray(self, nums: List[int]) -> int:\n mini = math.inf\n maxi = -math.inf\n flag = False\n\n for i in range(1, len(nums)):\n if nums[i] < nums[i - 1]:\n flag = True\n if flag:\n mini = min(mini, nums[i])\n\n flag = False\n\n for i in reversed(range(len(nums) - 1)):\n if nums[i] > nums[i + 1]:\n flag = True\n if flag:\n maxi = max(maxi, nums[i])\n\n for l in range(len(nums)):\n if nums[l] > mini:\n break\n\n for r, num in reversed(list(enumerate(nums))):\n if num < maxi:\n break\n\n return 0 if l >= r else r - l + 1\n", "java_solution": "class Solution {\n public int findUnsortedSubarray(int[] nums) {\n final int n = nums.length;\n int mn = Integer.MAX_VALUE;\n int mx = Integer.MIN_VALUE;\n boolean meetDecrease = false;\n boolean meetIncrease = false;\n\n for (int i = 1; i < n; ++i) {\n if (nums[i] < nums[i - 1])\n meetDecrease = true;\n if (meetDecrease)\n mn = Math.min(mn, nums[i]);\n }\n\n for (int i = n - 2; i >= 0; --i) {\n if (nums[i] > nums[i + 1])\n meetIncrease = true;\n if (meetIncrease)\n mx = Math.max(mx, nums[i]);\n }\n\n int l = 0;\n for (l = 0; l < n; ++l)\n if (nums[l] > mn)\n break;\n\n int r = 0;\n for (r = n - 1; r >= 0; --r)\n if (nums[r] < mx)\n break;\n\n return l > r ? 0 : r - l + 1;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int findUnsortedSubarray(vector& nums) {\n const int n = nums.size();\n int mn = INT_MAX;\n int mx = INT_MIN;\n bool meetDecrease = false;\n bool meetIncrease = false;\n\n for (int i = 1; i < n; ++i) {\n if (nums[i] < nums[i - 1])\n meetDecrease = true;\n if (meetDecrease)\n mn = min(mn, nums[i]);\n }\n\n for (int i = n - 2; i >= 0; --i) {\n if (nums[i] > nums[i + 1])\n meetIncrease = true;\n if (meetIncrease)\n mx = max(mx, nums[i]);\n }\n\n int l;\n for (l = 0; l < n; ++l)\n if (nums[l] > mn)\n break;\n\n int r;\n for (r = n - 1; r >= 0; --r)\n if (nums[r] < mx)\n break;\n\n return l < r ? r - l + 1 : 0;\n }\n};\n"} +{"task_num": 591, "task_title": "Tag Validator", "difficulty": 3, "func_name": "isValid", "description": "Given a string representing a code snippet, implement a tag validator to parse\nthe code and return whether it is valid.\n\nA code snippet is valid if all the following rules hold:\n\n1. The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.\n2. A closed tag (not necessarily valid) has exactly the following format : `TAG_CONTENT`. Among them, `` is the start tag, and `` is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid.\n3. A valid `TAG_NAME` only contain upper-case letters, and has length in range [1,9]. Otherwise, the `TAG_NAME` is invalid.\n4. A valid `TAG_CONTENT` may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched `<`, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the `TAG_CONTENT` is invalid.\n5. A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.\n6. A `<` is unmatched if you cannot find a subsequent `>`. And when you find a `<` or `` should be parsed as TAG_NAME (not necessarily valid).\n7. The cdata has the following format : ``. The range of `CDATA_CONTENT` is defined as the characters between ``.\n8. `CDATA_CONTENT` may contain any characters. The function of cdata is to forbid the validator to parse `CDATA_CONTENT`, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def isValid(self, code: str) -> bool:\n if code[0] != '<' or code[-1] != '>':\n return False\n\n containsTag = False\n stack = []\n\n def isValidCdata(s: str) -> bool:\n return s.find('[CDATA[') == 0\n\n def isValidTagName(tagName: str, isEndTag: bool) -> bool:\n nonlocal containsTag\n if not tagName or len(tagName) > 9:\n return False\n if any(not c.isupper() for c in tagName):\n return False\n\n if isEndTag:\n return stack and stack.pop() == tagName\n\n containsTag = True\n stack.append(tagName)\n return True\n\n i = 0\n while i < len(code):\n if not stack and containsTag:\n return False\n if code[i] == '<':\n if stack and code[i + 1] == '!':\n closeIndex = code.find(']]>', i + 2)\n if closeIndex == -1 or not isValidCdata(code[i + 2:closeIndex]):\n return False\n elif code[i + 1] == '/':\n closeIndex = code.find('>', i + 2)\n if closeIndex == -1 or not isValidTagName(code[i + 2:closeIndex], True):\n return False\n else:\n closeIndex = code.find('>', i + 1)\n if closeIndex == -1 or not isValidTagName(code[i + 1:closeIndex], False):\n return False\n i = closeIndex\n i += 1\n\n return not stack and containsTag\n", "java_solution": "class Solution {\n public boolean isValid(String code) {\n if (code.charAt(0) != '<' || code.charAt(code.length() - 1) != '>')\n return false;\n\n Deque stack = new ArrayDeque<>();\n\n for (int i = 0; i < code.length(); ++i) {\n int closeIndex = 0;\n if (stack.isEmpty() && containsTag)\n return false;\n if (code.charAt(i) == '<') {\n // It's inside a tag, so check if it's a cdata.\n if (!stack.isEmpty() && code.charAt(i + 1) == '!') {\n closeIndex = code.indexOf(\"]]>\", i + 2);\n if (closeIndex < 0 || !isValidCdata(code.substring(i + 2, closeIndex)))\n return false;\n } else if (code.charAt(i + 1) == '/') { // the end tag\n closeIndex = code.indexOf('>', i + 2);\n if (closeIndex < 0 || !isValidTagName(stack, code.substring(i + 2, closeIndex), true))\n return false;\n } else { // the start tag\n closeIndex = code.indexOf('>', i + 1);\n if (closeIndex < 0 || !isValidTagName(stack, code.substring(i + 1, closeIndex), false))\n return false;\n }\n i = closeIndex;\n }\n }\n\n return stack.isEmpty() && containsTag;\n }\n\n private boolean containsTag = false;\n\n private boolean isValidCdata(final String s) {\n return s.indexOf(\"[CDATA[\") == 0;\n }\n\n private boolean isValidTagName(Deque stack, String tagName, boolean isEndTag) {\n if (tagName.isEmpty() || tagName.length() > 9)\n return false;\n\n for (final char c : tagName.toCharArray())\n if (!Character.isUpperCase(c))\n return false;\n\n if (isEndTag)\n return !stack.isEmpty() && stack.pop().equals(tagName);\n\n containsTag = true;\n stack.push(tagName);\n return true;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool isValid(string code) {\n if (code[0] != '<' || code.back() != '>')\n return false;\n\n stack stack;\n\n for (int i = 0; i < code.length(); ++i) {\n int closeIndex = 0;\n if (stack.empty() && containsTag)\n return false;\n if (code[i] == '<') {\n // It's inside a tag, so check if it's a cdata.\n if (!stack.empty() && code[i + 1] == '!') {\n closeIndex = code.find(\"]]>\", i + 2);\n if (closeIndex == string::npos ||\n !isValidCdata(code.substr(i + 2, closeIndex - i - 2)))\n return false;\n } else if (code[i + 1] == '/') { // the end tag\n closeIndex = code.find('>', i + 2);\n if (closeIndex == string::npos ||\n !isValidTagName(stack, code.substr(i + 2, closeIndex - i - 2),\n true))\n return false;\n } else { // the start tag\n closeIndex = code.find('>', i + 1);\n if (closeIndex == string::npos ||\n !isValidTagName(stack, code.substr(i + 1, closeIndex - i - 1),\n false))\n return false;\n }\n i = closeIndex;\n }\n }\n\n return stack.empty() && containsTag;\n }\n\n private:\n bool containsTag = false;\n\n bool isValidCdata(const string& s) {\n return s.find(\"[CDATA[\") == 0;\n }\n\n bool isValidTagName(stack& stack, const string& tagName,\n bool isEndTag) {\n if (tagName.empty() || tagName.length() > 9)\n return false;\n\n for (const char c : tagName)\n if (!isupper(c))\n return false;\n\n if (isEndTag) {\n if (stack.empty())\n return false;\n if (stack.top() != tagName)\n return false;\n stack.pop();\n return true;\n }\n\n containsTag = true;\n stack.push(tagName);\n return true;\n }\n};\n"} +{"task_num": 648, "task_title": "Replace Words", "difficulty": 2, "func_name": "replaceWords", "description": "In English, we have a concept called root, which can be followed by some other\nword to form another longer word - let's call this word successor. For\nexample, when the root `\"help\"` is followed by the successor word `\"ful\"`, we\ncan form a new word `\"helpful\"`.\n\nGiven a `dictionary` consisting of many roots and a `sentence` consisting of\nwords separated by spaces, replace all the successors in the sentence with the\nroot forming it. If a successor can be replaced by more than one root, replace\nit with the root that has the shortest length.\n\nReturn the `sentence` after the replacement.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def __init__(self):\n self.root = {}\n\n def insert(self, word: str) -> None:\n node = self.root\n for c in word:\n if c not in node:\n node[c] = {}\n node = node[c]\n node['word'] = word\n\n def search(self, word: str) -> str:\n node = self.root\n for c in word:\n if 'word' in node:\n return node['word']\n if c not in node:\n return word\n node = node[c]\n return word\n\n def replaceWords(self, dictionary: List[str], sentence: str) -> str:\n for word in dictionary:\n self.insert(word)\n\n words = sentence.split(' ')\n return ' '.join([self.search(word) for word in words])\n", "java_solution": "class TrieNode {\n TrieNode[] children = new TrieNode[26];\n String word;\n}\n\nclass Solution {\n public String replaceWords(List dictionary, String sentence) {\n StringBuilder sb = new StringBuilder();\n\n for (final String word : dictionary)\n insert(word);\n\n final String[] words = sentence.split(\" \");\n for (final String word : words)\n sb.append(' ').append(search(word));\n\n return sb.substring(1).toString();\n }\n\n private TrieNode root = new TrieNode();\n\n private void insert(final String word) {\n TrieNode node = root;\n for (char c : word.toCharArray()) {\n final int i = c - 'a';\n if (node.children[i] == null)\n node.children[i] = new TrieNode();\n node = node.children[i];\n }\n node.word = word;\n }\n\n private String search(final String word) {\n TrieNode node = root;\n for (char c : word.toCharArray()) {\n if (node.word != null)\n return node.word;\n final int i = c - 'a';\n if (node.children[i] == null)\n return word;\n node = node.children[i];\n }\n return word;\n }\n}\n", "cpp_solution": "struct TrieNode {\n vector> children;\n const string* word = nullptr;\n TrieNode() : children(26) {}\n};\n\nclass Solution {\n public:\n string replaceWords(vector& dictionary, string sentence) {\n for (const string& word : dictionary)\n insert(word);\n\n string ans;\n istringstream iss(sentence);\n\n for (string s; iss >> s;)\n ans += search(s) + ' ';\n ans.pop_back();\n\n return ans;\n }\n\n private:\n shared_ptr root = make_shared();\n\n void insert(const string& word) {\n shared_ptr node = root;\n for (const char c : word) {\n const int i = c - 'a';\n if (node->children[i] == nullptr)\n node->children[i] = make_shared();\n node = node->children[i];\n }\n node->word = &word;\n }\n\n string search(const string& word) {\n shared_ptr node = root;\n for (const char c : word) {\n if (node->word)\n return *node->word;\n const int i = c - 'a';\n if (node->children[i] == nullptr)\n return word;\n node = node->children[i];\n }\n return word;\n }\n};\n"} +{"task_num": 673, "task_title": "Number of Longest Increasing Subsequence", "difficulty": 2, "func_name": "findNumberOfLIS", "description": "Given an integer array `nums`, return the number of longest increasing\nsubsequences.\n\nNotice that the sequence has to be strictly increasing.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def findNumberOfLIS(self, nums: List[int]) -> int:\n ans = 0\n maxLength = 0\n length = [1] * len(nums)\n count = [1] * len(nums)\n\n for i, num in enumerate(nums):\n for j in range(i):\n if nums[j] < num:\n if length[i] < length[j] + 1:\n length[i] = length[j] + 1\n count[i] = count[j]\n elif length[i] == length[j] + 1:\n count[i] += count[j]\n\n for i, l in enumerate(length):\n if l > maxLength:\n maxLength = l\n ans = count[i]\n elif l == maxLength:\n ans += count[i]\n\n return ans\n", "java_solution": "class Solution {\n public int findNumberOfLIS(int[] nums) {\n final int n = nums.length;\n int ans = 0;\n int maxLength = 0;\n // length[i] := the length of the LIS ending in nums[i]\n int[] length = new int[n];\n // count[i] := the number of LIS's ending in nums[i]\n int[] count = new int[n];\n\n Arrays.fill(length, 1);\n Arrays.fill(count, 1);\n\n // Calculate the `length` and `count` arrays.\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < i; ++j)\n if (nums[j] < nums[i])\n if (length[i] < length[j] + 1) {\n length[i] = length[j] + 1;\n count[i] = count[j];\n } else if (length[i] == length[j] + 1) {\n count[i] += count[j];\n }\n\n // Get the number of LIS.\n for (int i = 0; i < n; ++i)\n if (length[i] > maxLength) {\n maxLength = length[i];\n ans = count[i];\n } else if (length[i] == maxLength) {\n ans += count[i];\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int findNumberOfLIS(vector& nums) {\n const int n = nums.size();\n int ans = 0;\n int maxLength = 0;\n // length[i] := the length of LIS's ending in nums[i]\n vector length(n, 1);\n // count[i] := the number of LIS's ending in nums[i]\n vector count(n, 1);\n\n // Calculate `length` and `count` arrays.\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < i; ++j)\n if (nums[j] < nums[i])\n if (length[i] < length[j] + 1) {\n length[i] = length[j] + 1;\n count[i] = count[j];\n } else if (length[i] == length[j] + 1) {\n count[i] += count[j];\n }\n\n // Get the number of LIS.\n for (int i = 0; i < n; ++i)\n if (length[i] > maxLength) {\n maxLength = length[i];\n ans = count[i];\n } else if (length[i] == maxLength) {\n ans += count[i];\n }\n\n return ans;\n }\n};\n"} +{"task_num": 684, "task_title": "Redundant Connection", "difficulty": 2, "func_name": "findRedundantConnection", "description": "In this problem, a tree is an undirected graph that is connected and has no\ncycles.\n\nYou are given a graph that started as a tree with `n` nodes labeled from `1`\nto `n`, with one additional edge added. The added edge has two different\nvertices chosen from `1` to `n`, and was not an edge that already existed. The\ngraph is represented as an array `edges` of length `n` where `edges[i] = [ai,\nbi]` indicates that there is an edge between nodes `ai` and `bi` in the graph.\n\nReturn an edge that can be removed so that the resulting graph is a tree of\n`n` nodes. If there are multiple answers, return the answer that occurs last\nin the input.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> bool:\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return False\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n return True\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:\n uf = UnionFind(len(edges) + 1)\n\n for edge in edges:\n u, v = edge\n if not uf.unionByRank(u, v):\n return edge\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public boolean unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return false;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n return true;\n }\n\n private int[] id;\n private int[] rank;\n\n private int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n}\n\nclass Solution {\n public int[] findRedundantConnection(int[][] edges) {\n UnionFind uf = new UnionFind(edges.length + 1);\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n if (!uf.unionByRank(u, v))\n return edge;\n }\n\n throw new IllegalArgumentException();\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n), rank(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n bool unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return false;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n return true;\n }\n\n private:\n vector id;\n vector rank;\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n};\n\nclass Solution {\n public:\n vector findRedundantConnection(vector>& edges) {\n UnionFind uf(edges.size() + 1);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n if (!uf.unionByRank(u, v))\n return edge;\n }\n\n throw;\n }\n};\n"} +{"task_num": 685, "task_title": "Redundant Connection II", "difficulty": 3, "func_name": "findRedundantDirectedConnection", "description": "In this problem, a rooted tree is a directed graph such that, there is exactly\none node (the root) for which all other nodes are descendants of this node,\nplus every node has exactly one parent, except for the root node which has no\nparents.\n\nThe given input is a directed graph that started as a rooted tree with `n`\nnodes (with distinct values from `1` to `n`), with one additional directed\nedge added. The added edge has two different vertices chosen from `1` to `n`,\nand was not an edge that already existed.\n\nThe resulting graph is given as a 2D-array of `edges`. Each element of `edges`\nis a pair `[ui, vi]` that represents a directed edge connecting nodes `ui` and\n`vi`, where `ui` is a parent of child `vi`.\n\nReturn an edge that can be removed so that the resulting graph is a rooted\ntree of `n` nodes. If there are multiple answers, return the answer that\noccurs last in the given 2D-array.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> bool:\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return False\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n return True\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:\n ids = [0] * (len(edges) + 1)\n nodeWithTwoParents = 0\n\n for _, v in edges:\n ids[v] += 1\n if ids[v] == 2:\n nodeWithTwoParents = v\n\n def findRedundantDirectedConnection(skippedEdgeIndex: int) -> List[int]:\n uf = UnionFind(len(edges) + 1)\n\n for i, edge in enumerate(edges):\n if i == skippedEdgeIndex:\n continue\n if not uf.unionByRank(edge[0], edge[1]):\n return edge\n\n return []\n\n if nodeWithTwoParents == 0:\n return findRedundantDirectedConnection(-1)\n\n for i in reversed(range(len(edges))):\n _, v = edges[i]\n if v == nodeWithTwoParents:\n if not findRedundantDirectedConnection(i):\n return edges[i]\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public boolean unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return false;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n return true;\n }\n\n private int[] id;\n private int[] rank;\n\n private int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n}\n\nclass Solution {\n public int[] findRedundantDirectedConnection(int[][] edges) {\n int[] ids = new int[edges.length + 1];\n int nodeWithTwoParents = 0;\n\n for (int[] edge : edges) {\n final int v = edge[1];\n if (++ids[v] == 2) {\n nodeWithTwoParents = v;\n break;\n }\n }\n\n // If there is no edge with two ids, don't skip any edge.\n if (nodeWithTwoParents == 0)\n return findRedundantDirectedConnection(edges, -1);\n\n for (int i = edges.length - 1; i >= 0; --i)\n if (edges[i][1] == nodeWithTwoParents)\n // Try to delete the edges[i].\n if (findRedundantDirectedConnection(edges, i).length == 0)\n return edges[i];\n\n throw new IllegalArgumentException();\n }\n\n private int[] findRedundantDirectedConnection(int[][] edges, int skippedEdgeIndex) {\n UnionFind uf = new UnionFind(edges.length + 1);\n\n for (int i = 0; i < edges.length; ++i) {\n if (i == skippedEdgeIndex)\n continue;\n if (!uf.unionByRank(edges[i][0], edges[i][1]))\n return edges[i];\n }\n\n return new int[] {};\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n), rank(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n bool unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return false;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n return true;\n }\n\n private:\n vector id;\n vector rank;\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n};\n\nclass Solution {\n public:\n vector findRedundantDirectedConnection(vector>& edges) {\n vector ids(edges.size() + 1);\n int nodeWithTwoParents = 0;\n\n for (const vector& edge : edges) {\n const int v = edge[1];\n if (++ids[v] == 2) {\n nodeWithTwoParents = v;\n break;\n }\n }\n\n // If there is no edge with two ids, don't skip any edge.\n if (nodeWithTwoParents == 0)\n return findRedundantDirectedConnection(edges, -1);\n\n for (int i = edges.size() - 1; i >= 0; --i)\n if (edges[i][1] == nodeWithTwoParents)\n // Try to delete the edges[i].\n if (findRedundantDirectedConnection(edges, i).empty())\n return edges[i];\n\n throw;\n }\n\n vector findRedundantDirectedConnection(const vector>& edges,\n int skippedEdgeIndex) {\n UnionFind uf(edges.size() + 1);\n\n for (int i = 0; i < edges.size(); ++i) {\n if (i == skippedEdgeIndex)\n continue;\n if (!uf.unionByRank(edges[i][0], edges[i][1]))\n return edges[i];\n }\n\n return {};\n }\n};\n"} +{"task_num": 688, "task_title": "Knight Probability in Chessboard", "difficulty": 2, "func_name": "knightProbability", "description": "On an `n x n` chessboard, a knight starts at the cell `(row, column)` and\nattempts to make exactly `k` moves. The rows and columns are 0-indexed, so the\ntop-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.\n\nA chess knight has eight possible moves it can make, as illustrated below.\nEach move is two cells in a cardinal direction, then one cell in an orthogonal\ndirection.\n\nEach time the knight is to move, it chooses one of eight possible moves\nuniformly at random (even if the piece would go off the chessboard) and moves\nthere.\n\nThe knight continues moving until it has made exactly `k` moves or has moved\noff the chessboard.\n\nReturn the probability that the knight remains on the board after it has\nstopped moving.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def knightProbability(self, n: int, k: int, row: int, column: int) -> float:\n dirs = ((1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2))\n dp = [[0] * n for _ in range(n)]\n dp[row][column] = 1.0\n\n for _ in range(k):\n newDp = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if 0 <= x < n and 0 <= y < n:\n newDp[i][j] += dp[x][y]\n dp = newDp\n\n return sum(map(sum, dp)) / 8**k\n", "java_solution": "class Solution {\n public double knightProbability(int n, int k, int row, int column) {\n final int[][] DIRS = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}};\n final double PROB = 0.125;\n // dp[i][j] := the probability to stand on (i, j)\n double[][] dp = new double[n][n];\n dp[row][column] = 1.0;\n\n for (int move = 0; move < k; ++move) {\n double[][] newDp = new double[n][n];\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n if (dp[i][j] > 0.0) {\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x >= n || y < 0 || y >= n)\n continue;\n newDp[x][y] += dp[i][j] * PROB;\n }\n }\n dp = newDp;\n }\n\n return Arrays.stream(dp).flatMapToDouble(Arrays::stream).sum();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n double knightProbability(int n, int k, int row, int column) {\n constexpr int kDirs[8][2] = {{1, 2}, {2, 1}, {2, -1}, {1, -2},\n {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}};\n constexpr double kProb = 0.125;\n // dp[i][j] := the probability to stand on (i, j)\n vector> dp(n, vector(n));\n dp[row][column] = 1.0;\n\n for (int move = 0; move < k; ++move) {\n vector> newDp(n, vector(n));\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n if (dp[i][j] > 0.0) {\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x >= n || y < 0 || y >= n)\n continue;\n newDp[x][y] += dp[i][j] * kProb;\n }\n }\n dp = std::move(newDp);\n }\n\n return accumulate(dp.begin(), dp.end(), 0.0,\n [](double acc, const vector& row) {\n return acc + accumulate(row.begin(), row.end(), 0.0);\n });\n }\n};\n"} +{"task_num": 689, "task_title": "Maximum Sum of 3 Non-Overlapping Subarrays", "difficulty": 3, "func_name": "maxSumOfThreeSubarrays", "description": "Given an integer array `nums` and an integer `k`, find three non-overlapping\nsubarrays of length `k` with maximum sum and return them.\n\nReturn the result as a list of indices representing the starting position of\neach interval (0-indexed). If there are multiple answers, return the\nlexicographically smallest one.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:\n n = len(nums) - k + 1\n sums = [0] * n\n l = [0] * n\n r = [0] * n\n\n summ = 0\n for i, num in enumerate(nums):\n summ += num\n if i >= k:\n summ -= nums[i - k]\n if i >= k - 1:\n sums[i - k + 1] = summ\n\n maxIndex = 0\n for i in range(n):\n if sums[i] > sums[maxIndex]:\n maxIndex = i\n l[i] = maxIndex\n\n maxIndex = n - 1\n for i in range(n - 1, -1, -1):\n if sums[i] >= sums[maxIndex]:\n maxIndex = i\n r[i] = maxIndex\n\n ans = [-1, -1, -1]\n\n for i in range(k, n - k):\n if ans[0] == -1 or sums[ans[0]] + sums[ans[1]] + sums[ans[2]] < sums[l[i - k]] + sums[i] + sums[r[i + k]]:\n ans[0] = l[i - k]\n ans[1] = i\n ans[2] = r[i + k]\n\n return ans\n", "java_solution": "class Solution {\n public int[] maxSumOfThreeSubarrays(int[] nums, int k) {\n final int n = nums.length - k + 1;\n // sums[i] := sum(nums[i..i + k))\n int[] sums = new int[n];\n // l[i] := the index in [0..i] that has the maximum sums[i]\n int[] l = new int[n];\n // r[i] := the index in [i..n) that has the maximum sums[i]\n int[] r = new int[n];\n\n int sum = 0;\n for (int i = 0; i < nums.length; ++i) {\n sum += nums[i];\n if (i >= k)\n sum -= nums[i - k];\n if (i >= k - 1)\n sums[i - k + 1] = sum;\n }\n\n int maxIndex = 0;\n for (int i = 0; i < n; ++i) {\n if (sums[i] > sums[maxIndex])\n maxIndex = i;\n l[i] = maxIndex;\n }\n\n maxIndex = n - 1;\n for (int i = n - 1; i >= 0; --i) {\n if (sums[i] >= sums[maxIndex])\n maxIndex = i;\n r[i] = maxIndex;\n }\n\n int[] ans = {-1, -1, -1};\n\n for (int i = k; i + k < n; ++i)\n if (ans[0] == -1 ||\n sums[ans[0]] + sums[ans[1]] + sums[ans[2]] < sums[l[i - k]] + sums[i] + sums[r[i + k]]) {\n ans[0] = l[i - k];\n ans[1] = i;\n ans[2] = r[i + k];\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector maxSumOfThreeSubarrays(vector& nums, int k) {\n const int n = nums.size() - k + 1;\n // sums[i] := sum(nums[i..i + k))\n vector sums(n);\n // l[i] := the index in [0..i] that has the maximum sums[i]\n vector l(n);\n // r[i] := the index in [i..n) that has the maximum sums[i]\n vector r(n);\n\n int sum = 0;\n for (int i = 0; i < nums.size(); ++i) {\n sum += nums[i];\n if (i >= k)\n sum -= nums[i - k];\n if (i >= k - 1)\n sums[i - k + 1] = sum;\n }\n\n int maxIndex = 0;\n for (int i = 0; i < n; ++i) {\n if (sums[i] > sums[maxIndex])\n maxIndex = i;\n l[i] = maxIndex;\n }\n\n maxIndex = n - 1;\n for (int i = n - 1; i >= 0; --i) {\n if (sums[i] >= sums[maxIndex])\n maxIndex = i;\n r[i] = maxIndex;\n }\n\n vector ans{-1, -1, -1};\n\n for (int i = k; i < n - k; ++i)\n if (ans[0] == -1 || sums[ans[0]] + sums[ans[1]] + sums[ans[2]] <\n sums[l[i - k]] + sums[i] + sums[r[i + k]]) {\n ans[0] = l[i - k];\n ans[1] = i;\n ans[2] = r[i + k];\n }\n\n return ans;\n }\n};\n"} +{"task_num": 691, "task_title": "Stickers to Spell Word", "difficulty": 3, "func_name": "minStickers", "description": "We are given `n` different types of `stickers`. Each sticker has a lowercase\nEnglish word on it.\n\nYou would like to spell out the given string `target` by cutting individual\nletters from your collection of stickers and rearranging them. You can use\neach sticker more than once if you want, and you have infinite quantities of\neach sticker.\n\nReturn the minimum number of stickers that you need to spell out `target`. If\nthe task is impossible, return `-1`.\n\nNote: In all test cases, all words were chosen randomly from the `1000` most\ncommon US English words, and `target` was chosen as a concatenation of two\nrandom words.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minStickers(self, stickers: List[str], target: str) -> int:\n maxMask = 1 << len(target)\n dp = [math.inf] * maxMask\n dp[0] = 0\n\n for mask in range(maxMask):\n if dp[mask] == math.inf:\n continue\n for sticker in stickers:\n superMask = mask\n for c in sticker:\n for i, t in enumerate(target):\n if c == t and not (superMask >> i & 1):\n superMask |= 1 << i\n break\n dp[superMask] = min(dp[superMask], dp[mask] + 1)\n\n return -1 if dp[-1] == math.inf else dp[-1]\n", "java_solution": "class Solution {\n public int minStickers(String[] stickers, String target) {\n final int n = target.length();\n final int maxMask = 1 << n;\n // dp[i] := the minimum number of stickers to spell out i, where i is the\n // bit mask of target\n int[] dp = new int[maxMask];\n Arrays.fill(dp, Integer.MAX_VALUE);\n dp[0] = 0;\n\n for (int mask = 0; mask < maxMask; ++mask) {\n if (dp[mask] == Integer.MAX_VALUE)\n continue;\n // Try to expand from `mask` by using each sticker.\n for (final String sticker : stickers) {\n int superMask = mask;\n for (final char c : sticker.toCharArray())\n for (int i = 0; i < n; ++i)\n // Try to apply it on a missing letter.\n if (c == target.charAt(i) && (superMask >> i & 1) == 0) {\n superMask |= 1 << i;\n break;\n }\n dp[superMask] = Math.min(dp[superMask], dp[mask] + 1);\n }\n }\n\n return dp[maxMask - 1] == Integer.MAX_VALUE ? -1 : dp[maxMask - 1];\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minStickers(vector& stickers, string target) {\n const int n = target.size();\n const int maxMask = 1 << n;\n // dp[i] := the minimum number of stickers to spell out i, where i is the\n // bit mask of target\n vector dp(maxMask, INT_MAX);\n dp[0] = 0;\n\n for (int mask = 0; mask < maxMask; ++mask) {\n if (dp[mask] == INT_MAX)\n continue;\n // Try to expand from `mask` by using each sticker.\n for (const string& sticker : stickers) {\n int superMask = mask;\n for (const char c : sticker)\n for (int i = 0; i < n; ++i)\n // Try to apply it on a missing letter.\n if (c == target[i] && (superMask >> i & 1) == 0) {\n superMask |= 1 << i;\n break;\n }\n dp[superMask] = min(dp[superMask], dp[mask] + 1);\n }\n }\n\n return dp.back() == INT_MAX ? -1 : dp.back();\n }\n};\n"} +{"task_num": 722, "task_title": "Remove Comments", "difficulty": 2, "func_name": "removeComments", "description": "Given a C++ program, remove comments from it. The program source is an array\nof strings `source` where `source[i]` is the `ith` line of the source code.\nThis represents the result of splitting the original source code string by the\nnewline character `'\\n'`.\n\nIn C++, there are two types of comments, line comments, and block comments.\n\n* The string `\"//\"` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.\n* The string `\"/*\"` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `\"*/\"` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `\"/*/\"` does not yet end the block comment, as the ending would be overlapping the beginning.\n\nThe first effective comment takes precedence over others.\n\n* For example, if the string `\"//\"` occurs in a block comment, it is ignored.\n* Similarly, if the string `\"/*\"` occurs in a line or block comment, it is also ignored.\n\nIf a certain line of code is empty after removing comments, you must not\noutput that line: each string in the answer list will be non-empty.\n\nThere will be no control characters, single quote, or double quote characters.\n\n* For example, `source = \"string s = \"/* Not a comment. */\";\"` will not be a test case.\n\nAlso, nothing else such as defines or macros will interfere with the comments.\n\nIt is guaranteed that every open block comment will eventually be closed, so\n`\"/*\"` outside of a line or block comment always starts a new comment.\n\nFinally, implicit newline characters can be deleted by block comments. Please\nsee the examples below for details.\n\nAfter removing the comments from the source code, return the source code in\nthe same format.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def removeComments(self, source: List[str]) -> List[str]:\n ans = []\n commenting = False\n modified = ''\n\n for line in source:\n i = 0\n while i < len(line):\n if i + 1 == len(line):\n if not commenting:\n modified += line[i]\n i += 1\n break\n twoChars = line[i:i + 2]\n if twoChars == '/*' and not commenting:\n commenting = True\n i += 2\n elif twoChars == '*/' and commenting:\n commenting = False\n i += 2\n elif twoChars == '//':\n if not commenting:\n break\n else:\n i += 2\n else:\n if not commenting:\n modified += line[i]\n i += 1\n if modified and not commenting:\n ans.append(modified)\n modified = ''\n\n return ans\n", "java_solution": "class Solution {\n public List removeComments(String[] source) {\n List ans = new ArrayList<>();\n boolean commenting = false;\n StringBuilder modified = new StringBuilder();\n\n for (final String line : source) {\n for (int i = 0; i < line.length();) {\n if (i + 1 == line.length()) {\n if (!commenting)\n modified.append(line.charAt(i));\n ++i;\n break;\n }\n String twoChars = line.substring(i, i + 2);\n if (twoChars.equals(\"/*\") && !commenting) {\n commenting = true;\n i += 2;\n } else if (twoChars.equals(\"*/\") && commenting) {\n commenting = false;\n i += 2;\n } else if (twoChars.equals(\"//\")) {\n if (!commenting)\n break;\n else\n i += 2;\n } else {\n if (!commenting)\n modified.append(line.charAt(i));\n ++i;\n }\n }\n if (modified.length() > 0 && !commenting) {\n ans.add(modified.toString());\n modified.setLength(0);\n }\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector removeComments(vector& source) {\n vector ans;\n bool commenting = false;\n string modified;\n\n for (const string& line : source) {\n for (int i = 0; i < line.length();) {\n if (i + 1 == line.length()) {\n if (!commenting)\n modified += line[i];\n ++i;\n break;\n }\n const string& twoChars = line.substr(i, 2);\n if (twoChars == \"/*\" && !commenting) {\n commenting = true;\n i += 2;\n } else if (twoChars == \"*/\" && commenting) {\n commenting = false;\n i += 2;\n } else if (twoChars == \"//\") {\n if (!commenting)\n break;\n else\n i += 2;\n } else {\n if (!commenting)\n modified += line[i];\n ++i;\n }\n }\n if (modified.length() > 0 && !commenting) {\n ans.push_back(modified);\n modified = \"\";\n }\n }\n\n return ans;\n }\n};\n"} +{"task_num": 730, "task_title": "Count Different Palindromic Subsequences", "difficulty": 3, "func_name": "countPalindromicSubsequences", "description": "Given a string s, return the number of different non-empty palindromic\nsubsequences in `s`. Since the answer may be very large, return it modulo `109\n+ 7`.\n\nA subsequence of a string is obtained by deleting zero or more characters from\nthe string.\n\nA sequence is palindromic if it is equal to the sequence reversed.\n\nTwo sequences `a1, a2, ...` and `b1, b2, ...` are different if there is some\n`i` for which `ai != bi`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def countPalindromicSubsequences(self, s: str) -> int:\n kMod = 1_000_000_007\n n = len(s)\n dp = [[0] * n for _ in range(n)]\n\n for i in range(n):\n dp[i][i] = 1\n\n for d in range(1, n):\n for i in range(n - d):\n j = i + d\n if s[i] == s[j]:\n lo = i + 1\n hi = j - 1\n while lo <= hi and s[lo] != s[i]:\n lo += 1\n while lo <= hi and s[hi] != s[i]:\n hi -= 1\n if lo > hi:\n dp[i][j] = dp[i + 1][j - 1] * 2 + 2\n elif lo == hi:\n dp[i][j] = dp[i + 1][j - 1] * 2 + 1\n else:\n dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1]\n else:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]\n dp[i][j] = (dp[i][j] + kMod) % kMod\n\n return dp[0][n - 1]\n", "java_solution": "class Solution {\n public int countPalindromicSubsequences(String s) {\n final int MOD = 1_000_000_007;\n final int n = s.length();\n // dp[i][j] := the number of different non-empty palindromic subsequences in\n // s[i..j]\n int[][] dp = new int[n][n];\n\n for (int i = 0; i < n; ++i)\n dp[i][i] = 1;\n\n for (int d = 1; d < n; ++d)\n for (int i = 0; i + d < n; ++i) {\n final int j = i + d;\n if (s.charAt(i) == s.charAt(j)) {\n int lo = i + 1;\n int hi = j - 1;\n while (lo <= hi && s.charAt(lo) != s.charAt(i))\n ++lo;\n while (lo <= hi && s.charAt(hi) != s.charAt(i))\n --hi;\n if (lo > hi)\n dp[i][j] = dp[i + 1][j - 1] * 2 + 2;\n else if (lo == hi)\n dp[i][j] = dp[i + 1][j - 1] * 2 + 1;\n else\n dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1];\n } else {\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1];\n }\n dp[i][j] = (int) ((dp[i][j] + MOD) % MOD);\n }\n\n return dp[0][n - 1];\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int countPalindromicSubsequences(string s) {\n constexpr int kMod = 1'000'000'007;\n const int n = s.length();\n // dp[i][j] := the number of different non-empty palindromic subsequences in\n // s[i..j]\n vector> dp(n, vector(n));\n\n for (int i = 0; i < n; ++i)\n dp[i][i] = 1;\n\n for (int d = 1; d < n; ++d)\n for (int i = 0; i + d < n; ++i) {\n const int j = i + d;\n if (s[i] == s[j]) {\n int lo = i + 1;\n int hi = j - 1;\n while (lo <= hi && s[lo] != s[i])\n ++lo;\n while (lo <= hi && s[hi] != s[i])\n --hi;\n if (lo > hi)\n dp[i][j] = dp[i + 1][j - 1] * 2 + 2;\n else if (lo == hi)\n dp[i][j] = dp[i + 1][j - 1] * 2 + 1;\n else\n dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1];\n } else {\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1];\n }\n dp[i][j] = (dp[i][j] + kMod) % kMod;\n }\n\n return dp[0][n - 1];\n }\n};\n"} +{"task_num": 735, "task_title": "Asteroid Collision", "difficulty": 2, "func_name": "asteroidCollision", "description": "We are given an array `asteroids` of integers representing asteroids in a row.\n\nFor each asteroid, the absolute value represents its size, and the sign\nrepresents its direction (positive meaning right, negative meaning left). Each\nasteroid moves at the same speed.\n\nFind out the state of the asteroids after all collisions. If two asteroids\nmeet, the smaller one will explode. If both are the same size, both will\nexplode. Two asteroids moving in the same direction will never meet.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n stack = []\n\n for a in asteroids:\n if a > 0:\n stack.append(a)\n else:\n while stack and stack[-1] > 0 and stack[-1] < -a:\n stack.pop()\n if not stack or stack[-1] < 0:\n stack.append(a)\n elif stack[-1] == -a:\n stack.pop()\n else:\n pass\n\n return stack\n", "java_solution": "class Solution {\n public int[] asteroidCollision(int[] asteroids) {\n Stack stack = new Stack<>();\n\n for (final int a : asteroids)\n if (a > 0) {\n stack.push(a);\n } else { // a < 0\n // Destroy the previous positive one(s).\n while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < -a)\n stack.pop();\n if (stack.isEmpty() || stack.peek() < 0)\n stack.push(a);\n else if (stack.peek() == -a)\n stack.pop(); // Both asteroids explode.\n else // stack[-1] > the current asteroid.\n ; // Destroy the current asteroid, so do nothing.\n }\n\n return stack.stream().mapToInt(Integer::intValue).toArray();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector asteroidCollision(vector& asteroids) {\n vector stack;\n\n for (const int a : asteroids)\n if (a > 0) {\n stack.push_back(a);\n } else { // a < 0\n // Destroy the previous positive one(s).\n while (!stack.empty() && stack.back() > 0 && stack.back() < -a)\n stack.pop_back();\n if (stack.empty() || stack.back() < 0)\n stack.push_back(a);\n else if (stack.back() == -a)\n stack.pop_back(); // Both asteroids explode.\n else // stack[-1] > the current asteroid.\n ; // Destroy the current asteroid, so do nothing.\n }\n\n return stack;\n }\n};\n"} +{"task_num": 743, "task_title": "Network Delay Time", "difficulty": 2, "func_name": "networkDelayTime", "description": "You are given a network of `n` nodes, labeled from `1` to `n`. You are also\ngiven `times`, a list of travel times as directed edges `times[i] = (ui, vi,\nwi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the\ntime it takes for a signal to travel from source to target.\n\nWe will send a signal from a given node `k`. Return the minimum time it takes\nfor all the `n` nodes to receive the signal. If it is impossible for all the\n`n` nodes to receive the signal, return `-1`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n graph = [[] for _ in range(n)]\n\n for u, v, w in times:\n graph[u - 1].append((v - 1, w))\n\n return self._dijkstra(graph, k - 1)\n\n def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int) -> int:\n dist = [math.inf] * len(graph)\n\n dist[src] = 0\n minHeap = [(dist[src], src)]\n\n while minHeap:\n d, u = heapq.heappop(minHeap)\n if d > dist[u]:\n continue\n for v, w in graph[u]:\n if d + w < dist[v]:\n dist[v] = d + w\n heapq.heappush(minHeap, (dist[v], v))\n\n maxDist = max(dist)\n return maxDist if maxDist != math.inf else -1\n", "java_solution": "class Solution {\n public int networkDelayTime(int[][] times, int n, int k) {\n List>[] graph = new List[n];\n\n for (int i = 0; i < n; i++)\n graph[i] = new ArrayList<>();\n\n for (int[] time : times) {\n final int u = time[0] - 1;\n final int v = time[1] - 1;\n final int w = time[2];\n graph[u].add(new Pair<>(v, w));\n }\n\n return dijkstra(graph, k - 1);\n }\n\n private int dijkstra(List>[] graph, int src) {\n int[] dist = new int[graph.length];\n Arrays.fill(dist, Integer.MAX_VALUE);\n\n dist[src] = 0;\n Queue> minHeap =\n new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) {\n { offer(new Pair<>(dist[src], src)); } // (d, u)\n };\n\n while (!minHeap.isEmpty()) {\n final int d = minHeap.peek().getKey();\n final int u = minHeap.poll().getValue();\n if (d > dist[u])\n continue;\n for (Pair pair : graph[u]) {\n final int v = pair.getKey();\n final int w = pair.getValue();\n if (d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.offer(new Pair<>(dist[v], v));\n }\n }\n }\n\n final int maxDist = Arrays.stream(dist).max().getAsInt();\n return maxDist == Integer.MAX_VALUE ? -1 : maxDist;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int networkDelayTime(vector>& times, int n, int k) {\n vector>> graph(n);\n\n for (const vector& time : times) {\n const int u = time[0] - 1;\n const int v = time[1] - 1;\n const int w = time[2];\n graph[u].emplace_back(v, w);\n }\n\n return dijkstra(graph, k - 1);\n }\n\n private:\n int dijkstra(const vector>>& graph, int src) {\n vector dist(graph.size(), INT_MAX);\n\n dist[src] = 0;\n using P = pair; // (d, u)\n priority_queue, greater<>> minHeap;\n minHeap.emplace(dist[src], src);\n\n while (!minHeap.empty()) {\n const auto [d, u] = minHeap.top();\n minHeap.pop();\n if (d > dist[u])\n continue;\n for (const auto& [v, w] : graph[u])\n if (d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.emplace(dist[v], v);\n }\n }\n\n const int maxDist = ranges::max(dist);\n return maxDist == INT_MAX ? -1 : maxDist;\n }\n};\n"} +{"task_num": 770, "task_title": "Basic Calculator IV", "difficulty": 3, "func_name": "basicCalculatorIV", "description": "Given an expression such as `expression = \"e + 8 - a + 5\"` and an evaluation\nmap such as `{\"e\": 1}` (given in terms of `evalvars = [\"e\"]` and `evalints =\n[1]`), return a list of tokens representing the simplified expression, such as\n`[\"-1*a\",\"14\"]`\n\n* An expression alternates chunks and symbols, with a space separating each chunk and symbol.\n* A chunk is either an expression in parentheses, a variable, or a non-negative integer.\n* A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like `\"2x\"` or `\"-x\"`.\n\nExpressions are evaluated in the usual order: brackets first, then\nmultiplication, then addition and subtraction.\n\n* For example, `expression = \"1 + 2 * 3\"` has an answer of `[\"7\"]`.\n\nThe format of the output is as follows:\n\n* For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically. \n* For example, we would never write a term like `\"b*a*c\"`, only `\"a*b*c\"`.\n* Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term. \n* For example, `\"a*a*b*c\"` has degree `4`.\n* The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed.\n* An example of a well-formatted answer is `[\"-2*a*a*a\", \"3*a*a*b\", \"3*b*b\", \"4*a\", \"5*c\", \"-6\"]`.\n* Terms (including constant terms) with coefficient `0` are not included. \n* For example, an expression of `\"0\"` has an output of `[]`.\n\nNote: You may assume that the given expression is always valid. All\nintermediate results will be in the range of `[-231, 231 - 1]`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Poly:\n def __init__(self, term: str = None, coef: int = None):\n if term and coef:\n self.terms = collections.Counter({term: coef})\n else:\n self.terms = collections.Counter()\n\n def __add__(self, other):\n for term, coef in other.terms.items():\n self.terms[term] += coef\n return self\n\n def __sub__(self, other):\n for term, coef in other.terms.items():\n self.terms[term] -= coef\n return self\n\n def __mul__(self, other):\n res = Poly()\n for a, aCoef in self.terms.items():\n for b, bCoef in other.terms.items():\n res.terms[self._merge(a, b)] += aCoef * bCoef\n return res\n\n def toList(self) -> List[str]:\n for term in list(self.terms.keys()):\n if not self.terms[term]:\n del self.terms[term]\n\n def cmp(term: str) -> tuple:\n if term == '1':\n return (0,)\n var = term.split('*')\n return (-len(var), term)\n\n def concat(term: str) -> str:\n if term == '1':\n return str(self.terms[term])\n return str(self.terms[term]) + '*' + term\n\n terms = list(self.terms.keys())\n terms.sort(key=cmp)\n return [concat(term) for term in terms]\n\n def _merge(self, a: str, b: str) -> str:\n if a == '1':\n return b\n if b == '1':\n return a\n res = []\n A = a.split('*')\n B = b.split('*')\n i = 0\n j = 0\n while i < len(A) and j < len(B):\n if A[i] < B[j]:\n res.append(A[i])\n i += 1\n else:\n res.append(B[j])\n j += 1\n return '*'.join(res + A[i:] + B[j:])\n\n\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n tokens = list(self._getTokens(expression))\n evalMap = {a: b for a, b in zip(evalvars, evalints)}\n\n for i, token in enumerate(tokens):\n if token in evalMap:\n tokens[i] = str(evalMap[token])\n\n postfix = self._infixToPostfix(tokens)\n return self._evaluate(postfix).toList()\n\n def _getTokens(self, s: str) -> Iterator[str]:\n i = 0\n for j, c in enumerate(s):\n if c == ' ':\n if i < j:\n yield s[i:j]\n i = j + 1\n elif c in '()+-*':\n if i < j:\n yield s[i:j]\n yield c\n i = j + 1\n if i < len(s):\n yield s[i:]\n\n def _infixToPostfix(self, tokens: List[str]) -> List[str]:\n postfix = []\n ops = []\n\n def precedes(prevOp: str, currOp: str) -> bool:\n if prevOp == '(':\n return False\n return prevOp == '*' or currOp in '+-'\n\n for token in tokens:\n if token == '(':\n ops.append(token)\n elif token == ')':\n while ops[-1] != '(':\n postfix.append(ops.pop())\n ops.pop()\n elif token in '+-*':\n while ops and precedes(ops[-1], token):\n postfix.append(ops.pop())\n ops.append(token)\n else:\n postfix.append(token)\n return postfix + ops[::-1]\n\n def _evaluate(self, postfix: List[str]) -> Poly:\n polys: List[Poly] = []\n for token in postfix:\n if token in '+-*':\n b = polys.pop()\n a = polys.pop()\n if token == '+':\n polys.append(a + b)\n elif token == '-':\n polys.append(a - b)\n else:\n polys.append(a * b)\n elif token.lstrip('-').isnumeric():\n polys.append(Poly(\"1\", int(token)))\n else:\n polys.append(Poly(token, 1))\n return polys[0]\n", "java_solution": "class Poly {\n public Poly add(Poly o) {\n for (final String term : o.terms.keySet())\n terms.merge(term, o.terms.get(term), Integer::sum);\n return this;\n }\n\n public Poly minus(Poly o) {\n for (final String term : o.terms.keySet())\n terms.merge(term, -o.terms.get(term), Integer::sum);\n return this;\n }\n\n public Poly mult(Poly o) {\n Poly res = new Poly();\n for (final String a : terms.keySet())\n for (final String b : o.terms.keySet())\n res.terms.merge(merge(a, b), terms.get(a) * o.terms.get(b), Integer::sum);\n return res;\n }\n\n // @Override\n // Public String toString() {\n // StringBuilder sb = new StringBuilder();\n // sb.append(\"{\");\n // for (final String term : terms.keySet())\n // sb.append(term).append(\": \").append(terms.get(term)).append(\", \");\n // sb.append(\"}\");\n // return sb.toString();\n // }\n\n public List toList() {\n List res = new ArrayList<>();\n List keys = new ArrayList<>(terms.keySet());\n Collections.sort(keys, new Comparator() {\n @Override\n public int compare(final String a, final String b) {\n // the minimum degree is the last\n if (a.equals(\"1\"))\n return 1;\n if (b.equals(\"1\"))\n return -1;\n String[] as = a.split(\"\\\\*\");\n String[] bs = b.split(\"\\\\*\");\n // the maximum degree is the first\n // Break ties by their lexicographic orders.\n return as.length == bs.length ? a.compareTo(b) : bs.length - as.length;\n }\n });\n for (final String key : keys)\n if (terms.get(key) != 0)\n res.add(concat(key));\n return res;\n }\n\n public Poly() {}\n public Poly(final String term, int coef) {\n terms.put(term, coef);\n }\n\n private Map terms = new HashMap<>();\n\n // e.g. merge(\"a*b\", \"a*c\") -> \"a*a*b*c\"\n private static String merge(final String a, final String b) {\n if (a.equals(\"1\"))\n return b;\n if (b.equals(\"1\"))\n return a;\n StringBuilder sb = new StringBuilder();\n String[] A = a.split(\"\\\\*\");\n String[] B = b.split(\"\\\\*\");\n int i = 0; // A's index\n int j = 0; // B's index\n while (i < A.length && j < B.length)\n if (A[i].compareTo(B[j]) < 0)\n sb.append(\"*\").append(A[i++]);\n else\n sb.append(\"*\").append(B[j++]);\n while (i < A.length)\n sb.append(\"*\").append(A[i++]);\n while (j < B.length)\n sb.append(\"*\").append(B[j++]);\n return sb.substring(1).toString();\n }\n\n private String concat(final String term) {\n if (term.equals(\"1\"))\n return String.valueOf(terms.get(term));\n return new StringBuilder().append(terms.get(term)).append('*').append(term).toString();\n }\n}\n\nclass Solution {\n public List basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {\n List tokens = getTokens(expression);\n Map evalMap = new HashMap<>();\n\n for (int i = 0; i < evalvars.length; ++i)\n evalMap.put(evalvars[i], evalints[i]);\n\n for (int i = 0; i < tokens.size(); ++i)\n if (evalMap.containsKey(tokens.get(i)))\n tokens.set(i, String.valueOf(evalMap.get(tokens.get(i))));\n\n List postfix = infixToPostfix(tokens);\n return evaluate(postfix).toList();\n }\n\n private List getTokens(final String s) {\n List tokens = new ArrayList<>();\n int i = 0;\n for (int j = 0; j < s.length(); ++j)\n if (s.charAt(j) == ' ') {\n if (i < j)\n tokens.add(s.substring(i, j));\n i = j + 1;\n } else if (\"()+-*\".contains(s.substring(j, j + 1))) {\n if (i < j)\n tokens.add(s.substring(i, j));\n tokens.add(s.substring(j, j + 1));\n i = j + 1;\n }\n if (i < s.length())\n tokens.add(s.substring(i));\n return tokens;\n }\n\n private boolean isOperator(final String token) {\n return token.equals(\"+\") || token.equals(\"-\") || token.equals(\"*\");\n }\n\n private boolean precedes(final String prevOp, final String currOp) {\n if (prevOp.equals(\"(\"))\n return false;\n return prevOp.equals(\"*\") || currOp.equals(\"+\") || currOp.equals(\"-\");\n }\n\n private List infixToPostfix(List tokens) {\n List postfix = new ArrayList<>();\n Deque ops = new ArrayDeque<>();\n\n for (final String token : tokens)\n if (token.equals(\"(\")) {\n ops.push(token);\n } else if (token.equals(\")\")) {\n while (!ops.peek().equals(\"(\"))\n postfix.add(ops.pop());\n ops.pop();\n } else if (isOperator(token)) {\n while (!ops.isEmpty() && precedes(ops.peek(), token))\n postfix.add(ops.pop());\n ops.push(token);\n } else { // isOperand(token)\n postfix.add(token);\n }\n\n while (!ops.isEmpty())\n postfix.add(ops.pop());\n\n return postfix;\n }\n\n private Poly evaluate(List postfix) {\n LinkedList polys = new LinkedList<>();\n for (final String token : postfix)\n if (isOperator(token)) {\n final Poly b = polys.removeLast();\n final Poly a = polys.removeLast();\n if (token.equals(\"+\"))\n polys.add(a.add(b));\n else if (token.equals(\"-\"))\n polys.add(a.minus(b));\n else // token == \"*\"\n polys.add(a.mult(b));\n } else if (token.charAt(0) == '-' || token.chars().allMatch(c -> Character.isDigit(c))) {\n polys.add(new Poly(\"1\", Integer.parseInt(token)));\n } else {\n polys.add(new Poly(token, 1));\n }\n return polys.getFirst();\n }\n}\n", "cpp_solution": "class Poly {\n friend Poly operator+(const Poly& lhs, const Poly& rhs) {\n Poly res(lhs);\n for (const auto& [term, coef] : rhs.terms)\n res.terms[term] += coef;\n return res;\n }\n\n friend Poly operator-(const Poly& lhs, const Poly& rhs) {\n Poly res(lhs);\n for (const auto& [term, coef] : rhs.terms)\n res.terms[term] -= coef;\n return res;\n }\n\n friend Poly operator*(const Poly& lhs, const Poly& rhs) {\n Poly res;\n for (const auto& [a, aCoef] : lhs.terms)\n for (const auto& [b, bCoef] : rhs.terms)\n res.terms[merge(a, b)] += aCoef * bCoef;\n return res;\n }\n\n // Friend ostream& operator<<(ostream& os, const Poly& poly) {\n // os << \"{\";\n // for (const auto& [term, coef] : poly.terms)\n // os << term << \": \" << coef << \", \";\n // os << \"}\";\n // return os;\n // }\n\n public:\n vector toList() {\n vector res;\n vector keys;\n for (const auto& [term, _] : terms)\n keys.push_back(term);\n ranges::sort(keys, [&](const string& a, const string& b) {\n // the minimum degree is the last\n if (a == \"1\")\n return false;\n if (b == \"1\")\n return true;\n const vector as = split(a, '*');\n const vector bs = split(b, '*');\n // the maximum degree is the first\n // Break ties by their lexicographic orders.\n return as.size() == bs.size() ? a < b : as.size() > bs.size();\n });\n auto concat = [&](const string& term) -> string {\n if (term == \"1\")\n return to_string(terms[term]);\n return to_string(terms[term]) + '*' + term;\n };\n for (const string& key : keys)\n if (terms[key])\n res.push_back(concat(key));\n return res;\n }\n\n Poly() = default;\n Poly(const string& term, int coef) {\n terms[term] = coef;\n }\n\n private:\n unordered_map terms;\n\n // e.g. merge(\"a*b\", \"a*c\") -> \"a*a*b*c\"\n static string merge(const string& a, const string& b) {\n if (a == \"1\")\n return b;\n if (b == \"1\")\n return a;\n string res;\n vector A = split(a, '*');\n vector B = split(b, '*');\n int i = 0; // A's index\n int j = 0; // B's index\n while (i < A.size() && j < B.size())\n if (A[i] < B[j])\n res += '*' + A[i++];\n else\n res += '*' + B[j++];\n while (i < A.size())\n res += '*' + A[i++];\n while (j < B.size())\n res += '*' + B[j++];\n return res.substr(1);\n }\n\n static vector split(const string& token, char c) {\n vector vars;\n istringstream iss(token);\n for (string var; getline(iss, var, c);)\n vars.push_back(var);\n return vars;\n }\n};\n\nclass Solution {\n public:\n vector basicCalculatorIV(string expression, vector& evalvars,\n vector& evalints) {\n vector tokens = getTokens(expression);\n unordered_map evalMap;\n\n for (int i = 0; i < evalvars.size(); ++i)\n evalMap[evalvars[i]] = evalints[i];\n\n for (string& token : tokens)\n if (const auto it = evalMap.find(token); it != evalMap.cend())\n token = to_string(it->second);\n\n const vector& postfix = infixToPostfix(tokens);\n return evaluate(postfix).toList();\n }\n\n private:\n vector getTokens(const string& s) {\n vector tokens;\n int i = 0;\n for (int j = 0; j < s.length(); ++j)\n if (s[j] == ' ') {\n if (i < j)\n tokens.push_back(s.substr(i, j - i));\n i = j + 1;\n } else if (string(\"()+-*\").find(s[j]) != string::npos) {\n if (i < j)\n tokens.push_back(s.substr(i, j - i));\n tokens.push_back(s.substr(j, 1));\n i = j + 1;\n }\n if (i < s.length())\n tokens.push_back(s.substr(i));\n return tokens;\n }\n\n bool isOperator(const string& token) {\n return token == \"+\" || token == \"-\" || token == \"*\";\n }\n\n vector infixToPostfix(const vector& tokens) {\n vector postfix;\n stack ops;\n\n auto precedes = [](const string& prevOp, const string& currOp) -> bool {\n if (prevOp == \"(\")\n return false;\n return prevOp == \"*\" || currOp == \"+\" || currOp == \"-\";\n };\n\n for (const string& token : tokens)\n if (token == \"(\") {\n ops.push(token);\n } else if (token == \")\") {\n while (ops.top() != \"(\")\n postfix.push_back(ops.top()), ops.pop();\n ops.pop();\n } else if (isOperator(token)) {\n while (!ops.empty() && precedes(ops.top(), token))\n postfix.push_back(ops.top()), ops.pop();\n ops.push(token);\n } else { // isOperand(token)\n postfix.push_back(token);\n }\n\n while (!ops.empty())\n postfix.push_back(ops.top()), ops.pop();\n\n return postfix;\n }\n\n Poly evaluate(const vector& postfix) {\n vector polys;\n for (const string& token : postfix)\n if (isOperator(token)) {\n const Poly b = polys.back();\n polys.pop_back();\n const Poly a = polys.back();\n polys.pop_back();\n if (token == \"+\")\n polys.push_back(a + b);\n else if (token == \"-\")\n polys.push_back(a - b);\n else // token == \"*\"\n polys.push_back(a * b);\n } else if (token[0] == '-' ||\n ranges::all_of(token, [](char c) { return isdigit(c); })) {\n polys.push_back(Poly(\"1\", stoi(token)));\n } else {\n polys.push_back(Poly(token, 1));\n }\n return polys[0];\n }\n};\n"} +{"task_num": 777, "task_title": "Swap Adjacent in LR String", "difficulty": 2, "func_name": "canTransform", "description": "In a string composed of `'L'`, `'R'`, and `'X'` characters, like\n`\"RXXLRXRXL\"`, a move consists of either replacing one occurrence of `\"XL\"`\nwith `\"LX\"`, or replacing one occurrence of `\"RX\"` with `\"XR\"`. Given the\nstarting string `start` and the ending string `end`, return `True` if and only\nif there exists a sequence of moves to transform one string to the other.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n if start.replace('X', '') != end.replace('X', ''):\n return False\n\n i = 0\n j = 0\n\n while i < len(start) and j < len(end):\n while i < len(start) and start[i] == 'X':\n i += 1\n while j < len(end) and end[j] == 'X':\n j += 1\n if i == len(start) and j == len(end):\n return True\n if i == len(start) or j == len(end):\n return False\n if start[i] == 'L' and i < j:\n return False\n if start[i] == 'R' and i > j:\n return False\n i += 1\n j += 1\n\n return True\n", "java_solution": "class Solution {\n public boolean canTransform(String start, String end) {\n if (!start.replace(\"X\", \"\").equals(end.replace(\"X\", \"\")))\n return false;\n\n int i = 0; // start's index\n int j = 0; // end's index\n\n while (i < start.length() && j < end.length()) {\n while (i < start.length() && start.charAt(i) == 'X')\n ++i;\n while (j < end.length() && end.charAt(j) == 'X')\n ++j;\n if (i == start.length() && j == end.length())\n return true;\n if (i == start.length() || j == end.length())\n return false;\n // L can only move to left.\n if (start.charAt(i) == 'L' && i < j)\n return false;\n // R can only move to right.\n if (start.charAt(i) == 'R' && i > j)\n return false;\n ++i;\n ++j;\n }\n\n return true;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool canTransform(string start, string end) {\n if (removeX(start) != removeX(end))\n return false;\n\n int i = 0; // start's index\n int j = 0; // end's index\n\n while (i < start.length() && j < end.length()) {\n while (i < start.length() && start[i] == 'X')\n ++i;\n while (j < end.length() && end[j] == 'X')\n ++j;\n if (i == start.length() && j == end.length())\n return true;\n if (i == start.length() || j == end.length())\n return false;\n // L can only move to left.\n if (start[i] == 'L' && i < j)\n return false;\n // R can only move to right.\n if (start[i] == 'R' && i > j)\n return false;\n ++i;\n ++j;\n }\n\n return true;\n }\n\n private:\n string removeX(const string& s) {\n string t = s;\n std::erase(t, 'X');\n return t;\n }\n};\n"} +{"task_num": 782, "task_title": "Transform to Chessboard", "difficulty": 3, "func_name": "movesToChessboard", "description": "You are given an `n x n` binary grid `board`. In each move, you can swap any\ntwo rows with each other, or any two columns with each other.\n\nReturn the minimum number of moves to transform the board into a chessboard\nboard. If the task is impossible, return `-1`.\n\nA chessboard board is a board where no `0`'s and no `1`'s are 4-directionally\nadjacent.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n\n for i in range(n):\n for j in range(n):\n if board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]:\n return -1\n\n rowSum = sum(board[0])\n colSum = sum(board[i][0] for i in range(n))\n\n if rowSum != n // 2 and rowSum != (n + 1) // 2:\n return -1\n if colSum != n // 2 and colSum != (n + 1) // 2:\n return -1\n\n rowSwaps = sum(board[i][0] == (i & 1) for i in range(n))\n colSwaps = sum(board[0][i] == (i & 1) for i in range(n))\n\n if n & 1:\n if rowSwaps & 1:\n rowSwaps = n - rowSwaps\n if colSwaps & 1:\n colSwaps = n - colSwaps\n else:\n rowSwaps = min(rowSwaps, n - rowSwaps)\n colSwaps = min(colSwaps, n - colSwaps)\n\n return (rowSwaps + colSwaps) // 2\n", "java_solution": "class Solution {\n public int movesToChessboard(int[][] board) {\n final int n = board.length;\n int rowSum = 0;\n int colSum = 0;\n int rowSwaps = 0;\n int colSwaps = 0;\n\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n if ((board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]) == 1)\n return -1;\n\n for (int i = 0; i < n; ++i) {\n rowSum += board[0][i];\n colSum += board[i][0];\n }\n\n if (rowSum != n / 2 && rowSum != (n + 1) / 2)\n return -1;\n if (colSum != n / 2 && colSum != (n + 1) / 2)\n return -1;\n\n for (int i = 0; i < n; ++i) {\n if (board[i][0] == (i & 1))\n ++rowSwaps;\n if (board[0][i] == (i & 1))\n ++colSwaps;\n }\n\n if (n % 2 == 1) {\n if (rowSwaps % 2 == 1)\n rowSwaps = n - rowSwaps;\n if (colSwaps % 2 == 1)\n colSwaps = n - colSwaps;\n } else {\n rowSwaps = Math.min(rowSwaps, n - rowSwaps);\n colSwaps = Math.min(colSwaps, n - colSwaps);\n }\n\n return (rowSwaps + colSwaps) / 2;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int movesToChessboard(vector>& board) {\n const int n = board.size();\n int rowSum = 0;\n int colSum = 0;\n int rowSwaps = 0;\n int colSwaps = 0;\n\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n if (board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j] == 1)\n return -1;\n\n for (int i = 0; i < n; ++i) {\n rowSum += board[0][i];\n colSum += board[i][0];\n }\n\n if (rowSum != n / 2 && rowSum != (n + 1) / 2)\n return -1;\n if (colSum != n / 2 && colSum != (n + 1) / 2)\n return -1;\n\n for (int i = 0; i < n; ++i) {\n rowSwaps += board[i][0] == (i & 1);\n colSwaps += board[0][i] == (i & 1);\n }\n\n if (n % 2 == 1) {\n if (rowSwaps % 2 == 1)\n rowSwaps = n - rowSwaps;\n if (colSwaps % 2 == 1)\n colSwaps = n - colSwaps;\n } else {\n rowSwaps = min(rowSwaps, n - rowSwaps);\n colSwaps = min(colSwaps, n - colSwaps);\n }\n\n return (rowSwaps + colSwaps) / 2;\n }\n};\n"} +{"task_num": 786, "task_title": "K-th Smallest Prime Fraction", "difficulty": 2, "func_name": "kthSmallestPrimeFraction", "description": "You are given a sorted integer array `arr` containing `1` and prime numbers,\nwhere all the integers of `arr` are unique. You are also given an integer `k`.\n\nFor every `i` and `j` where `0 <= i < j < arr.length`, we consider the\nfraction `arr[i] / arr[j]`.\n\nReturn the `kth` smallest fraction considered. Return your answer as an array\nof integers of size `2`, where `answer[0] == arr[i]` and `answer[1] ==\narr[j]`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]:\n n = len(arr)\n ans = [0, 1]\n l = 0\n r = 1\n\n while True:\n m = (l + r) / 2\n ans[0] = 0\n count = 0\n j = 1\n\n for i in range(n):\n while j < n and arr[i] > m * arr[j]:\n j += 1\n count += n - j\n if j == n:\n break\n if ans[0] * arr[j] < ans[1] * arr[i]:\n ans[0] = arr[i]\n ans[1] = arr[j]\n\n if count < k:\n l = m\n elif count > k:\n r = m\n else:\n return ans\n", "java_solution": "class Solution {\n public int[] kthSmallestPrimeFraction(int[] arr, int k) {\n final int n = arr.length;\n double l = 0.0;\n double r = 1.0;\n\n while (l < r) {\n final double m = (l + r) / 2.0;\n int fractionsNoGreaterThanM = 0;\n int p = 0;\n int q = 1;\n\n // For each index i, find the first index j s.t. arr[i] / arr[j] <= m,\n // so fractionsNoGreaterThanM for index i will be n - j.\n for (int i = 0, j = 1; i < n; ++i) {\n while (j < n && arr[i] > m * arr[j])\n ++j;\n if (j == n)\n break;\n fractionsNoGreaterThanM += n - j;\n if (p * arr[j] < q * arr[i]) {\n p = arr[i];\n q = arr[j];\n }\n }\n\n if (fractionsNoGreaterThanM == k)\n return new int[] {p, q};\n if (fractionsNoGreaterThanM > k)\n r = m;\n else\n l = m;\n }\n\n throw new IllegalArgumentException();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector kthSmallestPrimeFraction(vector& arr, int k) {\n const int n = arr.size();\n double l = 0.0;\n double r = 1.0;\n\n while (l < r) {\n const double m = (l + r) / 2.0;\n int fractionsNoGreaterThanM = 0;\n int p = 0;\n int q = 1;\n\n // For each index i, find the first index j s.t. arr[i] / arr[j] <= m,\n // so fractionsNoGreaterThanM for index i will be n - j.\n for (int i = 0, j = 1; i < n; ++i) {\n while (j < n && arr[i] > m * arr[j])\n ++j;\n if (j == n)\n break;\n fractionsNoGreaterThanM += n - j;\n if (p * arr[j] < q * arr[i]) {\n p = arr[i];\n q = arr[j];\n }\n }\n\n if (fractionsNoGreaterThanM == k)\n return {p, q};\n if (fractionsNoGreaterThanM > k)\n r = m;\n else\n l = m;\n }\n\n throw;\n }\n};\n"} +{"task_num": 787, "task_title": "Cheapest Flights Within K Stops", "difficulty": 2, "func_name": "findCheapestPrice", "description": "There are `n` cities connected by some number of flights. You are given an\narray `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there\nis a flight from city `fromi` to city `toi` with cost `pricei`.\n\nYou are also given three integers `src`, `dst`, and `k`, return the cheapest\nprice from `src` to `dst` with at most `k` stops. If there is no such route,\nreturn `-1`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:\n graph = [[] for _ in range(n)]\n\n for u, v, w in flights:\n graph[u].append((v, w))\n\n return self._dijkstra(graph, src, dst, k)\n\n def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, dst: int, k: int) -> int:\n dist=[]\n for i in range(len(graph)):\n dist.append([math.inf for _ in range(k + 2)])\n\n dist[src][k + 1] = 0\n minHeap = [(dist[src][k + 1], src, k + 1)]\n\n while minHeap:\n d, u, stops = heapq.heappop(minHeap)\n if u == dst:\n return d\n if stops == 0 or d > dist[u][stops]:\n continue\n for v, w in graph[u]:\n if d + w < dist[v][stops - 1]:\n dist[v][stops - 1] = d + w\n heapq.heappush(minHeap, (dist[v][stops - 1], v, stops - 1))\n\n return -1\n", "java_solution": "class Solution {\n public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {\n List>[] graph = new List[n];\n\n for (int i = 0; i < n; i++)\n graph[i] = new ArrayList<>();\n\n for (int[] flight : flights) {\n final int u = flight[0];\n final int v = flight[1];\n final int w = flight[2];\n graph[u].add(new Pair<>(v, w));\n }\n\n return dijkstra(graph, src, dst, k);\n }\n\n private int dijkstra(List>[] graph, int src, int dst, int k) {\n int[][] dist = new int[graph.length][k + 2];\n Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));\n\n dist[src][k + 1] = 0;\n Queue minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) {\n { offer(new int[] {dist[src][k + 1], src, k + 1}); } // (d, u, stops)\n };\n\n while (!minHeap.isEmpty()) {\n final int d = minHeap.peek()[0];\n final int u = minHeap.peek()[1];\n final int stops = minHeap.poll()[2];\n if (u == dst)\n return d;\n if (stops == 0 || d > dist[u][stops])\n continue;\n for (Pair pair : graph[u]) {\n final int v = pair.getKey();\n final int w = pair.getValue();\n if (d + w < dist[v][stops - 1]) {\n dist[v][stops - 1] = d + w;\n minHeap.offer(new int[] {dist[v][stops - 1], v, stops - 1});\n }\n }\n }\n\n return -1;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int findCheapestPrice(int n, vector>& flights, int src, int dst,\n int k) {\n vector>> graph(n);\n\n for (const vector& flight : flights) {\n const int u = flight[0];\n const int v = flight[1];\n const int w = flight[2];\n graph[u].emplace_back(v, w);\n }\n\n return dijkstra(graph, src, dst, k);\n }\n\n private:\n int dijkstra(const vector>>& graph, int src, int dst,\n int k) {\n vector> dist(graph.size(), vector(k + 2, INT_MAX));\n\n dist[src][k + 1] = 0;\n using T = tuple; // (d, u, stops)\n priority_queue, greater<>> minHeap;\n minHeap.emplace(dist[src][k + 1], src, k + 1);\n\n while (!minHeap.empty()) {\n const auto [d, u, stops] = minHeap.top();\n minHeap.pop();\n if (u == dst)\n return d;\n if (stops == 0 || d > dist[u][stops])\n continue;\n for (const auto& [v, w] : graph[u])\n if (d + w < dist[v][stops - 1]) {\n dist[v][stops - 1] = d + w;\n minHeap.emplace(dist[v][stops - 1], v, stops - 1);\n }\n }\n\n return -1;\n }\n};\n"} +{"task_num": 794, "task_title": "Valid Tic-Tac-Toe State", "difficulty": 2, "func_name": "validTicTacToe", "description": "Given a Tic-Tac-Toe board as a string array `board`, return `true` if and only\nif it is possible to reach this board position during the course of a valid\ntic-tac-toe game.\n\nThe board is a `3 x 3` array that consists of characters `' '`, `'X'`, and\n`'O'`. The `' '` character represents an empty square.\n\nHere are the rules of Tic-Tac-Toe:\n\n* Players take turns placing characters into empty squares `' '`.\n* The first player always places `'X'` characters, while the second player always places `'O'` characters.\n* `'X'` and `'O'` characters are always placed into empty squares, never filled ones.\n* The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.\n* The game also ends if all squares are non-empty.\n* No more moves can be played if the game is over.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def validTicTacToe(self, board: List[str]) -> bool:\n def isWin(c: str) -> bool:\n return any(row.count(c) == 3 for row in board) or any(row.count(c) == 3 for row in list(zip(*board))) or all(board[i][i] == c for i in range(3)) or all(board[i][2 - i] == c for i in range(3))\n\n countX = sum(row.count('X') for row in board)\n countO = sum(row.count('O') for row in board)\n\n if countX < countO or countX - countO > 1:\n return False\n if isWin('X') and countX == countO or isWin('O') and countX != countO:\n return False\n\n return True\n", "java_solution": "class Solution {\n public boolean validTicTacToe(String[] board) {\n final int countX = sum(board, 'X');\n final int countO = sum(board, 'O');\n\n if (countX < countO || countX - countO > 1)\n return false;\n if (isWinned(board, 'X') && countX == countO || //\n isWinned(board, 'O') && countX != countO)\n return false;\n\n return true;\n }\n\n private int sum(final String[] board, char c) {\n int ans = 0;\n\n for (final String row : board)\n ans += row.chars().filter(i -> i == c).count();\n\n return ans;\n }\n\n private boolean isWinned(final String[] board, char c) {\n String[] rotated = rotate(board);\n\n return Arrays.stream(board).anyMatch(row -> row.chars().filter(i -> i == c).count() == 3) ||\n Arrays.stream(rotated).anyMatch(row -> row.chars().filter(i -> i == c).count() == 3) ||\n board[0].charAt(0) == c && board[1].charAt(1) == c && board[2].charAt(2) == c ||\n board[0].charAt(2) == c && board[1].charAt(1) == c && board[2].charAt(0) == c;\n }\n\n private String[] rotate(final String[] board) {\n String[] rotated = new String[3];\n\n for (final String row : board)\n for (int i = 0; i < 3; ++i)\n rotated[i] += row.charAt(i);\n\n return rotated;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool validTicTacToe(vector& board) {\n const int countX = sum(board, 'X');\n const int countO = sum(board, 'O');\n\n if (countX < countO || countX - countO > 1)\n return false;\n if (isWinned(board, 'X') && countX == countO ||\n isWinned(board, 'O') && countX != countO)\n return false;\n\n return true;\n }\n\n private:\n int sum(const vector& board, char c) {\n int ans = 0;\n\n for (const string& row : board)\n ans += ranges::count(row, c);\n\n return ans;\n }\n\n bool isWinned(const vector& board, char c) {\n vector rotated = rotate(board);\n\n auto equalsToThree = [&c](const string& row) {\n return ranges::count(row, c) == 3;\n };\n\n return ranges::any_of(board, equalsToThree) ||\n ranges::any_of(rotated, equalsToThree) ||\n board[0][0] == c && board[1][1] == c && board[2][2] == c ||\n board[0][2] == c && board[1][1] == c && board[2][0] == c;\n }\n\n vector rotate(const vector& board) {\n vector rotated(3);\n\n for (const string& row : board)\n for (int i = 0; i < 3; ++i)\n rotated[i].push_back(row[i]);\n\n return rotated;\n }\n};\n"} +{"task_num": 805, "task_title": "Split Array With Same Average", "difficulty": 3, "func_name": "splitArraySameAverage", "description": "You are given an integer array `nums`.\n\nYou should move each element of `nums` into one of the two arrays `A` and `B`\nsuch that `A` and `B` are non-empty, and `average(A) == average(B)`.\n\nReturn `true` if it is possible to achieve that and `false` otherwise.\n\nNote that for an array `arr`, `average(arr)` is the sum of all the elements of\n`arr` over the length of `arr`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def splitArraySameAverage(self, nums: List[int]) -> bool:\n n = len(nums)\n summ = sum(nums)\n if not any(i * summ % n == 0 for i in range(1, n // 2 + 1)):\n return False\n\n sums = [set() for _ in range(n // 2 + 1)]\n sums[0].add(0)\n\n for num in nums:\n for i in range(n // 2, 0, -1):\n for val in sums[i - 1]:\n sums[i].add(num + val)\n\n for i in range(1, n // 2 + 1):\n if i * summ % n == 0 and i * summ // n in sums[i]:\n return True\n\n return False\n", "java_solution": "class Solution {\n public boolean splitArraySameAverage(int[] nums) {\n final int n = nums.length;\n final int sum = Arrays.stream(nums).sum();\n if (!isPossible(sum, n))\n return false;\n\n List> sums = new ArrayList<>();\n\n for (int i = 0; i < n / 2 + 1; ++i)\n sums.add(new HashSet<>());\n sums.get(0).add(0);\n\n for (final int num : nums)\n for (int i = n / 2; i > 0; --i)\n for (final int val : sums.get(i - 1))\n sums.get(i).add(num + val);\n\n for (int i = 1; i < n / 2 + 1; ++i)\n if (i * sum % n == 0 && sums.get(i).contains(i * sum / n))\n return true;\n\n return false;\n }\n\n private boolean isPossible(int sum, int n) {\n for (int i = 1; i < n / 2 + 1; ++i)\n if (i * sum % n == 0)\n return true;\n return false;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool splitArraySameAverage(vector& nums) {\n const int n = nums.size();\n const int sum = accumulate(nums.begin(), nums.end(), 0);\n if (!isPossible(sum, n))\n return false;\n\n vector> sums(n / 2 + 1);\n sums[0].insert(0);\n\n for (const int num : nums)\n for (int i = n / 2; i > 0; --i)\n for (const int val : sums[i - 1])\n sums[i].insert(num + val);\n\n for (int i = 1; i < n / 2 + 1; ++i)\n if (i * sum % n == 0 && sums[i].contains(i * sum / n))\n return true;\n\n return false;\n }\n\n private:\n bool isPossible(int sum, int n) {\n for (int i = 1; i < n / 2 + 1; ++i)\n if (i * sum % n == 0)\n return true;\n return false;\n }\n};\n"} +{"task_num": 815, "task_title": "Bus Routes", "difficulty": 3, "func_name": "numBusesToDestination", "description": "You are given an array `routes` representing bus routes where `routes[i]` is a\nbus route that the `ith` bus repeats forever.\n\n* For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever.\n\nYou will start at the bus stop `source` (You are not on any bus initially),\nand you want to go to the bus stop `target`. You can travel between bus stops\nby buses only.\n\nReturn the least number of buses you must take to travel from `source` to\n`target`. Return `-1` if it is not possible.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n if source == target:\n return 0\n\n graph = collections.defaultdict(list)\n usedBuses = set()\n\n for i in range(len(routes)):\n for route in routes[i]:\n graph[route].append(i)\n\n ans = 0\n q = collections.deque([source])\n\n while q:\n ans += 1\n for _ in range(len(q)):\n for bus in graph[q.popleft()]:\n if bus in usedBuses:\n continue\n usedBuses.add(bus)\n for nextRoute in routes[bus]:\n if nextRoute == target:\n return ans\n q.append(nextRoute)\n\n return -1\n", "java_solution": "class Solution {\n public int numBusesToDestination(int[][] routes, int source, int target) {\n if (source == target)\n return 0;\n\n Map> graph = new HashMap<>(); // {route: [buses]}\n Set usedBuses = new HashSet<>();\n\n for (int i = 0; i < routes.length; ++i)\n for (final int route : routes[i]) {\n graph.putIfAbsent(route, new ArrayList<>());\n graph.get(route).add(i);\n }\n\n Queue q = new ArrayDeque<>(List.of(source));\n\n for (int step = 1; !q.isEmpty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n for (final int bus : graph.getOrDefault(q.poll(), new ArrayList<>()))\n if (usedBuses.add(bus))\n for (final int nextRoute : routes[bus]) {\n if (nextRoute == target)\n return step;\n q.offer(nextRoute);\n }\n }\n\n return -1;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int numBusesToDestination(vector>& routes, int source,\n int target) {\n if (source == target)\n return 0;\n\n unordered_map> graph; // {route: [buses]}\n unordered_set usedBuses;\n\n for (int i = 0; i < routes.size(); ++i)\n for (const int route : routes[i])\n graph[route].push_back(i);\n\n queue q{{source}};\n\n for (int step = 1; !q.empty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n const int route = q.front();\n q.pop();\n for (const int bus : graph[route])\n if (usedBuses.insert(bus).second)\n for (const int nextRoute : routes[bus]) {\n if (nextRoute == target)\n return step;\n q.push(nextRoute);\n }\n }\n\n return -1;\n }\n};\n"} +{"task_num": 838, "task_title": "Push Dominoes", "difficulty": 2, "func_name": "pushDominoes", "description": "There are `n` dominoes in a line, and we place each domino vertically upright.\nIn the beginning, we simultaneously push some of the dominoes either to the\nleft or to the right.\n\nAfter each second, each domino that is falling to the left pushes the adjacent\ndomino on the left. Similarly, the dominoes falling to the right push their\nadjacent dominoes standing on the right.\n\nWhen a vertical domino has dominoes falling on it from both sides, it stays\nstill due to the balance of the forces.\n\nFor the purposes of this question, we will consider that a falling domino\nexpends no additional force to a falling or already fallen domino.\n\nYou are given a string `dominoes` representing the initial state where:\n\n* `dominoes[i] = 'L'`, if the `ith` domino has been pushed to the left,\n* `dominoes[i] = 'R'`, if the `ith` domino has been pushed to the right, and\n* `dominoes[i] = '.'`, if the `ith` domino has not been pushed.\n\nReturn a string representing the final state.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def pushDominoes(self, dominoes: str) -> str:\n ans = list(dominoes)\n L = -1\n R = -1\n\n for i in range(len(dominoes) + 1):\n if i == len(dominoes) or dominoes[i] == 'R':\n if L < R:\n while R < i:\n ans[R] = 'R'\n R += 1\n R = i\n elif dominoes[i] == 'L':\n if R < L or (L, R) == (-1, -1):\n if (L, R) == (-1, -1):\n L += 1\n while L < i:\n ans[L] = 'L'\n L += 1\n else:\n l = R + 1\n r = i - 1\n while l < r:\n ans[l] = 'R'\n ans[r] = 'L'\n l += 1\n r -= 1\n L = i\n\n return ''.join(ans)\n", "java_solution": "class Solution {\n public String pushDominoes(String dominoes) {\n char[] s = dominoes.toCharArray();\n int L = -1;\n int R = -1;\n\n for (int i = 0; i <= dominoes.length(); ++i)\n if (i == dominoes.length() || s[i] == 'R') {\n if (L < R)\n while (R < i)\n s[R++] = 'R';\n R = i;\n } else if (s[i] == 'L') {\n if (R < L || L == -1 && R == -1) {\n if (L == -1 && R == -1)\n ++L;\n while (L < i)\n s[L++] = 'L';\n } else {\n int l = R + 1;\n int r = i - 1;\n while (l < r) {\n s[l++] = 'R';\n s[r--] = 'L';\n }\n }\n L = i;\n }\n\n return new String(s);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n string pushDominoes(string dominoes) {\n int L = -1;\n int R = -1;\n\n for (int i = 0; i <= dominoes.length(); ++i)\n if (i == dominoes.length() || dominoes[i] == 'R') {\n if (L < R)\n while (R < i)\n dominoes[R++] = 'R';\n R = i;\n } else if (dominoes[i] == 'L') {\n if (R < L || L == -1 && R == -1) {\n if (L == -1 && R == -1)\n ++L;\n while (L < i)\n dominoes[L++] = 'L';\n } else {\n int l = R + 1;\n int r = i - 1;\n while (l < r) {\n dominoes[l++] = 'R';\n dominoes[r--] = 'L';\n }\n }\n L = i;\n }\n\n return dominoes;\n }\n};\n"} +{"task_num": 845, "task_title": "Longest Mountain in Array", "difficulty": 2, "func_name": "longestMountain", "description": "You may recall that an array `arr` is a mountain array if and only if:\n\n* `arr.length >= 3`\n* There exists some index `i` (0-indexed) with `0 < i < arr.length - 1` such that: \n* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`\n* `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`\n\nGiven an integer array `arr`, return the length of the longest subarray, which\nis a mountain. Return `0` if there is no mountain subarray.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def longestMountain(self, arr: List[int]) -> int:\n ans = 0\n i = 0\n\n while i + 1 < len(arr):\n while i + 1 < len(arr) and arr[i] == arr[i + 1]:\n i += 1\n\n increasing = 0\n decreasing = 0\n\n while i + 1 < len(arr) and arr[i] < arr[i + 1]:\n increasing += 1\n i += 1\n\n while i + 1 < len(arr) and arr[i] > arr[i + 1]:\n decreasing += 1\n i += 1\n\n if increasing > 0 and decreasing > 0:\n ans = max(ans, increasing + decreasing + 1)\n\n return ans\n", "java_solution": "class Solution {\n public int longestMountain(int[] arr) {\n int ans = 0;\n\n for (int i = 0; i + 1 < arr.length;) {\n while (i + 1 < arr.length && arr[i] == arr[i + 1])\n ++i;\n\n int increasing = 0;\n int decreasing = 0;\n\n while (i + 1 < arr.length && arr[i] < arr[i + 1]) {\n ++increasing;\n ++i;\n }\n\n while (i + 1 < arr.length && arr[i] > arr[i + 1]) {\n ++decreasing;\n ++i;\n }\n\n if (increasing > 0 && decreasing > 0)\n ans = Math.max(ans, increasing + decreasing + 1);\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int longestMountain(vector& arr) {\n int ans = 0;\n\n for (int i = 0; i + 1 < arr.size();) {\n while (i + 1 < arr.size() && arr[i] == arr[i + 1])\n ++i;\n\n int increasing = 0;\n int decreasing = 0;\n\n while (i + 1 < arr.size() && arr[i] < arr[i + 1]) {\n ++increasing;\n ++i;\n }\n\n while (i + 1 < arr.size() && arr[i] > arr[i + 1]) {\n ++decreasing;\n ++i;\n }\n\n if (increasing > 0 && decreasing > 0)\n ans = max(ans, increasing + decreasing + 1);\n }\n\n return ans;\n }\n};\n"} +{"task_num": 854, "task_title": "K-Similar Strings", "difficulty": 3, "func_name": "kSimilarity", "description": "Strings `s1` and `s2` are `k`-similar (for some non-negative integer `k`) if\nwe can swap the positions of two letters in `s1` exactly `k` times so that the\nresulting string equals `s2`.\n\nGiven two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and\n`s2` are `k`-similar.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n ans = 0\n q = collections.deque([s1])\n seen = {s1}\n\n while q:\n for _ in range(len(q)):\n curr = q.popleft()\n if curr == s2:\n return ans\n for child in self._getChildren(curr, s2):\n if child in seen:\n continue\n q.append(child)\n seen.add(child)\n ans += 1\n\n return -1\n\n def _getChildren(self, curr: str, target: str) -> List[str]:\n children = []\n s = list(curr)\n i = 0\n while curr[i] == target[i]:\n i += 1\n\n for j in range(i + 1, len(s)):\n if s[j] == target[i]:\n s[i], s[j] = s[j], s[i]\n children.append(''.join(s))\n s[i], s[j] = s[j], s[i]\n\n return children\n", "java_solution": "class Solution {\n public int kSimilarity(String s1, String s2) {\n Queue q = new ArrayDeque<>(List.of(s1));\n Set seen = new HashSet<>(Arrays.asList(s1));\n\n for (int step = 0; !q.isEmpty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n final String curr = q.poll();\n if (curr.equals(s2))\n return step;\n for (final String child : getChildren(curr, s2)) {\n if (seen.contains(child))\n continue;\n q.offer(child);\n seen.add(child);\n }\n }\n\n return -1;\n }\n\n private List getChildren(final String curr, final String target) {\n List children = new ArrayList<>();\n char[] charArray = curr.toCharArray();\n int i = 0; // the first index s.t. curr.charAt(i) != target.charAt(i)\n while (curr.charAt(i) == target.charAt(i))\n ++i;\n\n for (int j = i + 1; j < charArray.length; ++j)\n if (curr.charAt(j) == target.charAt(i)) {\n swap(charArray, i, j);\n children.add(String.valueOf(charArray));\n swap(charArray, i, j);\n }\n\n return children;\n }\n\n private void swap(char[] charArray, int i, int j) {\n final char temp = charArray[i];\n charArray[i] = charArray[j];\n charArray[j] = temp;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int kSimilarity(string s1, string s2) {\n queue q{{s1}};\n unordered_set seen{{s1}};\n\n for (int step = 0; !q.empty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n string curr = q.front();\n q.pop();\n if (curr == s2)\n return step;\n for (const string& child : getChildren(curr, s2)) {\n if (seen.contains(child))\n continue;\n q.push(child);\n seen.insert(child);\n }\n }\n\n return -1;\n }\n\n private:\n vector getChildren(string& curr, const string& target) {\n vector children;\n int i = 0; // the first index s.t. curr[i] != target[i]\n while (curr[i] == target[i])\n ++i;\n\n for (int j = i + 1; j < curr.length(); ++j)\n if (curr[j] == target[i]) {\n swap(curr[i], curr[j]);\n children.push_back(curr);\n swap(curr[i], curr[j]);\n }\n\n return children;\n }\n};\n"} +{"task_num": 861, "task_title": "Score After Flipping Matrix", "difficulty": 2, "func_name": "matrixScore", "description": "You are given an `m x n` binary matrix `grid`.\n\nA move consists of choosing any row or column and toggling each value in that\nrow or column (i.e., changing all `0`'s to `1`'s, and all `1`'s to `0`'s).\n\nEvery row of the matrix is interpreted as a binary number, and the score of\nthe matrix is the sum of these numbers.\n\nReturn the highest possible score after making any number of moves (including\nzero moves).\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def matrixScore(self, grid: List[List[int]]) -> int:\n for row in grid:\n if row[0] == 0:\n self._flip(row)\n\n for j, col in enumerate(list(zip(*grid))):\n if sum(col) * 2 < len(grid):\n self._flipCol(grid, j)\n\n return sum(self._binary(row) for row in grid)\n\n def _flip(self, row: List[int]) -> None:\n for i in range(len(row)):\n row[i] ^= 1\n\n def _flipCol(self, grid: List[List[int]], j: int) -> None:\n for i in range(len(grid)):\n grid[i][j] ^= 1\n\n def _binary(self, row: List[int]) -> int:\n res = row[0]\n for j in range(1, len(row)):\n res = res * 2 + row[j]\n return res\n", "java_solution": "class Solution {\n public int matrixScore(int[][] grid) {\n final int m = grid.length;\n final int n = grid[0].length;\n int ans = 0;\n\n // Flip the rows with a leading 0.\n for (int[] row : grid)\n if (row[0] == 0)\n flip(row);\n\n // Flip the columns with 1s < 0s.\n for (int j = 0; j < n; ++j)\n if (onesColCount(grid, j) * 2 < m)\n flipCol(grid, j);\n\n // Add a binary number for each row.\n for (int[] row : grid)\n ans += binary(row);\n\n return ans;\n }\n\n private void flip(int[] row) {\n for (int i = 0; i < row.length; ++i)\n row[i] ^= 1;\n }\n\n private int onesColCount(int[][] grid, int j) {\n int ones = 0;\n for (int i = 0; i < grid.length; ++i)\n ones += grid[i][j];\n return ones;\n }\n\n private void flipCol(int[][] grid, int j) {\n for (int i = 0; i < grid.length; ++i)\n grid[i][j] ^= 1;\n }\n\n private int binary(int[] row) {\n int res = row[0];\n for (int j = 1; j < row.length; ++j)\n res = res * 2 + row[j];\n return res;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int matrixScore(vector>& grid) {\n const int m = grid.size();\n const int n = grid[0].size();\n int ans = 0;\n\n // Flip the rows with a leading 0.\n for (auto& row : grid)\n if (row[0] == 0)\n flip(row);\n\n // Flip the columns with 1s < 0s.\n for (int j = 0; j < n; ++j)\n if (onesColCount(grid, j) * 2 < m)\n flipCol(grid, j);\n\n // Add a binary number for each row.\n for (const vector& row : grid)\n ans += binary(row);\n\n return ans;\n }\n\n private:\n void flip(vector& row) {\n for (int i = 0; i < row.size(); ++i)\n row[i] ^= 1;\n }\n\n int onesColCount(const vector>& grid, int j) {\n int ones = 0;\n for (int i = 0; i < grid.size(); ++i)\n ones += grid[i][j];\n return ones;\n }\n\n void flipCol(vector>& grid, int j) {\n for (int i = 0; i < grid.size(); ++i)\n grid[i][j] ^= 1;\n }\n\n int binary(const vector& row) {\n int res = row[0];\n for (int j = 1; j < row.size(); ++j)\n res = res * 2 + row[j];\n return res;\n }\n};\n"} +{"task_num": 866, "task_title": "Prime Palindrome", "difficulty": 2, "func_name": "primePalindrome", "description": "Given an integer n, return the smallest prime palindrome greater than or equal\nto `n`.\n\nAn integer is prime if it has exactly two divisors: `1` and itself. Note that\n`1` is not a prime number.\n\n* For example, `2`, `3`, `5`, `7`, `11`, and `13` are all primes.\n\nAn integer is a palindrome if it reads the same from left to right as it does\nfrom right to left.\n\n* For example, `101` and `12321` are palindromes.\n\nThe test cases are generated so that the answer always exists and is in the\nrange `[2, 2 * 108]`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def primePalindrome(self, n: int) -> int:\n def getPalindromes(n: int):\n length = n // 2\n for i in range(10**(length - 1), 10**length):\n s = str(i)\n for j in range(10):\n yield int(s + str(j) + s[::-1])\n\n def isPrime(num: int) -> bool:\n for i in range(2, int(num**0.5 + 1)):\n if num % i == 0:\n return False\n return True\n\n if n <= 2:\n return 2\n if n == 3:\n return 3\n if n <= 5:\n return 5\n if n <= 7:\n return 7\n if n <= 11:\n return 11\n\n nLength = len(str(n))\n\n while True:\n for num in getPalindromes(nLength):\n if num >= n and isPrime(num):\n return num\n nLength += 1\n", "java_solution": "class Solution {\n public int primePalindrome(int n) {\n if (n <= 2)\n return 2;\n if (n == 3)\n return 3;\n if (n <= 5)\n return 5;\n if (n <= 7)\n return 7;\n if (n <= 11)\n return 11;\n\n int nLength = String.valueOf(n).length();\n\n while (true) {\n for (final int num : getPalindromes(nLength))\n if (num >= n && isPrime(num))\n return num;\n ++nLength;\n }\n }\n\n private List getPalindromes(int n) {\n List palindromes = new ArrayList<>();\n int length = n / 2;\n\n for (int i = (int) Math.pow(10, length - 1); i < (int) Math.pow(10, length); ++i) {\n String s = String.valueOf(i);\n String reversedS = new StringBuilder(s).reverse().toString();\n for (int j = 0; j < 10; ++j)\n palindromes.add(Integer.valueOf(s + String.valueOf(j) + reversedS));\n }\n\n return palindromes;\n }\n\n private boolean isPrime(int num) {\n for (int i = 2; i < (int) Math.sqrt(num) + 1; ++i)\n if (num % i == 0)\n return false;\n return true;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int primePalindrome(int n) {\n if (n <= 2)\n return 2;\n if (n == 3)\n return 3;\n if (n <= 5)\n return 5;\n if (n <= 7)\n return 7;\n if (n <= 11)\n return 11;\n\n int nLength = to_string(n).length();\n\n while (true) {\n for (const int num : getPalindromes(nLength))\n if (num >= n && isPrime(num))\n return num;\n ++nLength;\n }\n\n throw;\n }\n\n private:\n vector getPalindromes(int n) {\n vector palindromes;\n const int length = n / 2;\n\n for (int i = pow(10, length - 1); i < pow(10, length); ++i) {\n const string s = to_string(i);\n string reversedS = s;\n ranges::reverse(reversedS);\n for (int j = 0; j < 10; ++j)\n palindromes.push_back(stoi(s + to_string(j) + reversedS));\n }\n\n return palindromes;\n }\n\n bool isPrime(int num) {\n for (int i = 2; i < sqrt(num) + 1; ++i)\n if (num % i == 0)\n return false;\n return true;\n }\n};\n"} +{"task_num": 882, "task_title": "Reachable Nodes In Subdivided Graph", "difficulty": 3, "func_name": "reachableNodes", "description": "You are given an undirected graph (the \"original graph\") with `n` nodes\nlabeled from `0` to `n - 1`. You decide to subdivide each edge in the graph\ninto a chain of nodes, with the number of new nodes varying between each edge.\n\nThe graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]`\nindicates that there is an edge between nodes `ui` and `vi` in the original\ngraph, and `cnti` is the total number of new nodes that you will subdivide the\nedge into. Note that `cnti == 0` means you will not subdivide the edge.\n\nTo subdivide the edge `[ui, vi]`, replace it with `(cnti + 1)` new edges and\n`cnti` new nodes. The new nodes are `x1`, `x2`, ..., `xcnti`, and the new\nedges are `[ui, x1]`, `[x1, x2]`, `[x2, x3]`, ..., `[xcnti-1, xcnti]`,\n`[xcnti, vi]`.\n\nIn this new graph, you want to know how many nodes are reachable from the node\n`0`, where a node is reachable if the distance is `maxMoves` or less.\n\nGiven the original graph and `maxMoves`, return the number of nodes that are\nreachable from node `0` in the new graph.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:\n graph = [[] for _ in range(n)]\n dist = [maxMoves + 1] * n\n\n for u, v, cnt in edges:\n graph[u].append((v, cnt))\n graph[v].append((u, cnt))\n\n reachableNodes = self._dijkstra(graph, 0, maxMoves, dist)\n reachableSubnodes = 0\n\n for u, v, cnt in edges:\n a = 0 if dist[u] > maxMoves else min(maxMoves - dist[u], cnt)\n b = 0 if dist[v] > maxMoves else min(maxMoves - dist[v], cnt)\n reachableSubnodes += min(a + b, cnt)\n\n return reachableNodes + reachableSubnodes\n\n def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, maxMoves: int, dist: List[int]) -> int:\n dist[src] = 0\n minHeap = [(dist[src], src)]\n\n while minHeap:\n d, u = heapq.heappop(minHeap)\n if dist[u] >= maxMoves:\n break\n if d > dist[u]:\n continue\n for v, w in graph[u]:\n newDist = d + w + 1\n if newDist < dist[v]:\n dist[v] = newDist\n heapq.heappush(minHeap, (newDist, v))\n\n return sum(d <= maxMoves for d in dist)\n", "java_solution": "class Solution {\n public int reachableNodes(int[][] edges, int maxMoves, int n) {\n List>[] graph = new List[n];\n int[] dist = new int[n];\n Arrays.fill(dist, maxMoves + 1);\n Arrays.setAll(graph, i -> new ArrayList<>());\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n final int cnt = edge[2];\n graph[u].add(new Pair<>(v, cnt));\n graph[v].add(new Pair<>(u, cnt));\n }\n\n final int reachableNodes = dijkstra(graph, 0, maxMoves, dist);\n int reachableSubnodes = 0;\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n final int cnt = edge[2];\n // the number of reachable nodes of `edge` from `u`\n final int a = dist[u] > maxMoves ? 0 : Math.min(maxMoves - dist[u], cnt);\n // the number of reachable nodes of `edge` from `v`\n final int b = dist[v] > maxMoves ? 0 : Math.min(maxMoves - dist[v], cnt);\n reachableSubnodes += Math.min(a + b, cnt);\n }\n\n return reachableNodes + reachableSubnodes;\n }\n\n private int dijkstra(List>[] graph, int src, int maxMoves, int[] dist) {\n dist[src] = 0;\n Queue> minHeap =\n new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) {\n { offer(new Pair<>(dist[src], src)); } // (d, u)\n };\n\n while (!minHeap.isEmpty()) {\n final int d = minHeap.peek().getKey();\n final int u = minHeap.poll().getValue();\n // Already took `maxMoves` to reach `u`, so can't explore anymore.\n if (d >= maxMoves)\n break;\n if (d > dist[u])\n continue;\n for (Pair pair : graph[u]) {\n final int v = pair.getKey();\n final int w = pair.getValue();\n if (d + w + 1 < dist[v]) {\n dist[v] = d + w + 1;\n minHeap.offer(new Pair<>(dist[v], v));\n }\n }\n }\n\n return (int) Arrays.stream(dist).filter(d -> d <= maxMoves).count();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int reachableNodes(vector>& edges, int maxMoves, int n) {\n vector>> graph(n);\n vector dist(graph.size(), maxMoves + 1);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n const int cnt = edge[2];\n graph[u].emplace_back(v, cnt);\n graph[v].emplace_back(u, cnt);\n }\n\n const int reachableNodes = dijkstra(graph, 0, maxMoves, dist);\n int reachableSubnodes = 0;\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n const int cnt = edge[2];\n // the number of reachable nodes of `edge` from `u`\n const int a = dist[u] > maxMoves ? 0 : min(maxMoves - dist[u], cnt);\n // the number of reachable nodes of `edge` from `v`\n const int b = dist[v] > maxMoves ? 0 : min(maxMoves - dist[v], cnt);\n reachableSubnodes += min(a + b, cnt);\n }\n\n return reachableNodes + reachableSubnodes;\n }\n\n private:\n int dijkstra(const vector>>& graph, int src,\n int maxMoves, vector& dist) {\n dist[src] = 0;\n using P = pair; // (d, u)\n priority_queue, greater<>> minHeap;\n minHeap.emplace(dist[src], src);\n\n while (!minHeap.empty()) {\n const auto [d, u] = minHeap.top();\n minHeap.pop();\n // Already took `maxMoves` to reach `u`, so can't explore anymore.\n if (d >= maxMoves)\n break;\n if (d > dist[u])\n continue;\n for (const auto& [v, w] : graph[u])\n if (d + w + 1 < dist[v]) {\n dist[v] = d + w + 1;\n minHeap.emplace(dist[v], v);\n }\n }\n\n return ranges::count_if(dist, [&](int d) { return d <= maxMoves; });\n }\n};\n"} +{"task_num": 909, "task_title": "Snakes and Ladders", "difficulty": 2, "func_name": "snakesAndLadders", "description": "You are given an `n x n` integer matrix `board` where the cells are labeled\nfrom `1` to `n2` in a Boustrophedon style starting from the bottom left of the\nboard (i.e. `board[n - 1][0]`) and alternating direction each row.\n\nYou start on square `1` of the board. In each move, starting from square\n`curr`, do the following:\n\n* Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`. \n* This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board.\n* If `next` has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to `next`.\n* The game ends when you reach the square `n2`.\n\nA board square on row `r` and column `c` has a snake or ladder if `board[r][c]\n!= -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1`\nand `n2` do not have a snake or ladder.\n\nNote that you only take a snake or ladder at most once per move. If the\ndestination to a snake or ladder is the start of another snake or ladder, you\ndo not follow the subsequent snake or ladder.\n\n* For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do not follow the subsequent ladder to `4`.\n\nReturn the least number of moves required to reach the square `n2`. If it is\nnot possible to reach the square, return `-1`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n ans = 0\n q = collections.deque([1])\n seen = set()\n A = [0] * (1 + n * n)\n\n for i in range(n):\n for j in range(n):\n if n - i & 1 :\n A[(n - 1 - i) * n + (j + 1)] = board[i][j]\n else:\n A[(n - 1 - i) * n + (n - j)] = board[i][j]\n\n while q:\n ans += 1\n for _ in range(len(q)):\n curr = q.popleft()\n for next in range(curr + 1, min(curr + 6, n * n) + 1):\n dest = A[next] if A[next] > 0 else next\n if dest == n * n:\n return ans\n if dest in seen:\n continue\n q.append(dest)\n seen.add(dest)\n\n return -1\n", "java_solution": "class Solution {\n public int snakesAndLadders(int[][] board) {\n final int n = board.length;\n Queue q = new ArrayDeque<>(List.of(1));\n boolean[] seen = new boolean[1 + n * n];\n int[] arr = new int[1 + n * n]; // 2D -> 1D\n\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n arr[(n - 1 - i) * n + ((n - i) % 2 == 0 ? n - j : j + 1)] = board[i][j];\n\n for (int step = 1; !q.isEmpty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n final int curr = q.poll();\n for (int next = curr + 1; next <= Math.min(curr + 6, n * n); ++next) {\n final int dest = arr[next] > 0 ? arr[next] : next;\n if (dest == n * n)\n return step;\n if (seen[dest])\n continue;\n q.offer(dest);\n seen[dest] = true;\n }\n }\n\n return -1;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int snakesAndLadders(vector>& board) {\n const int n = board.size();\n queue q{{1}};\n vector seen(1 + n * n);\n vector arr(1 + n * n); // 2D -> 1D\n\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n arr[(n - 1 - i) * n + ((n - i) % 2 == 0 ? n - j : j + 1)] = board[i][j];\n\n for (int step = 1; !q.empty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n const int curr = q.front();\n q.pop();\n for (int next = curr + 1; next <= min(curr + 6, n * n); ++next) {\n const int dest = arr[next] > 0 ? arr[next] : next;\n if (dest == n * n)\n return step;\n if (seen[dest])\n continue;\n q.push(dest);\n seen[dest] = true;\n }\n }\n\n return -1;\n }\n};\n"} +{"task_num": 913, "task_title": "Cat and Mouse", "difficulty": 3, "func_name": "catMouseGame", "description": "A game on an undirected graph is played by two players, Mouse and Cat, who\nalternate turns.\n\nThe graph is given as follows: `graph[a]` is a list of all nodes `b` such that\n`ab` is an edge of the graph.\n\nThe mouse starts at node `1` and goes first, the cat starts at node `2` and\ngoes second, and there is a hole at node `0`.\n\nDuring each player's turn, they must travel along one edge of the graph that\nmeets where they are. For example, if the Mouse is at node 1, it must travel\nto any node in `graph[1]`.\n\nAdditionally, it is not allowed for the Cat to travel to the Hole (node `0`).\n\nThen, the game can end in three ways:\n\n* If ever the Cat occupies the same node as the Mouse, the Cat wins.\n* If ever the Mouse reaches the Hole, the Mouse wins.\n* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.\n\nGiven a `graph`, and assuming both players play optimally, return\n\n* `1` if the mouse wins the game,\n* `2` if the cat wins the game, or\n* `0` if the game is a draw.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nfrom enum import IntEnum\n\n\nclass State(IntEnum):\n kDraw = 0\n kMouseWin = 1\n kCatWin = 2\n\n\nclass Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n n = len(graph)\n states = [[[0] * 2 for i in range(n)] for j in range(n)]\n outDegree = [[[0] * 2 for i in range(n)] for j in range(n)]\n q = collections.deque()\n\n for cat in range(n):\n for mouse in range(n):\n outDegree[cat][mouse][0] = len(graph[mouse])\n outDegree[cat][mouse][1] = len(graph[cat]) - graph[cat].count(0)\n\n for cat in range(1, n):\n for move in range(2):\n states[cat][0][move] = int(State.kMouseWin)\n q.append((cat, 0, move, int(State.kMouseWin)))\n states[cat][cat][move] = int(State.kCatWin)\n q.append((cat, cat, move, int(State.kCatWin)))\n\n while q:\n cat, mouse, move, state = q.popleft()\n if cat == 2 and mouse == 1 and move == 0:\n return state\n prevMove = move ^ 1\n for prev in graph[cat if prevMove else mouse]:\n prevCat = prev if prevMove else cat\n if prevCat == 0:\n continue\n prevMouse = mouse if prevMove else prev\n if states[prevCat][prevMouse][prevMove]:\n continue\n if prevMove == 0 and state == int(State.kMouseWin) or \\\n prevMove == 1 and state == int(State.kCatWin):\n states[prevCat][prevMouse][prevMove] = state\n q.append((prevCat, prevMouse, prevMove, state))\n else:\n outDegree[prevCat][prevMouse][prevMove] -= 1\n if outDegree[prevCat][prevMouse][prevMove] == 0:\n states[prevCat][prevMouse][prevMove] = state\n q.append((prevCat, prevMouse, prevMove, state))\n\n return states[2][1][0]\n", "java_solution": "enum State { DRAW, MOUSE_WIN, CAT_WIN }\n\nclass Solution {\n public int catMouseGame(int[][] graph) {\n final int n = graph.length;\n // result of (cat, mouse, move)\n // move := 0 (mouse) / 1 (cat)\n int[][][] states = new int[n][n][2];\n int[][][] outDegree = new int[n][n][2];\n Queue q = new ArrayDeque<>();\n\n for (int cat = 0; cat < n; ++cat)\n for (int mouse = 0; mouse < n; ++mouse) {\n outDegree[cat][mouse][0] = graph[mouse].length;\n outDegree[cat][mouse][1] =\n graph[cat].length - (Arrays.stream(graph[cat]).anyMatch(v -> v == 0) ? 1 : 0);\n }\n\n // Start from the states s.t. the winner can be determined.\n for (int cat = 1; cat < n; ++cat)\n for (int move = 0; move < 2; ++move) {\n // Mouse is in the hole.\n states[cat][0][move] = State.MOUSE_WIN.ordinal();\n q.offer(new int[] {cat, 0, move, State.MOUSE_WIN.ordinal()});\n // Cat catches mouse.\n states[cat][cat][move] = State.CAT_WIN.ordinal();\n q.offer(new int[] {cat, cat, move, State.CAT_WIN.ordinal()});\n }\n\n while (!q.isEmpty()) {\n final int cat = q.peek()[0];\n final int mouse = q.peek()[1];\n final int move = q.peek()[2];\n final int state = q.poll()[3];\n if (cat == 2 && mouse == 1 && move == 0)\n return state;\n final int prevMove = move ^ 1;\n for (final int prev : graph[prevMove == 0 ? mouse : cat]) {\n final int prevCat = prevMove == 0 ? cat : prev;\n if (prevCat == 0) // invalid\n continue;\n final int prevMouse = prevMove == 0 ? prev : mouse;\n // The state has been determined.\n if (states[prevCat][prevMouse][prevMove] > 0)\n continue;\n if (prevMove == 0 && state == State.MOUSE_WIN.ordinal() ||\n prevMove == 1 && state == State.CAT_WIN.ordinal() ||\n --outDegree[prevCat][prevMouse][prevMove] == 0) {\n states[prevCat][prevMouse][prevMove] = state;\n q.offer(new int[] {prevCat, prevMouse, prevMove, state});\n }\n }\n }\n\n return states[2][1][0];\n }\n}\n", "cpp_solution": "enum class State { kDraw, kMouseWin, kCatWin };\n\nclass Solution {\n public:\n int catMouseGame(vector>& graph) {\n const int n = graph.size();\n // result of (cat, mouse, move)\n // move := 0 (mouse) / 1 (cat)\n vector>> states(\n n, vector>(n, vector(2)));\n vector>> outDegree(\n n, vector>(n, vector(2)));\n queue> q; // (cat, mouse, move, state)\n\n for (int cat = 0; cat < n; ++cat)\n for (int mouse = 0; mouse < n; ++mouse) {\n outDegree[cat][mouse][0] = graph[mouse].size();\n outDegree[cat][mouse][1] =\n graph[cat].size() - ranges::count(graph[cat], 0);\n }\n\n // Start from the states s.t. the winner can be determined.\n for (int cat = 1; cat < n; ++cat)\n for (int move = 0; move < 2; ++move) {\n // Mouse is in the hole.\n states[cat][0][move] = State::kMouseWin;\n q.emplace(cat, 0, move, State::kMouseWin);\n // Cat catches mouse.\n states[cat][cat][move] = State::kCatWin;\n q.emplace(cat, cat, move, State::kCatWin);\n }\n\n while (!q.empty()) {\n const auto [cat, mouse, move, state] = q.front();\n q.pop();\n if (cat == 2 && mouse == 1 && move == 0)\n return static_cast(state);\n const int prevMove = move ^ 1;\n for (const int prev : graph[prevMove ? cat : mouse]) {\n const int prevCat = prevMove ? prev : cat;\n if (prevCat == 0) // invalid\n continue;\n const int prevMouse = prevMove ? mouse : prev;\n // The state has been determined.\n if (states[prevCat][prevMouse][prevMove] != State::kDraw)\n continue;\n if (prevMove == 0 && state == State::kMouseWin ||\n prevMove == 1 && state == State::kCatWin ||\n --outDegree[prevCat][prevMouse][prevMove] == 0) {\n states[prevCat][prevMouse][prevMove] = state;\n q.emplace(prevCat, prevMouse, prevMove, state);\n }\n }\n }\n\n return static_cast(states[2][1][0]);\n }\n};\n"} +{"task_num": 923, "task_title": "3Sum With Multiplicity", "difficulty": 2, "func_name": "threeSumMulti", "description": "Given an integer array `arr`, and an integer `target`, return the number of\ntuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] ==\ntarget`.\n\nAs the answer can be very large, return it modulo `109 + 7`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def threeSumMulti(self, arr: List[int], target: int) -> int:\n kMod = 1_000_000_007\n ans = 0\n count = collections.Counter(arr)\n\n for i, x in count.items():\n for j, y in count.items():\n k = target - i - j\n if k not in count:\n continue\n if i == j and j == k:\n ans = (ans + x * (x - 1) * (x - 2) // 6) % kMod\n elif i == j and j != k:\n ans = (ans + x * (x - 1) // 2 * count[k]) % kMod\n elif i < j and j < k:\n ans = (ans + x * y * count[k]) % kMod\n\n return ans % kMod\n", "java_solution": "class Solution {\n public int threeSumMulti(int[] arr, int target) {\n final int MOD = 1_000_000_007;\n int ans = 0;\n Map count = new HashMap<>();\n\n for (final int a : arr)\n count.merge(a, 1, Integer::sum);\n\n for (Map.Entry entry : count.entrySet()) {\n final int i = entry.getKey();\n final int x = entry.getValue();\n for (Map.Entry entry2 : count.entrySet()) {\n final int j = entry2.getKey();\n final int y = entry2.getValue();\n final int k = target - i - j;\n if (!count.containsKey(k))\n continue;\n if (i == j && j == k)\n ans = (int) ((ans + (long) x * (x - 1) * (x - 2) / 6) % MOD);\n else if (i == j && j != k)\n ans = (int) ((ans + (long) x * (x - 1) / 2 * count.get(k)) % MOD);\n else if (i < j && j < k)\n ans = (int) ((ans + (long) x * y * count.get(k)) % MOD);\n }\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int threeSumMulti(vector& arr, int target) {\n constexpr int kMod = 1'000'000'007;\n int ans = 0;\n unordered_map count;\n\n for (const int a : arr)\n ++count[a];\n\n for (const auto& [i, x] : count)\n for (const auto& [j, y] : count) {\n const int k = target - i - j;\n const auto it = count.find(k);\n if (it == count.cend())\n continue;\n if (i == j && j == k)\n ans = (ans + static_cast(x) * (x - 1) * (x - 2) / 6) % kMod;\n else if (i == j && j != k)\n ans = (ans + static_cast(x) * (x - 1) / 2 * it->second) % kMod;\n else if (i < j && j < k)\n ans = (ans + static_cast(x) * y * it->second) % kMod;\n }\n\n return ans;\n }\n};\n"} +{"task_num": 927, "task_title": "Three Equal Parts", "difficulty": 3, "func_name": "threeEqualParts", "description": "You are given an array `arr` which consists of only zeros and ones, divide the\narray into three non-empty parts such that all of these parts represent the\nsame binary value.\n\nIf it is possible, return any `[i, j]` with `i + 1 < j`, such that:\n\n* `arr[0], arr[1], ..., arr[i]` is the first part,\n* `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and\n* `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part.\n* All three parts have equal binary values.\n\nIf it is not possible, return `[-1, -1]`.\n\nNote that the entire part is used when considering what binary value it\nrepresents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also,\nleading zeros are allowed, so `[0,1,1]` and `[1,1]` represent the same value.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def threeEqualParts(self, arr: List[int]) -> List[int]:\n ones = sum(a == 1 for a in arr)\n\n if ones == 0:\n return [0, len(arr) - 1]\n if ones % 3 != 0:\n return [-1, -1]\n\n k = ones // 3\n i = 0\n\n for i in range(len(arr)):\n if arr[i] == 1:\n first = i\n break\n\n gapOnes = k\n\n for j in range(i + 1, len(arr)):\n if arr[j] == 1:\n gapOnes -= 1\n if gapOnes == 0:\n second = j\n break\n\n gapOnes = k\n\n for i in range(j + 1, len(arr)):\n if arr[i] == 1:\n gapOnes -= 1\n if gapOnes == 0:\n third = i\n break\n\n while third < len(arr) and arr[first] == arr[second] == arr[third]:\n first += 1\n second += 1\n third += 1\n\n if third == len(arr):\n return [first - 1, second]\n return [-1, -1]\n", "java_solution": "class Solution {\n public int[] threeEqualParts(int[] arr) {\n int ones = 0;\n\n for (final int a : arr)\n if (a == 1)\n ++ones;\n\n if (ones == 0)\n return new int[] {0, arr.length - 1};\n if (ones % 3 != 0)\n return new int[] {-1, -1};\n\n int k = ones / 3;\n int i = 0;\n int j = 0;\n int first = 0;\n int second = 0;\n int third = 0;\n\n for (i = 0; i < arr.length; ++i)\n if (arr[i] == 1) {\n first = i;\n break;\n }\n\n int gapOnes = k;\n\n for (j = i + 1; j < arr.length; ++j)\n if (arr[j] == 1 && --gapOnes == 0) {\n second = j;\n break;\n }\n\n gapOnes = k;\n\n for (i = j + 1; i < arr.length; ++i)\n if (arr[i] == 1 && --gapOnes == 0) {\n third = i;\n break;\n }\n\n while (third < arr.length && arr[first] == arr[second] && arr[second] == arr[third]) {\n ++first;\n ++second;\n ++third;\n }\n\n if (third == arr.length)\n return new int[] {first - 1, second};\n return new int[] {-1, -1};\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector threeEqualParts(vector& arr) {\n const int ones = ranges::count_if(arr, [](int a) { return a == 1; });\n\n if (ones == 0)\n return {0, static_cast(arr.size()) - 1};\n if (ones % 3 != 0)\n return {-1, -1};\n\n int k = ones / 3;\n int i;\n int j;\n int first;\n int second;\n int third;\n\n for (i = 0; i < arr.size(); ++i)\n if (arr[i] == 1) {\n first = i;\n break;\n }\n\n int gapOnes = k;\n\n for (j = i + 1; j < arr.size(); ++j)\n if (arr[j] == 1 && --gapOnes == 0) {\n second = j;\n break;\n }\n\n gapOnes = k;\n\n for (i = j + 1; i < arr.size(); ++i)\n if (arr[i] == 1 && --gapOnes == 0) {\n third = i;\n break;\n }\n\n while (third < arr.size() && arr[first] == arr[second] &&\n arr[second] == arr[third]) {\n ++first;\n ++second;\n ++third;\n }\n\n if (third == arr.size())\n return {first - 1, second};\n return {-1, -1};\n }\n};\n"} +{"task_num": 935, "task_title": "Knight Dialer", "difficulty": 2, "func_name": "knightDialer", "description": "The chess knight has a unique movement, it may move two squares vertically and\none square horizontally, or two squares horizontally and one square vertically\n(with both forming the shape of an L). The possible movements of chess knight\nare shown in this diagram:\n\nA chess knight can move as indicated in the chess diagram below:\n\nWe have a chess knight and a phone pad as shown below, the knight can only\nstand on a numeric cell (i.e. blue cell).\n\nGiven an integer `n`, return how many distinct phone numbers of length `n` we\ncan dial.\n\nYou are allowed to place the knight on any numeric cell initially and then you\nshould perform `n - 1` jumps to dial a number of length `n`. All jumps should\nbe valid knight jumps.\n\nAs the answer may be very large, return the answer modulo `109 + 7`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def knightDialer(self, n: int) -> int:\n dirs = ((1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2))\n kMod = 1_000_000_007\n\n dp = [[1] * 3 for _ in range(4)]\n dp[3][0] = dp[3][2] = 0\n\n for _ in range(n - 1):\n newDp = [[0] * 3 for _ in range(4)]\n for i in range(4):\n for j in range(3):\n if (i, j) in ((3, 0), (3, 2)):\n continue\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x >= 4 or y < 0 or y >= 3:\n continue\n if (x, y) in ((3, 0), (3, 2)):\n continue\n newDp[x][y] = (newDp[x][y] + dp[i][j]) % kMod\n dp = newDp\n\n return sum(map(sum, dp)) % kMod\n", "java_solution": "class Solution {\n public int knightDialer(int n) {\n final int[][] DIRS = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}};\n final int MOD = 1_000_000_007;\n // dp[i][j] := the number of ways to stand on (i, j)\n int[][] dp = new int[4][3];\n Arrays.stream(dp).forEach(A -> Arrays.fill(A, 1));\n dp[3][0] = dp[3][2] = 0;\n\n for (int k = 0; k < n - 1; ++k) {\n int[][] newDp = new int[4][3];\n for (int i = 0; i < 4; ++i)\n for (int j = 0; j < 3; ++j) {\n if (isNotNumericCell(i, j))\n continue;\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x >= 4 || y < 0 || y >= 3)\n continue;\n if (isNotNumericCell(x, y))\n continue;\n newDp[i][j] = (newDp[i][j] + dp[x][y]) % MOD;\n }\n }\n dp = newDp;\n }\n\n int ans = 0;\n\n for (int[] row : dp)\n for (final int a : row)\n ans = (ans + a) % MOD;\n\n return ans;\n }\n\n private boolean isNotNumericCell(int i, int j) {\n return i == 3 && (j == 0 || j == 2);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int knightDialer(int n) {\n constexpr int kDirs[8][2] = {{1, 2}, {2, 1}, {2, -1}, {1, -2},\n {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}};\n constexpr int kMod = 1'000'000'007;\n\n // dp[i][j] := the number of ways to stand on (i, j)\n vector> dp(4, vector(3, 1));\n dp[3][0] = dp[3][2] = 0;\n\n for (int k = 0; k < n - 1; ++k) {\n vector> newDp(4, vector(3));\n for (int i = 0; i < 4; ++i)\n for (int j = 0; j < 3; ++j) {\n if (isNotNumericCell(i, j))\n continue;\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x >= 4 || y < 0 || y >= 3)\n continue;\n if (isNotNumericCell(x, y))\n continue;\n newDp[i][j] = (newDp[i][j] + dp[x][y]) % kMod;\n }\n }\n dp = std::move(newDp);\n }\n\n int ans = 0;\n\n for (const vector& row : dp)\n for (const int a : row)\n ans = (ans + a) % kMod;\n\n return ans;\n }\n\n private:\n bool isNotNumericCell(int i, int j) {\n return i == 3 && (j == 0 || j == 2);\n }\n};\n"} +{"task_num": 939, "task_title": "Minimum Area Rectangle", "difficulty": 2, "func_name": "minAreaRect", "description": "You are given an array of points in the X-Y plane `points` where `points[i] =\n[xi, yi]`.\n\nReturn the minimum area of a rectangle formed from these points, with sides\nparallel to the X and Y axes. If there is not any such rectangle, return `0`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minAreaRect(self, points: List[List[int]]) -> int:\n ans = math.inf\n xToYs = collections.defaultdict(set)\n\n for x, y in points:\n xToYs[x].add(y)\n\n for i in range(len(points)):\n for j in range(i):\n x1, y1 = points[i]\n x2, y2 = points[j]\n if x1 == x2 or y1 == y2:\n continue\n if y2 in xToYs[x1] and y1 in xToYs[x2]:\n ans = min(ans, abs(x1 - x2) * abs(y1 - y2))\n\n return ans if ans < math.inf else 0\n", "java_solution": "class Solution {\n public int minAreaRect(int[][] points) {\n int ans = Integer.MAX_VALUE;\n Map> xToYs = new HashMap<>();\n\n for (int[] p : points) {\n xToYs.putIfAbsent(p[0], new HashSet<>());\n xToYs.get(p[0]).add(p[1]);\n }\n\n for (int i = 1; i < points.length; ++i)\n for (int j = 0; j < i; ++j) {\n int[] p = points[i];\n int[] q = points[j];\n if (p[0] == q[0] || p[1] == q[1])\n continue;\n if (xToYs.get(p[0]).contains(q[1]) && xToYs.get(q[0]).contains(p[1]))\n ans = Math.min(ans, Math.abs(p[0] - q[0]) * Math.abs(p[1] - q[1]));\n }\n\n return ans == Integer.MAX_VALUE ? 0 : ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minAreaRect(vector>& points) {\n int ans = INT_MAX;\n unordered_map> xToYs;\n\n for (const vector& p : points)\n xToYs[p[0]].insert(p[1]);\n\n for (int i = 1; i < points.size(); ++i)\n for (int j = 0; j < i; ++j) {\n const vector& p = points[i];\n const vector& q = points[j];\n if (p[0] == q[0] || p[1] == q[1])\n continue;\n if (xToYs[p[0]].contains(q[1]) && xToYs[q[0]].contains(p[1]))\n ans = min(ans, abs(p[0] - q[0]) * abs(p[1] - q[1]));\n }\n\n return ans == INT_MAX ? 0 : ans;\n }\n};\n"} +{"task_num": 952, "task_title": "Largest Component Size by Common Factor", "difficulty": 3, "func_name": "largestComponentSize", "description": "You are given an integer array of unique positive integers `nums`. Consider\nthe following graph:\n\n* There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`,\n* There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`.\n\nReturn the size of the largest connected component in the graph.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self.find(u)\n j = self.find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n ans = 0\n uf = UnionFind(max(nums) + 1)\n count = collections.Counter()\n\n for num in nums:\n for x in range(2, int(math.sqrt(num) + 1)):\n if num % x == 0:\n uf.unionByRank(num, x)\n uf.unionByRank(num, num // x)\n\n for num in nums:\n numRoot = uf.find(num)\n count[numRoot] += 1\n ans = max(ans, count[numRoot])\n\n return ans\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public void unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n public int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n\n private int[] id;\n private int[] rank;\n}\n\nclass Solution {\n public int largestComponentSize(int[] nums) {\n final int n = Arrays.stream(nums).max().getAsInt();\n int ans = 0;\n UnionFind uf = new UnionFind(n + 1);\n Map count = new HashMap<>();\n\n for (final int num : nums)\n for (int x = 2; x <= (int) Math.sqrt(num); ++x)\n if (num % x == 0) {\n uf.unionByRank(num, x);\n uf.unionByRank(num, num / x);\n }\n\n for (final int num : nums)\n ans = Math.max(ans, count.merge(uf.find(num), 1, Integer::sum));\n\n return ans;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n), rank(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n void unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n\n private:\n vector id;\n vector rank;\n};\n\nclass Solution {\n public:\n int largestComponentSize(vector& nums) {\n const int n = ranges::max(nums);\n int ans = 0;\n UnionFind uf(n + 1);\n unordered_map count;\n\n for (const int num : nums)\n for (int x = 2; x <= sqrt(num); ++x)\n if (num % x == 0) {\n uf.unionByRank(num, x);\n uf.unionByRank(num, num / x);\n }\n\n for (const int num : nums)\n ans = max(ans, ++count[uf.find(num)]);\n\n return ans;\n }\n};\n"} +{"task_num": 963, "task_title": "Minimum Area Rectangle II", "difficulty": 2, "func_name": "minAreaFreeRect", "description": "You are given an array of points in the X-Y plane `points` where `points[i] =\n[xi, yi]`.\n\nReturn the minimum area of any rectangle formed from these points, with sides\nnot necessarily parallel to the X and Y axes. If there is not any such\nrectangle, return `0`.\n\nAnswers within `10-5` of the actual answer will be accepted.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\nfrom math import sqrt\n\nclass Solution:\n def minAreaFreeRect(self, points: List[List[int]]) -> float:\n ans = math.inf\n centerToPoints = collections.defaultdict(list)\n\n for ax, ay in points:\n for bx, by in points:\n center = ((ax + bx) / 2, (ay + by) / 2)\n centerToPoints[center].append((ax, ay, bx, by))\n\n def dist(px: int, py: int, qx: int, qy: int) -> float:\n return (px - qx)**2 + (py - qy)**2\n\n for points in centerToPoints.values():\n for ax, ay, _, _ in points:\n for cx, cy, dx, dy in points:\n if (cx - ax) * (dx - ax) + (cy - ay) * (dy - ay) == 0:\n squaredArea = dist(ax, ay, cx, cy) * dist(ax, ay, dx, dy)\n if squaredArea > 0:\n ans = min(ans, squaredArea)\n\n return 0 if ans == math.inf else sqrt(ans)\n", "java_solution": "class Solution {\n public double minAreaFreeRect(int[][] points) {\n long ans = Long.MAX_VALUE;\n // For each A, B pair points, {hash(A, B): (ax, ay, bx, by)}.\n Map> centerToPoints = new HashMap<>();\n\n for (int[] A : points)\n for (int[] B : points) {\n int center = hash(A, B);\n if (centerToPoints.get(center) == null)\n centerToPoints.put(center, new ArrayList<>());\n centerToPoints.get(center).add(new int[] {A[0], A[1], B[0], B[1]});\n }\n\n // For all pair points \"that share the same center\".\n for (List pointPairs : centerToPoints.values())\n for (int[] ab : pointPairs)\n for (int[] cd : pointPairs) {\n final int ax = ab[0], ay = ab[1];\n final int cx = cd[0], cy = cd[1];\n final int dx = cd[2], dy = cd[3];\n // AC is perpendicular to AD.\n // AC dot AD = (cx - ax, cy - ay) dot (dx - ax, dy - ay) == 0.\n if ((cx - ax) * (dx - ax) + (cy - ay) * (dy - ay) == 0) {\n final long squaredArea = dist(ax, ay, cx, cy) * dist(ax, ay, dx, dy);\n if (squaredArea > 0)\n ans = Math.min(ans, squaredArea);\n }\n }\n\n return ans == Long.MAX_VALUE ? 0 : Math.sqrt(ans);\n }\n\n private int hash(int[] p, int[] q) {\n return ((p[0] + q[0]) << 16) + (p[1] + q[1]);\n }\n\n private long dist(long px, long py, long qx, long qy) {\n return (px - qx) * (px - qx) + (py - qy) * (py - qy);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n double minAreaFreeRect(vector>& points) {\n long ans = LONG_MAX;\n // For each A, B pair points, {hash(A, B): (ax, ay, bx, by)}.\n unordered_map>> centerToPoints;\n\n for (const vector& A : points)\n for (const vector& B : points) {\n const int center = hash(A, B);\n centerToPoints[center].emplace_back(A[0], A[1], B[0], B[1]);\n }\n\n // For all pair points \"that share the same center\".\n for (const auto& [_, points] : centerToPoints)\n for (const auto& [ax, ay, bx, by] : points)\n for (const auto& [cx, cy, dx, dy] : points)\n // AC is perpendicular to AD.\n // AC dot AD = (cx - ax, cy - ay) dot (dx - ax, dy - ay) == 0.\n if ((cx - ax) * (dx - ax) + (cy - ay) * (dy - ay) == 0) {\n const long squaredArea =\n dist(ax, ay, cx, cy) * dist(ax, ay, dx, dy);\n if (squaredArea > 0)\n ans = min(ans, squaredArea);\n }\n\n return ans == LONG_MAX ? 0 : sqrt(ans);\n }\n\n private:\n int hash(const vector& p, const vector& q) {\n return ((long)(p[0] + q[0]) << 16) + (p[1] + q[1]);\n }\n\n long dist(int px, int py, int qx, int qy) {\n return (px - qx) * (px - qx) + (py - qy) * (py - qy);\n }\n};\n"} +{"task_num": 990, "task_title": "Satisfiability of Equality Equations", "difficulty": 2, "func_name": "equationsPossible", "description": "You are given an array of strings `equations` that represent relationships\nbetween variables where each string `equations[i]` is of length `4` and takes\none of two different forms: `\"xi==yi\"` or `\"xi!=yi\"`.Here, `xi` and `yi` are\nlowercase letters (not necessarily different) that represent one-letter\nvariable names.\n\nReturn `true` if it is possible to assign integers to variable names so as to\nsatisfy all the given equations, or `false` otherwise.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n\n def union(self, u: int, v: int) -> None:\n self.id[self.find(u)] = self.find(v)\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def equationsPossible(self, equations: List[str]) -> bool:\n uf = UnionFind(26)\n\n for x, op, _, y in equations:\n if op == '=':\n uf.union(ord(x) - ord('a'), ord(y) - ord('a'))\n\n for x, op, _, y in equations:\n if op == '!':\n if uf.find(ord(x) - ord('a')) == uf.find(ord(y) - ord('a')):\n return False\n return True\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public void unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n public int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n\n private int[] id;\n private int[] rank;\n}\n\nclass Solution {\n public boolean equationsPossible(String[] equations) {\n UnionFind uf = new UnionFind(26);\n\n for (final String e : equations)\n if (e.charAt(1) == '=') {\n final int x = e.charAt(0) - 'a';\n final int y = e.charAt(3) - 'a';\n uf.unionByRank(x, y);\n }\n\n for (final String e : equations)\n if (e.charAt(1) == '!') {\n final int x = e.charAt(0) - 'a';\n final int y = e.charAt(3) - 'a';\n if (uf.find(x) == uf.find(y))\n return false;\n }\n\n return true;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n void union_(int u, int v) {\n id[find(u)] = find(v);\n }\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n\n private:\n vector id;\n};\n\nclass Solution {\n public:\n bool equationsPossible(vector& equations) {\n UnionFind uf(26);\n\n for (const string& e : equations)\n if (e[1] == '=') {\n const int x = e[0] - 'a';\n const int y = e[3] - 'a';\n uf.union_(x, y);\n }\n\n for (const string& e : equations)\n if (e[1] == '!') {\n const int x = e[0] - 'a';\n const int y = e[3] - 'a';\n if (uf.find(x) == uf.find(y))\n return false;\n }\n\n return true;\n }\n};\n"} +{"task_num": 999, "task_title": "Available Captures for Rook", "difficulty": 1, "func_name": "numRookCaptures", "description": "On an `8 x 8` chessboard, there is exactly one white rook `'R'` and some\nnumber of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.\n\nWhen the rook moves, it chooses one of four cardinal directions (north, east,\nsouth, or west), then moves in that direction until it chooses to stop,\nreaches the edge of the board, captures a black pawn, or is blocked by a white\nbishop. A rook is considered attacking a pawn if the rook can capture the pawn\non the rook's turn. The number of available captures for the white rook is the\nnumber of pawns that the rook is attacking.\n\nReturn the number of available captures for the white rook.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def numRookCaptures(self, board: List[List[str]]) -> int:\n ans = 0\n\n for i in range(8):\n for j in range(8):\n if board[i][j] == 'R':\n i0 = i\n j0 = j\n\n for d in [[1, 0], [0, 1], [-1, 0], [0, -1]]:\n i = i0 + d[0]\n j = j0 + d[1]\n while 0 <= i < 8 and 0 <= j < 8:\n if board[i][j] == 'p':\n ans += 1\n if board[i][j] != '.':\n break\n i += d[0]\n j += d[1]\n\n return ans\n", "java_solution": "class Solution {\n public int numRookCaptures(char[][] board) {\n int ans = 0;\n int i0 = 0;\n int j0 = 0;\n\n for (int i = 0; i < 8; ++i)\n for (int j = 0; j < 8; ++j)\n if (board[i][j] == 'R') {\n i0 = i;\n j0 = j;\n }\n\n for (int[] d : new int[][] {{1, 0}, {0, 1}, {-1, 0}, {0, -1}})\n for (int i = i0 + d[0], j = j0 + d[1]; 0 <= i && i < 8 && 0 <= j && j < 8;\n i += d[0], j += d[1]) {\n if (board[i][j] == 'p')\n ++ans;\n if (board[i][j] != '.')\n break;\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int numRookCaptures(vector>& board) {\n int ans = 0;\n int i0 = 0;\n int j0 = 0;\n\n for (int i = 0; i < 8; ++i)\n for (int j = 0; j < 8; ++j)\n if (board[i][j] == 'R') {\n i0 = i;\n j0 = j;\n }\n\n for (const vector& d :\n vector>({{1, 0}, {0, 1}, {-1, 0}, {0, -1}}))\n for (int i = i0 + d[0], j = j0 + d[1]; 0 <= i && i < 8 && 0 <= j && j < 8;\n i += d[0], j += d[1]) {\n if (board[i][j] == 'p')\n ++ans;\n if (board[i][j] != '.')\n break;\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1001, "task_title": "Grid Illumination", "difficulty": 3, "func_name": "gridIllumination", "description": "There is a 2D `grid` of size `n x n` where each cell of this grid has a lamp\nthat is initially turned off.\n\nYou are given a 2D array of lamp positions `lamps`, where `lamps[i] = [rowi,\ncoli]` indicates that the lamp at `grid[rowi][coli]` is turned on. Even if the\nsame lamp is listed more than once, it is turned on.\n\nWhen a lamp is turned on, it illuminates its cell and all other cells in the\nsame row, column, or diagonal.\n\nYou are also given another 2D array `queries`, where `queries[j] = [rowj,\ncolj]`. For the `jth` query, determine whether `grid[rowj][colj]` is\nilluminated or not. After answering the `jth` query, turn off the lamp at\n`grid[rowj][colj]` and its 8 adjacent lamps if they exist. A lamp is adjacent\nif its cell shares either a side or corner with `grid[rowj][colj]`.\n\nReturn an array of integers `ans`, where `ans[j]` should be `1` if the cell in\nthe `jth` query was illuminated, or `0` if the lamp was not.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:\n ans = []\n rows = collections.Counter()\n cols = collections.Counter()\n diag1 = collections.Counter()\n diag2 = collections.Counter()\n lampsSet = set()\n\n for i, j in lamps:\n if (i, j) not in lampsSet:\n lampsSet.add((i, j))\n rows[i] += 1\n cols[j] += 1\n diag1[i + j] += 1\n diag2[i - j] += 1\n\n for i, j in queries:\n if rows[i] or cols[j] or diag1[i + j] or diag2[i - j]:\n ans.append(1)\n for y in range(max(0, i - 1), min(n, i + 2)):\n for x in range(max(0, j - 1), min(n, j + 2)):\n if (y, x) in lampsSet:\n lampsSet.remove((y, x))\n rows[y] -= 1\n cols[x] -= 1\n diag1[y + x] -= 1\n diag2[y - x] -= 1\n else:\n ans.append(0)\n\n return ans\n", "java_solution": "class Solution {\n public int[] gridIllumination(int n, int[][] lamps, int[][] queries) {\n List ans = new ArrayList<>();\n Map rows = new HashMap<>();\n Map cols = new HashMap<>();\n Map diag1 = new HashMap<>();\n Map diag2 = new HashMap<>();\n Set lampsSet = new HashSet<>();\n\n for (int[] lamp : lamps) {\n final int i = lamp[0];\n final int j = lamp[1];\n if (lampsSet.add(hash(i, j))) {\n rows.merge(i, 1, Integer::sum);\n cols.merge(j, 1, Integer::sum);\n diag1.merge(i + j, 1, Integer::sum);\n diag2.merge(i - j, 1, Integer::sum);\n }\n }\n\n for (int[] query : queries) {\n final int i = query[0];\n final int j = query[1];\n if (rows.getOrDefault(i, 0) > 0 || cols.getOrDefault(j, 0) > 0 ||\n diag1.getOrDefault(i + j, 0) > 0 || diag2.getOrDefault(i - j, 0) > 0) {\n ans.add(1);\n for (int y = Math.max(0, i - 1); y < Math.min(n, i + 2); ++y)\n for (int x = Math.max(0, j - 1); x < Math.min(n, j + 2); ++x)\n if (lampsSet.remove(hash(y, x))) {\n rows.merge(y, 1, Integer::sum);\n cols.merge(x, 1, Integer::sum);\n diag1.merge(y + x, 1, Integer::sum);\n diag2.merge(y - x, 1, Integer::sum);\n }\n } else {\n ans.add(0);\n }\n }\n\n return ans.stream().mapToInt(Integer::intValue).toArray();\n }\n\n private long hash(int i, int j) {\n return ((long) i << 32) + j;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector gridIllumination(int n, vector>& lamps,\n vector>& queries) {\n vector ans;\n unordered_map rows;\n unordered_map cols;\n unordered_map diag1;\n unordered_map diag2;\n unordered_set, PairHash> lampsSet;\n\n for (const vector& lamp : lamps) {\n const int i = lamp[0];\n const int j = lamp[1];\n if (lampsSet.insert({i, j}).second) {\n ++rows[i];\n ++cols[j];\n ++diag1[i + j];\n ++diag2[i - j];\n }\n }\n\n for (const vector& query : queries) {\n const int i = query[0];\n const int j = query[1];\n if (rows[i] || cols[j] || diag1[i + j] || diag2[i - j]) {\n ans.push_back(1);\n for (int y = max(0, i - 1); y < min(n, i + 2); ++y)\n for (int x = max(0, j - 1); x < min(n, j + 2); ++x)\n if (lampsSet.erase({y, x})) {\n --rows[y];\n --cols[x];\n --diag1[y + x];\n --diag2[y - x];\n }\n } else {\n ans.push_back(0);\n }\n }\n\n return ans;\n }\n\n private:\n struct PairHash {\n size_t operator()(const pair& p) const {\n return p.first ^ p.second;\n }\n };\n};\n"} +{"task_num": 1093, "task_title": "Statistics from a Large Sample", "difficulty": 2, "func_name": "sampleStats", "description": "You are given a large sample of integers in the range `[0, 255]`. Since the\nsample is so large, it is represented by an array `count` where `count[k]` is\nthe number of times that `k` appears in the sample.\n\nCalculate the following statistics:\n\n* `minimum`: The minimum element in the sample.\n* `maximum`: The maximum element in the sample.\n* `mean`: The average of the sample, calculated as the total sum of all elements divided by the total number of elements.\n* `median`: \n* If the sample has an odd number of elements, then the `median` is the middle element once the sample is sorted.\n* If the sample has an even number of elements, then the `median` is the average of the two middle elements once the sample is sorted.\n* `mode`: The number that appears the most in the sample. It is guaranteed to be unique.\n\nReturn the statistics of the sample as an array of floating-point numbers\n`[minimum, maximum, mean, median, mode]`. Answers within `10-5` of the actual\nanswer will be accepted.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def sampleStats(self, count: List[int]) -> List[float]:\n minimum = next((i for i, num in enumerate(count) if num), None)\n maximum = next((i for i, num in reversed(list(enumerate(count))) if num), None)\n n = sum(count)\n mean = sum(i * c / n for i, c in enumerate(count))\n mode = count.index(max(count))\n\n numCount = 0\n leftMedian = 0\n for i, c in enumerate(count):\n numCount += c\n if numCount >= n / 2:\n leftMedian = i\n break\n\n numCount = 0\n rightMedian = 0\n for i, c in reversed(list(enumerate(count))):\n numCount += c\n if numCount >= n / 2:\n rightMedian = i\n break\n\n return [minimum, maximum, mean, (leftMedian + rightMedian) / 2, mode]\n", "java_solution": "class Solution {\n public double[] sampleStats(int[] count) {\n final int n = Arrays.stream(count).sum();\n return new double[] {\n getMinimum(count), //\n getMaximum(count), //\n getMean(count, n), //\n (getLeftMedian(count, n) + getRightMedian(count, n)) / 2.0, //\n getMode(count),\n };\n }\n\n private double getMinimum(int[] count) {\n for (int i = 0; i < count.length; ++i)\n if (count[i] > 0)\n return i;\n return -1;\n }\n\n private double getMaximum(int[] count) {\n for (int i = count.length - 1; i >= 0; --i)\n if (count[i] > 0)\n return i;\n return -1;\n }\n\n private double getMean(int[] count, double n) {\n double mean = 0;\n for (int i = 0; i < count.length; ++i)\n mean += ((long) i * (long) count[i]) / n;\n return mean;\n }\n\n private double getLeftMedian(int[] count, double n) {\n int numCount = 0;\n for (int i = 0; i < count.length; ++i) {\n numCount += count[i];\n if (numCount >= n / 2)\n return i;\n }\n return -1;\n }\n\n private double getRightMedian(int[] count, double n) {\n int numCount = 0;\n for (int i = count.length - 1; i >= 0; --i) {\n numCount += count[i];\n if (numCount >= n / 2)\n return i;\n }\n return -1;\n }\n\n private double getMode(int[] count) {\n int mode = -1;\n int maxCount = 0;\n for (int i = 0; i < count.length; ++i)\n if (count[i] > maxCount) {\n maxCount = count[i];\n mode = i;\n }\n return mode;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector sampleStats(vector& count) {\n const int n = accumulate(count.begin(), count.end(), 0);\n const double mode = ranges::max_element(count) - count.begin();\n return {\n getMinimum(count),\n getMaximum(count),\n getMean(count, n),\n (getLeftMedian(count, n) + getRightMedian(count, n)) / 2.0,\n mode,\n };\n }\n\n private:\n double getMinimum(const vector& count) {\n for (int i = 0; i < count.size(); ++i)\n if (count[i])\n return i;\n return -1;\n }\n\n double getMaximum(const vector& count) {\n for (int i = count.size() - 1; i >= 0; --i)\n if (count[i])\n return i;\n return -1;\n }\n\n double getMean(const vector& count, double n) {\n double mean = 0;\n for (long i = 0; i < count.size(); ++i)\n mean += (i * count[i]) / n;\n return mean;\n }\n\n double getLeftMedian(const vector& count, double n) {\n int numCount = 0;\n for (int i = 0; i < count.size(); ++i) {\n numCount += count[i];\n if (numCount >= n / 2)\n return i;\n }\n return -1;\n }\n\n double getRightMedian(const vector& count, double n) {\n int numCount = 0;\n for (int i = count.size() - 1; i >= 0; --i) {\n numCount += count[i];\n if (numCount >= n / 2)\n return i;\n }\n return -1;\n }\n};\n"} +{"task_num": 1129, "task_title": "Shortest Path with Alternating Colors", "difficulty": 2, "func_name": "shortestAlternatingPaths", "description": "You are given an integer `n`, the number of nodes in a directed graph where\nthe nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this\ngraph, and there could be self-edges and parallel edges.\n\nYou are given two arrays `redEdges` and `blueEdges` where:\n\n* `redEdges[i] = [ai, bi]` indicates that there is a directed red edge from node `ai` to node `bi` in the graph, and\n* `blueEdges[j] = [uj, vj]` indicates that there is a directed blue edge from node `uj` to node `vj` in the graph.\n\nReturn an array `answer` of length `n`, where each `answer[x]` is the length\nof the shortest path from node `0` to node `x` such that the edge colors\nalternate along the path, or `-1` if such a path does not exist.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nfrom enum import Enum\n\n\nclass Color(Enum):\n kInit = 0\n kRed = 1\n kBlue = 2\n\n\nclass Solution:\n def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:\n ans = [-1] * n\n graph = [[] for _ in range(n)]\n q = collections.deque([(0, Color.kInit)])\n\n for u, v in redEdges:\n graph[u].append((v, Color.kRed))\n\n for u, v in blueEdges:\n graph[u].append((v, Color.kBlue))\n\n step = 0\n while q:\n for _ in range(len(q)):\n u, prevColor = q.popleft()\n if ans[u] == -1:\n ans[u] = step\n for i, (v, edgeColor) in enumerate(graph[u]):\n if v == -1 or edgeColor == prevColor:\n continue\n q.append((v, edgeColor))\n graph[u][i] = (-1, edgeColor)\n step += 1\n\n return ans\n", "java_solution": "enum Color { INIT, RED, BLUE }\n\nclass Solution {\n public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) {\n int[] ans = new int[n];\n Arrays.fill(ans, -1);\n // graph[u] := [(v, edgeColor)]\n List>[] graph = new List[n];\n // [(u, prevColor)]\n Queue> q = new ArrayDeque<>(List.of(new Pair<>(0, Color.INIT)));\n Arrays.setAll(graph, i -> new ArrayList<>());\n\n for (int[] edge : redEdges) {\n final int u = edge[0];\n final int v = edge[1];\n graph[u].add(new Pair<>(v, Color.RED));\n }\n\n for (int[] edge : blueEdges) {\n final int u = edge[0];\n final int v = edge[1];\n graph[u].add(new Pair<>(v, Color.BLUE));\n }\n\n for (int step = 0; !q.isEmpty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n final int u = q.peek().getKey();\n Color prevColor = q.poll().getValue();\n ans[u] = ans[u] == -1 ? step : ans[u];\n for (int i = 0; i < graph[u].size(); ++i) {\n Pair node = graph[u].get(i);\n final int v = node.getKey();\n Color edgeColor = node.getValue();\n if (v == -1 || edgeColor == prevColor)\n continue;\n q.add(new Pair<>(v, edgeColor));\n // Mark (u, v) as used.\n graph[u].set(i, new Pair<>(-1, edgeColor));\n }\n }\n\n return ans;\n }\n}\n", "cpp_solution": "enum class Color { kInit, kRed, kBlue };\n\nclass Solution {\n public:\n vector shortestAlternatingPaths(int n, vector>& redEdges,\n vector>& blueEdges) {\n vector ans(n, -1);\n vector>> graph(n); // graph[u] := [(v, edgeColor)]\n queue> q{{{0, Color::kInit}}}; // [(u, prevColor)]\n\n for (const vector& edge : redEdges) {\n const int u = edge[0];\n const int v = edge[1];\n graph[u].emplace_back(v, Color::kRed);\n }\n\n for (const vector& edge : blueEdges) {\n const int u = edge[0];\n const int v = edge[1];\n graph[u].emplace_back(v, Color::kBlue);\n }\n\n for (int step = 0; !q.empty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n const auto [u, prevColor] = q.front();\n q.pop();\n ans[u] = ans[u] == -1 ? step : ans[u];\n for (auto& [v, edgeColor] : graph[u]) {\n if (v == -1 || edgeColor == prevColor)\n continue;\n q.emplace(v, edgeColor);\n v = -1; // Mark (u, v) as used.\n }\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1139, "task_title": "Largest 1-Bordered Square", "difficulty": 2, "func_name": "largest1BorderedSquare", "description": "Given a 2D `grid` of `0`s and `1`s, return the number of elements in the\nlargest square subgrid that has all `1`s on its border, or `0` if such a\nsubgrid doesn't exist in the `grid`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n\n leftOnes = [[0] * n for _ in range(m)]\n topOnes = [[0] * n for _ in range(m)]\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n if j==0:\n leftOnes[i][j]=1\n else:\n leftOnes[i][j]=1+leftOnes[i][j-1]\n if i==0:\n topOnes[i][j]=1\n else:\n topOnes[i][j]=1+topOnes[i-1][j]\n\n for sz in range(min(m, n), 0, -1):\n for i in range(m - sz + 1):\n for j in range(n - sz + 1):\n x = i + sz - 1\n y = j + sz - 1\n if min(leftOnes[i][y], leftOnes[x][y], topOnes[x][j], topOnes[x][y]) >= sz:\n return sz * sz\n\n return 0\n", "java_solution": "class Solution {\n public int largest1BorderedSquare(int[][] grid) {\n final int m = grid.length;\n final int n = grid[0].length;\n\n // leftOnes[i][j] := consecutive 1s in the left of grid[i][j]\n int[][] leftOnes = new int[m][n];\n // topOnes[i][j] := consecutive 1s in the top of grid[i][j]\n int[][] topOnes = new int[m][n];\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 1) {\n leftOnes[i][j] = j == 0 ? 1 : 1 + leftOnes[i][j - 1];\n topOnes[i][j] = i == 0 ? 1 : 1 + topOnes[i - 1][j];\n }\n\n for (int sz = Math.min(m, n); sz > 0; --sz)\n for (int i = 0; i + sz - 1 < m; ++i)\n for (int j = 0; j + sz - 1 < n; ++j) {\n final int x = i + sz - 1;\n final int y = j + sz - 1;\n // If grid[i..x][j..y] has all 1s on its border.\n if (Math.min(leftOnes[i][y], leftOnes[x][y]) >= sz &&\n Math.min(topOnes[x][j], topOnes[x][y]) >= sz)\n return sz * sz;\n }\n\n return 0;\n }\n};\n", "cpp_solution": "class Solution {\n public:\n int largest1BorderedSquare(vector>& grid) {\n const int m = grid.size();\n const int n = grid[0].size();\n\n // leftOnes[i][j] := consecutive 1s in the left of grid[i][j]\n vector> leftOnes(m, vector(n));\n // topOnes[i][j] := consecutive 1s in the top of grid[i][j]\n vector> topOnes(m, vector(n));\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 1) {\n leftOnes[i][j] = j == 0 ? 1 : 1 + leftOnes[i][j - 1];\n topOnes[i][j] = i == 0 ? 1 : 1 + topOnes[i - 1][j];\n }\n\n for (int sz = min(m, n); sz > 0; --sz)\n for (int i = 0; i + sz - 1 < m; ++i)\n for (int j = 0; j + sz - 1 < n; ++j) {\n const int x = i + sz - 1;\n const int y = j + sz - 1;\n // If grid[i..x][j..y] has all 1s on its border.\n if (min(leftOnes[i][y], leftOnes[x][y]) >= sz &&\n min(topOnes[x][j], topOnes[x][y]) >= sz)\n return sz * sz;\n }\n\n return 0;\n }\n};\n"} +{"task_num": 1162, "task_title": "As Far from Land as Possible", "difficulty": 2, "func_name": "maxDistance", "description": "Given an `n x n` `grid` containing only values `0` and `1`, where `0`\nrepresents water and `1` represents land, find a water cell such that its\ndistance to the nearest land cell is maximized, and return the distance. If no\nland or water exists in the grid, return `-1`.\n\nThe distance used in this problem is the Manhattan distance: the distance\nbetween two cells `(x0, y0)` and `(x1, y1)` is `|x0 - x1| + |y0 - y1|`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def maxDistance(self, grid: List[List[int]]) -> int:\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(grid)\n n = len(grid[0])\n q = collections.deque()\n water = 0\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n water += 1\n else:\n q.append((i, j))\n\n if water == 0 or water == m * n:\n return -1\n\n ans = 0\n d = 0\n\n while q:\n for _ in range(len(q)):\n i, j = q.popleft()\n ans = d\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if grid[x][y] > 0:\n continue\n q.append((x, y))\n grid[x][y] = 2\n d += 1\n\n return ans\n", "java_solution": "class Solution {\n public int maxDistance(int[][] grid) {\n final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n final int m = grid.length;\n final int n = grid[0].length;\n Queue> q = new ArrayDeque<>();\n int water = 0;\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 0)\n ++water;\n else\n q.offer(new Pair<>(i, j));\n\n if (water == 0 || water == m * n)\n return -1;\n\n int ans = 0;\n\n for (int d = 0; !q.isEmpty(); ++d)\n for (int sz = q.size(); sz > 0; --sz) {\n Pair pair = q.poll();\n final int i = pair.getKey();\n final int j = pair.getValue();\n ans = d;\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (grid[x][y] > 0)\n continue;\n q.offer(new Pair<>(x, y));\n grid[x][y] = 2; // Mark as visited.\n }\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int maxDistance(vector>& grid) {\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n const int m = grid.size();\n const int n = grid[0].size();\n queue> q;\n int water = 0;\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 0)\n ++water;\n else\n q.emplace(i, j);\n\n if (water == 0 || water == m * n)\n return -1;\n\n int ans = 0;\n\n for (int d = 0; !q.empty(); ++d)\n for (int sz = q.size(); sz > 0; --sz) {\n const auto [i, j] = q.front();\n q.pop();\n ans = d;\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (grid[x][y] > 0)\n continue;\n q.emplace(x, y);\n grid[x][y] = 2; // Mark as visited.\n }\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1202, "task_title": "Smallest String With Swaps", "difficulty": 2, "func_name": "smallestStringWithSwaps", "description": "You are given a string `s`, and an array of pairs of indices in the string\n`pairs` where `pairs[i] = [a, b]` indicates 2 indices(0-indexed) of the\nstring.\n\nYou can swap the characters at any pair of indices in the given `pairs` any\nnumber of times.\n\nReturn the lexicographically smallest string that `s` can be changed to after\nusing the swaps.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self.find(u)\n j = self.find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:\n ans = ''\n uf = UnionFind(len(s))\n map = collections.defaultdict(list)\n\n for a, b in pairs:\n uf.unionByRank(a, b)\n\n for i, c in enumerate(s):\n map[uf.find(i)].append(c)\n\n for key in map.keys():\n map[key].sort(reverse=True)\n\n for i in range(len(s)):\n ans += map[uf.find(i)].pop()\n\n return ans\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public void unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n public int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n\n private int[] id;\n private int[] rank;\n}\n\nclass Solution {\n public String smallestStringWithSwaps(String s, List> pairs) {\n StringBuilder sb = new StringBuilder();\n UnionFind uf = new UnionFind(s.length());\n Map> indexToLetters = new HashMap<>();\n\n for (List pair : pairs) {\n final int a = pair.get(0);\n final int b = pair.get(1);\n uf.unionByRank(a, b);\n }\n\n for (int i = 0; i < s.length(); ++i)\n indexToLetters.computeIfAbsent(uf.find(i), k -> new PriorityQueue<>()).offer(s.charAt(i));\n\n for (int i = 0; i < s.length(); ++i)\n sb.append(indexToLetters.get(uf.find(i)).poll());\n\n return sb.toString();\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n), rank(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n void unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n\n private:\n vector id;\n vector rank;\n};\n\nclass Solution {\n public:\n string smallestStringWithSwaps(string s, vector>& pairs) {\n string ans;\n UnionFind uf(s.length());\n unordered_map, greater<>>>\n indexToLetters;\n\n for (const vector& pair : pairs) {\n const int a = pair[0];\n const int b = pair[1];\n uf.unionByRank(a, b);\n }\n\n for (int i = 0; i < s.length(); ++i)\n indexToLetters[uf.find(i)].push(s[i]);\n\n for (int i = 0; i < s.length(); ++i)\n ans += indexToLetters[uf.find(i)].top(), indexToLetters[uf.find(i)].pop();\n\n return ans;\n }\n};\n"} +{"task_num": 1210, "task_title": "Minimum Moves to Reach Target with Rotations", "difficulty": 3, "func_name": "minimumMoves", "description": "In an `n*n` grid, there is a snake that spans 2 cells and starts moving from\nthe top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells\nrepresented by zeros and blocked cells represented by ones. The snake wants to\nreach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.\n\nIn one move the snake can:\n\n* Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.\n* Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.\n* Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from `(r, c)` and `(r, c+1)` to `(r, c)` and `(r+1, c)`. \n\n* Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from `(r, c)` and `(r+1, c)` to `(r, c)` and `(r, c+1)`. \n\nReturn the minimum number of moves to reach the target.\n\nIf there is no way to reach the target, return `-1`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nfrom enum import IntEnum\n\n\nclass Pos(IntEnum):\n kHorizontal = 0\n kVertical = 1\n\n\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n n = len(grid)\n ans = 0\n\n q = collections.deque([(0, 0, Pos.kHorizontal)])\n seen = {(0, 0, Pos.kHorizontal)}\n\n def canMoveRight(x: int, y: int, pos: Pos) -> bool:\n if pos == Pos.kHorizontal:\n return y + 2 < n and not grid[x][y + 2]\n return y + 1 < n and not grid[x][y + 1] and not grid[x + 1][y + 1]\n\n def canMoveDown(x: int, y: int, pos: Pos) -> bool:\n if pos == Pos.kVertical:\n return x + 2 < n and not grid[x + 2][y]\n return x + 1 < n and not grid[x + 1][y] and not grid[x + 1][y + 1]\n\n def canRotateClockwise(x: int, y: int, pos: Pos) -> bool:\n return pos == Pos.kHorizontal and x + 1 < n and \\\n not grid[x + 1][y + 1] and not grid[x + 1][y]\n\n def canRotateCounterclockwise(x: int, y: int, pos: Pos) -> bool:\n return pos == Pos.kVertical and y + 1 < n and \\\n not grid[x + 1][y + 1] and not grid[x][y + 1]\n\n while q:\n for _ in range(len(q)):\n x, y, pos = q.popleft()\n if x == n - 1 and y == n - 2 and pos == Pos.kHorizontal:\n return ans\n if canMoveRight(x, y, pos) and (x, y + 1, pos) not in seen:\n q.append((x, y + 1, pos))\n seen.add((x, y + 1, pos))\n if canMoveDown(x, y, pos) and (x + 1, y, pos) not in seen:\n q.append((x + 1, y, pos))\n seen.add((x + 1, y, pos))\n newPos = Pos.kVertical if pos == Pos.kHorizontal else Pos.kHorizontal\n if (canRotateClockwise(x, y, pos) or canRotateCounterclockwise(x, y, pos)) and (x, y, newPos) not in seen:\n q.append((x, y, newPos))\n seen.add((x, y, newPos))\n ans += 1\n\n return -1\n", "java_solution": "enum Pos { HORIZONTAL, VERTICAL }\n\nclass Solution {\n public int minimumMoves(int[][] grid) {\n record T(int x, int y, Pos pos) {}\n final int n = grid.length;\n Queue q = new ArrayDeque<>(List.of(new T(0, 0, Pos.HORIZONTAL)));\n boolean[][][] seen = new boolean[n][n][2];\n seen[0][0][Pos.HORIZONTAL.ordinal()] = true;\n\n for (int step = 0; !q.isEmpty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n final int x = q.peek().x;\n final int y = q.peek().y;\n final Pos pos = q.poll().pos;\n if (x == n - 1 && y == n - 2 && pos == Pos.HORIZONTAL)\n return step;\n if (canMoveRight(grid, x, y, pos) && !seen[x][y + 1][pos.ordinal()]) {\n q.offer(new T(x, y + 1, pos));\n seen[x][y + 1][pos.ordinal()] = true;\n }\n if (canMoveDown(grid, x, y, pos) && !seen[x + 1][y][pos.ordinal()]) {\n q.offer(new T(x + 1, y, pos));\n seen[x + 1][y][pos.ordinal()] = true;\n }\n final Pos newPos = pos == Pos.HORIZONTAL ? Pos.VERTICAL : Pos.HORIZONTAL;\n if ((canRotateClockwise(grid, x, y, pos) || canRotateCounterclockwise(grid, x, y, pos)) &&\n !seen[x][y][newPos.ordinal()]) {\n q.offer(new T(x, y, newPos));\n seen[x][y][newPos.ordinal()] = true;\n }\n }\n\n return -1;\n }\n\n private boolean canMoveRight(int[][] grid, int x, int y, Pos pos) {\n if (pos == Pos.HORIZONTAL)\n return y + 2 < grid.length && grid[x][y + 2] == 0;\n return y + 1 < grid.length && grid[x][y + 1] == 0 && grid[x + 1][y + 1] == 0;\n }\n\n private boolean canMoveDown(int[][] grid, int x, int y, Pos pos) {\n if (pos == Pos.VERTICAL)\n return x + 2 < grid.length && grid[x + 2][y] == 0;\n return x + 1 < grid.length && grid[x + 1][y] == 0 && grid[x + 1][y + 1] == 0;\n }\n\n private boolean canRotateClockwise(int[][] grid, int x, int y, Pos pos) {\n return pos == Pos.HORIZONTAL && x + 1 < grid.length && grid[x + 1][y + 1] == 0 &&\n grid[x + 1][y] == 0;\n }\n\n private boolean canRotateCounterclockwise(int[][] grid, int x, int y, Pos pos) {\n return pos == Pos.VERTICAL && y + 1 < grid.length && grid[x + 1][y + 1] == 0 &&\n grid[x][y + 1] == 0;\n }\n}\n", "cpp_solution": "enum class Pos { kHorizontal, kVertical };\n\nclass Solution {\n public:\n int minimumMoves(vector>& grid) {\n const int n = grid.size();\n queue> q{{{0, 0, Pos::kHorizontal}}};\n vector>> seen(n,\n vector>(n, vector(2)));\n seen[0][0][static_cast(Pos::kHorizontal)] = true;\n\n auto canMoveRight = [&](int x, int y, Pos pos) -> bool {\n if (pos == Pos::kHorizontal)\n return y + 2 < n && !grid[x][y + 2];\n return y + 1 < n && !grid[x][y + 1] && !grid[x + 1][y + 1];\n };\n\n auto canMoveDown = [&](int x, int y, Pos pos) -> bool {\n if (pos == Pos::kVertical)\n return x + 2 < n && !grid[x + 2][y];\n return x + 1 < n && !grid[x + 1][y] && !grid[x + 1][y + 1];\n };\n\n auto canRotateClockwise = [&](int x, int y, Pos pos) -> bool {\n return pos == Pos::kHorizontal && x + 1 < n && !grid[x + 1][y + 1] &&\n !grid[x + 1][y];\n };\n\n auto canRotateCounterclockwise = [&](int x, int y, Pos pos) -> bool {\n return pos == Pos::kVertical && y + 1 < n && !grid[x + 1][y + 1] &&\n !grid[x][y + 1];\n };\n\n for (int step = 0; !q.empty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n const auto [x, y, pos] = q.front();\n q.pop();\n if (x == n - 1 && y == n - 2 && pos == Pos::kHorizontal)\n return step;\n if (canMoveRight(x, y, pos) && !seen[x][y + 1][static_cast(pos)]) {\n q.emplace(x, y + 1, pos);\n seen[x][y + 1][static_cast(pos)] = true;\n }\n if (canMoveDown(x, y, pos) && !seen[x + 1][y][static_cast(pos)]) {\n q.emplace(x + 1, y, pos);\n seen[x + 1][y][static_cast(pos)] = true;\n }\n const Pos newPos =\n pos == Pos::kHorizontal ? Pos::kVertical : Pos::kHorizontal;\n if ((canRotateClockwise(x, y, pos) ||\n canRotateCounterclockwise(x, y, pos)) &&\n !seen[x][y][static_cast(newPos)]) {\n q.emplace(x, y, newPos);\n seen[x][y][static_cast(newPos)] = true;\n }\n }\n\n return -1;\n }\n};\n"} +{"task_num": 1253, "task_title": "Reconstruct a 2-Row Binary Matrix", "difficulty": 2, "func_name": "reconstructMatrix", "description": "Given the following details of a matrix with `n` columns and `2` rows :\n\n* The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`.\n* The sum of elements of the 0-th(upper) row is given as `upper`.\n* The sum of elements of the 1-st(lower) row is given as `lower`.\n* The sum of elements in the i-th column(0-indexed) is `colsum[i]`, where `colsum` is given as an integer array with length `n`.\n\nYour task is to reconstruct the matrix with `upper`, `lower` and `colsum`.\n\nReturn it as a 2-D integer array.\n\nIf there are more than one valid solution, any of them will be accepted.\n\nIf no valid solution exists, return an empty 2-D array.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n if upper + lower != sum(colsum):\n return []\n if min(upper, lower) < colsum.count(2):\n return []\n\n ans = [[0] * len(colsum) for _ in range(2)]\n\n for j, c in enumerate(colsum):\n if c == 2:\n ans[0][j] = 1\n ans[1][j] = 1\n upper -= 1\n lower -= 1\n\n for j, c in enumerate(colsum):\n if c == 1 and upper > 0:\n ans[0][j] = 1\n c -= 1\n upper -= 1\n if c == 1 and lower > 0:\n ans[1][j] = 1\n lower -= 1\n\n return ans\n", "java_solution": "class Solution {\n public List> reconstructMatrix(int upper, int lower, int[] colsum) {\n if (upper + lower != Arrays.stream(colsum).sum())\n return new ArrayList<>();\n\n int count = 0;\n for (int c : colsum)\n if (c == 2)\n ++count;\n\n if (Math.min(upper, lower) < count)\n return new ArrayList<>();\n\n int[][] ans = new int[2][colsum.length];\n\n for (int j = 0; j < colsum.length; ++j)\n if (colsum[j] == 2) {\n ans[0][j] = 1;\n ans[1][j] = 1;\n --upper;\n --lower;\n }\n\n for (int j = 0; j < colsum.length; ++j) {\n if (colsum[j] == 1 && upper > 0) {\n ans[0][j] = 1;\n --colsum[j];\n --upper;\n }\n\n if (colsum[j] == 1 && lower > 0) {\n ans[1][j] = 1;\n --lower;\n }\n }\n\n return new ArrayList(Arrays.asList(ans[0], ans[1]));\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector> reconstructMatrix(int upper, int lower,\n vector& colsum) {\n if (upper + lower != accumulate(colsum.begin(), colsum.end(), 0))\n return {};\n if (min(upper, lower) <\n ranges::count_if(colsum, [](int c) { return c == 2; }))\n return {};\n\n vector> ans(2, vector(colsum.size()));\n\n for (int j = 0; j < colsum.size(); ++j)\n if (colsum[j] == 2) {\n ans[0][j] = 1;\n ans[1][j] = 1;\n --upper;\n --lower;\n }\n\n for (int j = 0; j < colsum.size(); ++j) {\n if (colsum[j] == 1 && upper > 0) {\n ans[0][j] = 1;\n --colsum[j];\n --upper;\n }\n\n if (colsum[j] == 1 && lower > 0) {\n ans[1][j] = 1;\n --lower;\n }\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1254, "task_title": "Number of Closed Islands", "difficulty": 2, "func_name": "closedIsland", "description": "Given a 2D `grid` consists of `0s` (land) and `1s` (water). An island is a\nmaximal 4-directionally connected group of `0s` and a closed island is an\nisland totally (all left, top, right, bottom) surrounded by `1s.`\n\nReturn the number of closed islands.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n\n def dfs(i: int, j: int) -> None:\n if i < 0 or i == m or j < 0 or j == n:\n return\n if grid[i][j] == 1:\n return\n\n grid[i][j] = 1\n dfs(i + 1, j)\n dfs(i - 1, j)\n dfs(i, j + 1)\n dfs(i, j - 1)\n\n for i in range(m):\n for j in range(n):\n if i * j == 0 or i == m - 1 or j == n - 1:\n if grid[i][j] == 0:\n dfs(i, j)\n\n ans = 0\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n dfs(i, j)\n ans += 1\n\n return ans\n", "java_solution": "class Solution {\n public int closedIsland(int[][] grid) {\n final int m = grid.length;\n final int n = grid[0].length;\n\n // Remove the lands connected to the edge.\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (i * j == 0 || i == m - 1 || j == n - 1)\n if (grid[i][j] == 0)\n dfs(grid, i, j);\n\n int ans = 0;\n\n // Reduce to 200. Number of Islands\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 0) {\n dfs(grid, i, j);\n ++ans;\n }\n\n return ans;\n }\n\n private void dfs(int[][] grid, int i, int j) {\n if (i < 0 || i == grid.length || j < 0 || j == grid[0].length)\n return;\n if (grid[i][j] == 1)\n return;\n grid[i][j] = 1;\n dfs(grid, i + 1, j);\n dfs(grid, i - 1, j);\n dfs(grid, i, j + 1);\n dfs(grid, i, j - 1);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int closedIsland(vector>& grid) {\n const int m = grid.size();\n const int n = grid[0].size();\n\n // Remove the lands connected to the edge.\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (i * j == 0 || i == m - 1 || j == n - 1)\n if (grid[i][j] == 0)\n dfs(grid, i, j);\n\n int ans = 0;\n\n // Reduce to 200. Number of Islands\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 0) {\n dfs(grid, i, j);\n ++ans;\n }\n\n return ans;\n }\n\n private:\n void dfs(vector>& grid, int i, int j) {\n if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size())\n return;\n if (grid[i][j] == 1)\n return;\n grid[i][j] = 1;\n dfs(grid, i + 1, j);\n dfs(grid, i - 1, j);\n dfs(grid, i, j + 1);\n dfs(grid, i, j - 1);\n };\n};\n"} +{"task_num": 1263, "task_title": "Minimum Moves to Move a Box to Their Target Location", "difficulty": 3, "func_name": "minPushBox", "description": "A storekeeper is a game in which the player pushes boxes around in a warehouse\ntrying to get them to target locations.\n\nThe game is represented by an `m x n` grid of characters `grid` where each\nelement is a wall, floor, or box.\n\nYour task is to move the box `'B'` to the target position `'T'` under the\nfollowing rules:\n\n* The character `'S'` represents the player. The player can move up, down, left, right in `grid` if it is a floor (empty cell).\n* The character `'.'` represents the floor which means a free cell to walk.\n* The character `'#'` represents the wall which means an obstacle (impossible to walk there).\n* There is only one box `'B'` and one target cell `'T'` in the `grid`.\n* The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push.\n* The player cannot walk through the box.\n\nReturn the minimum number of pushes to move the box to the target. If there is\nno way to reach the target, return `-1`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\nfrom collections import deque\n\nclass Solution:\n def minPushBox(self, grid: List[List[str]]) -> int:\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == \"T\":\n target = (i,j)\n if grid[i][j] == \"B\":\n box = (i,j)\n if grid[i][j] == \"S\":\n person = (i,j)\n\n def valid(x,y):\n return 0<=x q = new ArrayDeque<>(List.of(new T(box[0], box[1], player[0], player[1])));\n boolean[][][][] seen = new boolean[m][n][m][n];\n seen[box[0]][box[1]][player[0]][player[1]] = true;\n\n for (int step = 0; !q.isEmpty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n final int boxX = q.peek().boxX;\n final int boxY = q.peek().boxY;\n final int playerX = q.peek().playerX;\n final int playerY = q.poll().playerY;\n if (boxX == target[0] && boxY == target[1])\n return step;\n for (int k = 0; k < 4; ++k) {\n final int nextBoxX = boxX + DIRS[k][0];\n final int nextBoxY = boxY + DIRS[k][1];\n if (isInvalid(grid, nextBoxX, nextBoxY))\n continue;\n if (seen[nextBoxX][nextBoxY][boxX][boxY])\n continue;\n final int fromX = boxX + DIRS[(k + 2) % 4][0];\n final int fromY = boxY + DIRS[(k + 2) % 4][1];\n if (isInvalid(grid, fromX, fromY))\n continue;\n if (canGoTo(grid, playerX, playerY, fromX, fromY, boxX, boxY)) {\n seen[nextBoxX][nextBoxY][boxX][boxY] = true;\n q.offer(new T(nextBoxX, nextBoxY, boxX, boxY));\n }\n }\n }\n\n return -1;\n }\n\n private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n // Returns true if (playerX, playerY) can go to (fromX, fromY).\n private boolean canGoTo(char[][] grid, int playerX, int playerY, int fromX, int fromY, int boxX,\n int boxY) {\n Queue> q = new ArrayDeque<>(List.of(new Pair<>(playerX, playerY)));\n boolean[][] seen = new boolean[grid.length][grid[0].length];\n seen[playerX][playerY] = true;\n\n while (!q.isEmpty()) {\n final int i = q.peek().getKey();\n final int j = q.poll().getValue();\n if (i == fromX && j == fromY)\n return true;\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (isInvalid(grid, x, y))\n continue;\n if (seen[x][y])\n continue;\n if (x == boxX && y == boxY)\n continue;\n q.offer(new Pair<>(x, y));\n seen[x][y] = true;\n }\n }\n\n return false;\n }\n\n private boolean isInvalid(char[][] grid, int playerX, int playerY) {\n return playerX < 0 || playerX == grid.length || playerY < 0 || playerY == grid[0].length ||\n grid[playerX][playerY] == '#';\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minPushBox(vector>& grid) {\n const int m = grid.size();\n const int n = grid[0].size();\n vector box;\n vector player;\n vector target;\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 'B')\n box = {i, j};\n else if (grid[i][j] == 'S')\n player = {i, j};\n else if (grid[i][j] == 'T')\n target = {i, j};\n\n // (boxX, boxY, playerX, playerY)\n queue> q{\n {{box[0], box[1], player[0], player[1]}}};\n vector>>> seen(\n m, vector>>(\n n, vector>(m, vector(n))));\n seen[box[0]][box[1]][player[0]][player[1]] = true;\n\n for (int step = 0; !q.empty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n const auto [boxX, boxY, playerX, playerY] = q.front();\n q.pop();\n if (boxX == target[0] && boxY == target[1])\n return step;\n for (int k = 0; k < 4; ++k) {\n const int nextBoxX = boxX + kDirs[k % 4][0];\n const int nextBoxY = boxY + kDirs[k % 4][1];\n if (isInvalid(grid, nextBoxX, nextBoxY))\n continue;\n if (seen[nextBoxX][nextBoxY][boxX][boxY])\n continue;\n const int fromX = boxX + kDirs[(k + 2) % 4][0];\n const int fromY = boxY + kDirs[(k + 2) % 4][1];\n if (isInvalid(grid, fromX, fromY))\n continue;\n if (canGoTo(grid, playerX, playerY, fromX, fromY, boxX, boxY)) {\n seen[nextBoxX][nextBoxY][boxX][boxY] = true;\n q.emplace(nextBoxX, nextBoxY, boxX, boxY);\n }\n }\n }\n\n return -1;\n }\n\n private:\n static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n // Returns true if (playerX, playerY) can go to (fromX, fromY).\n bool canGoTo(const vector>& grid, int playerX, int playerY,\n int fromX, int fromY, int boxX, int boxY) {\n queue> q{{{playerX, playerY}}};\n vector> seen(grid.size(), vector(grid[0].size()));\n seen[playerX][playerY] = true;\n\n while (!q.empty()) {\n const auto [i, j] = q.front();\n q.pop();\n if (i == fromX && j == fromY)\n return true;\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (isInvalid(grid, x, y))\n continue;\n if (seen[x][y])\n continue;\n if (x == boxX && y == boxY)\n continue;\n q.emplace(x, y);\n seen[x][y] = true;\n }\n }\n\n return false;\n }\n\n bool isInvalid(const vector>& grid, int playerX, int playerY) {\n return playerX < 0 || playerX == grid.size() || playerY < 0 ||\n playerY == grid[0].size() || grid[playerX][playerY] == '#';\n }\n};\n"} +{"task_num": 1267, "task_title": "Count Servers that Communicate", "difficulty": 2, "func_name": "countServers", "description": "You are given a map of a server center, represented as a `m * n` integer\nmatrix `grid`, where 1 means that on that cell there is a server and 0 means\nthat it is no server. Two servers are said to communicate if they are on the\nsame row or on the same column. \n\nReturn the number of servers that communicate with any other server.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def countServers(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n ans = 0\n rows = [0] * m\n cols = [0] * n\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n rows[i] += 1\n cols[j] += 1\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1 and (rows[i] > 1 or cols[j] > 1):\n ans += 1\n\n return ans\n", "java_solution": "class Solution {\n public int countServers(int[][] grid) {\n final int m = grid.length;\n final int n = grid[0].length;\n int ans = 0;\n int[] rows = new int[m];\n int[] cols = new int[n];\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 1) {\n ++rows[i];\n ++cols[j];\n }\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 1 && (rows[i] > 1 || cols[j] > 1))\n ++ans;\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int countServers(vector>& grid) {\n const int m = grid.size();\n const int n = grid[0].size();\n int ans = 0;\n vector rows(m);\n vector cols(n);\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 1) {\n ++rows[i];\n ++cols[j];\n }\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 1 && (rows[i] > 1 || cols[j] > 1))\n ++ans;\n\n return ans;\n }\n};\n"} +{"task_num": 1284, "task_title": "Minimum Number of Flips to Convert Binary Matrix to Zero Matrix", "difficulty": 3, "func_name": "minFlips", "description": "Given a `m x n` binary matrix `mat`. In one step, you can choose one cell and\nflip it and all the four neighbors of it if they exist (Flip is changing `1`\nto `0` and `0` to `1`). A pair of cells are called neighbors if they share one\nedge.\n\nReturn the minimum number of steps required to convert `mat` to a zero matrix\nor `-1` if you cannot.\n\nA binary matrix is a matrix with all cells equal to `0` or `1` only.\n\nA zero matrix is a matrix with all cells equal to `0`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minFlips(self, mat: List[List[int]]) -> int:\n m = len(mat)\n n = len(mat[0])\n hash = self._getHash(mat, m, n)\n if hash == 0:\n return 0\n\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n step = 0\n q = collections.deque([hash])\n seen = {hash}\n\n while q:\n step += 1\n for _ in range(len(q)):\n curr = q.popleft()\n for i in range(m):\n for j in range(n):\n next = curr ^ 1 << (i * n + j)\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n next ^= 1 << (x * n + y)\n if next == 0:\n return step\n if next in seen:\n continue\n q.append(next)\n seen.add(next)\n\n return -1\n\n def _getHash(self, mat: List[List[int]], m: int, n: int) -> int:\n hash = 0\n for i in range(m):\n for j in range(n):\n if mat[i][j]:\n hash |= 1 << (i * n + j)\n return hash\n", "java_solution": "class Solution {\n public int minFlips(int[][] mat) {\n final int m = mat.length;\n final int n = mat[0].length;\n final int hash = getHash(mat, m, n);\n if (hash == 0)\n return 0;\n\n final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n Queue q = new ArrayDeque<>(List.of(hash));\n Set seen = new HashSet<>(Arrays.asList(hash));\n\n for (int step = 1; !q.isEmpty(); ++step) {\n for (int sz = q.size(); sz > 0; --sz) {\n final int curr = q.poll();\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n int next = curr ^ 1 << (i * n + j);\n // Flie the four neighbors.\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n next ^= 1 << (x * n + y);\n }\n if (next == 0)\n return step;\n if (seen.contains(next))\n continue;\n q.offer(next);\n seen.add(next);\n }\n }\n }\n }\n\n return -1;\n }\n\n private int getHash(int[][] mat, int m, int n) {\n int hash = 0;\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (mat[i][j] == 1)\n hash |= 1 << (i * n + j);\n return hash;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minFlips(vector>& mat) {\n const int m = mat.size();\n const int n = mat[0].size();\n const int hash = getHash(mat, m, n);\n if (hash == 0)\n return 0;\n\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n queue q{{hash}};\n unordered_set seen{hash};\n\n for (int step = 1; !q.empty(); ++step) {\n for (int sz = q.size(); sz > 0; --sz) {\n const int curr = q.front();\n q.pop();\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n int next = curr ^ 1 << (i * n + j);\n // Flie the four neighbors.\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n next ^= 1 << (x * n + y);\n }\n if (next == 0)\n return step;\n if (seen.contains(next))\n continue;\n q.push(next);\n seen.insert(next);\n }\n }\n }\n }\n\n return -1;\n }\n\n private:\n int getHash(const vector>& mat, int m, int n) {\n int hash = 0;\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (mat[i][j])\n hash |= 1 << (i * n + j);\n return hash;\n }\n};\n"} +{"task_num": 1293, "task_title": "Shortest Path in a Grid with Obstacles Elimination", "difficulty": 3, "func_name": "shortestPath", "description": "You are given an `m x n` integer matrix `grid` where each cell is either `0`\n(empty) or `1` (obstacle). You can move up, down, left, or right from and to\nan empty cell in one step.\n\nReturn the minimum number of steps to walk from the upper left corner `(0, 0)`\nto the lower right corner `(m - 1, n - 1)` given that you can eliminate at\nmost `k` obstacles. If it is not possible to find such walk return `-1`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n m = len(grid)\n n = len(grid[0])\n if m == 1 and n == 1:\n return 0\n\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n steps = 0\n q = collections.deque([(0, 0, k)])\n seen = {(0, 0, k)}\n\n while q:\n steps += 1\n for _ in range(len(q)):\n i, j, eliminate = q.popleft()\n for l in range(4):\n x = i + dirs[l][0]\n y = j + dirs[l][1]\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if x == m - 1 and y == n - 1:\n return steps\n if grid[x][y] == 1 and eliminate == 0:\n continue\n newEliminate = eliminate - grid[x][y]\n if (x, y, newEliminate) in seen:\n continue\n q.append((x, y, newEliminate))\n seen.add((x, y, newEliminate))\n\n return -1\n", "java_solution": "class Solution {\n public int shortestPath(int[][] grid, int k) {\n record T(int i, int j, int eliminate) {}\n final int m = grid.length;\n final int n = grid[0].length;\n if (m == 1 && n == 1)\n return 0;\n\n final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n Queue q = new ArrayDeque<>(List.of(new T(0, 0, k)));\n boolean[][][] seen = new boolean[m][n][k + 1];\n seen[0][0][k] = true;\n\n for (int step = 1; !q.isEmpty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n final int i = q.peek().i;\n final int j = q.peek().j;\n final int eliminate = q.poll().eliminate;\n for (int l = 0; l < 4; ++l) {\n final int x = i + DIRS[l][0];\n final int y = j + DIRS[l][1];\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (x == m - 1 && y == n - 1)\n return step;\n if (grid[x][y] == 1 && eliminate == 0)\n continue;\n final int newEliminate = eliminate - grid[x][y];\n if (seen[x][y][newEliminate])\n continue;\n q.offer(new T(x, y, newEliminate));\n seen[x][y][newEliminate] = true;\n }\n }\n\n return -1;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int shortestPath(vector>& grid, int k) {\n const int m = grid.size();\n const int n = grid[0].size();\n if (m == 1 && n == 1)\n return 0;\n\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n queue> q{{{0, 0, k}}}; // (i, j, eliminate)\n vector>> seen(\n m, vector>(n, vector(k + 1)));\n seen[0][0][k] = true;\n\n for (int step = 1; !q.empty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n const auto [i, j, eliminate] = q.front();\n q.pop();\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (x == m - 1 && y == n - 1)\n return step;\n if (grid[x][y] == 1 && eliminate == 0)\n continue;\n const int newEliminate = eliminate - grid[x][y];\n if (seen[x][y][newEliminate])\n continue;\n q.emplace(x, y, newEliminate);\n seen[x][y][newEliminate] = true;\n }\n }\n\n return -1;\n }\n};\n"} +{"task_num": 1301, "task_title": "Number of Paths with Max Score", "difficulty": 3, "func_name": "pathsWithMaxScore", "description": "You are given a square `board` of characters. You can move on the board\nstarting at the bottom right square marked with the character `'S'`.\n\nYou need to reach the top left square marked with the character `'E'`. The\nrest of the squares are labeled either with a numeric character `1, 2, ..., 9`\nor with an obstacle `'X'`. In one move you can go up, left or up-left\n(diagonally) only if there is no obstacle there.\n\nReturn a list of two integers: the first integer is the maximum sum of numeric\ncharacters you can collect, and the second is the number of such paths that\nyou can take to get that maximum sum, taken modulo `10^9 + 7`.\n\nIn case there is no path, return `[0, 0]`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def pathsWithMaxScore(self, board: List[str]) -> List[int]:\n kMod = 1_000_000_007\n n = len(board)\n dirs = ((0, 1), (1, 0), (1, 1))\n dp = [[-1] * (n + 1) for _ in range(n + 1)]\n count = [[0] * (n + 1) for _ in range(n + 1)]\n\n dp[0][0] = 0\n dp[n - 1][n - 1] = 0\n count[n - 1][n - 1] = 1\n\n for i in reversed(range(n)):\n for j in reversed(range(n)):\n if board[i][j] == 'S' or board[i][j] == 'X':\n continue\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if dp[i][j] < dp[x][y]:\n dp[i][j] = dp[x][y]\n count[i][j] = count[x][y]\n elif dp[i][j] == dp[x][y]:\n count[i][j] += count[x][y]\n count[i][j] %= kMod\n\n if dp[i][j] != -1 and board[i][j] != 'E':\n dp[i][j] += int(board[i][j])\n dp[i][j] %= kMod\n\n return [dp[0][0], count[0][0]]\n", "java_solution": "class Solution {\n public int[] pathsWithMaxScore(List board) {\n final int MOD = 1_000_000_007;\n final int[][] DIRS = {{0, 1}, {1, 0}, {1, 1}};\n final int n = board.size();\n // dp[i][j] := the maximum sum from (n - 1, n - 1) to (i, j)\n int[][] dp = new int[n + 1][n + 1];\n Arrays.stream(dp).forEach(A -> Arrays.fill(A, -1));\n // count[i][j] := the number of paths to get dp[i][j] from (n - 1, n - 1) to (i, j)\n int[][] count = new int[n + 1][n + 1];\n\n dp[0][0] = 0;\n dp[n - 1][n - 1] = 0;\n count[n - 1][n - 1] = 1;\n\n for (int i = n - 1; i >= 0; --i)\n for (int j = n - 1; j >= 0; --j) {\n if (board.get(i).charAt(j) == 'S' || board.get(i).charAt(j) == 'X')\n continue;\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (dp[i][j] < dp[x][y]) {\n dp[i][j] = dp[x][y];\n count[i][j] = count[x][y];\n } else if (dp[i][j] == dp[x][y]) {\n count[i][j] += count[x][y];\n count[i][j] %= MOD;\n }\n }\n // If there's path(s) from 'S' to (i, j) and the cell is not 'E'.\n if (dp[i][j] != -1 && board.get(i).charAt(j) != 'E') {\n dp[i][j] += board.get(i).charAt(j) - '0';\n dp[i][j] %= MOD;\n }\n }\n\n return new int[] {dp[0][0], count[0][0]};\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector pathsWithMaxScore(vector& board) {\n constexpr int kMod = 1'000'000'007;\n constexpr int kDirs[3][2] = {{0, 1}, {1, 0}, {1, 1}};\n const int n = board.size();\n // dp[i][j] := the maximum sum from (n - 1, n - 1) to (i, j)\n vector> dp(n + 1, vector(n + 1, -1));\n // count[i][j] := the number of paths to get dp[i][j] from (n - 1, n - 1) to\n // (i, j)\n vector> count(n + 1, vector(n + 1));\n\n dp[0][0] = 0;\n dp[n - 1][n - 1] = 0;\n count[n - 1][n - 1] = 1;\n\n for (int i = n - 1; i >= 0; --i)\n for (int j = n - 1; j >= 0; --j) {\n if (board[i][j] == 'S' || board[i][j] == 'X')\n continue;\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (dp[i][j] < dp[x][y]) {\n dp[i][j] = dp[x][y];\n count[i][j] = count[x][y];\n } else if (dp[i][j] == dp[x][y]) {\n count[i][j] += count[x][y];\n count[i][j] %= kMod;\n }\n }\n // If there's path(s) from 'S' to (i, j) and the cell is not 'E'.\n if (dp[i][j] != -1 && board[i][j] != 'E') {\n dp[i][j] += board[i][j] - '0';\n dp[i][j] %= kMod;\n }\n }\n\n return {dp[0][0], count[0][0]};\n }\n};\n"} +{"task_num": 1334, "task_title": "Find the City With the Smallest Number of Neighbors at a Threshold Distance", "difficulty": 2, "func_name": "findTheCity", "description": "There are `n` cities numbered from `0` to `n-1`. Given the array `edges` where\n`edges[i] = [fromi, toi, weighti]` represents a bidirectional and weighted\nedge between cities `fromi` and `toi`, and given the integer\n`distanceThreshold`.\n\nReturn the city with the smallest number of cities that are reachable through\nsome path and whose distance is at most `distanceThreshold`, If there are\nmultiple such cities, return the city with the greatest number.\n\nNotice that the distance of a path connecting cities i and j is equal to the\nsum of the edges' weights along that path.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n ans = -1\n minCitiesCount = n\n dist = self._floydWarshall(n, edges, distanceThreshold)\n\n for i in range(n):\n citiesCount = sum(dist[i][j] <= distanceThreshold for j in range(n))\n if citiesCount <= minCitiesCount:\n ans = i\n minCitiesCount = citiesCount\n\n return ans\n\n def _floydWarshall(self, n: int, edges: List[List[int]], distanceThreshold: int) -> List[List[int]]:\n dist = [[distanceThreshold + 1] * n for _ in range(n)]\n\n for i in range(n):\n dist[i][i] = 0\n\n for u, v, w in edges:\n dist[u][v] = w\n dist[v][u] = w\n\n for k in range(n):\n for i in range(n):\n for j in range(n):\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n\n return dist\n", "java_solution": "class Solution {\n public int findTheCity(int n, int[][] edges, int distanceThreshold) {\n int ans = -1;\n int minCitiesCount = n;\n int[][] dist = floydWarshall(n, edges, distanceThreshold);\n\n for (int i = 0; i < n; ++i) {\n int citiesCount = 0;\n for (int j = 0; j < n; ++j)\n if (dist[i][j] <= distanceThreshold)\n ++citiesCount;\n if (citiesCount <= minCitiesCount) {\n ans = i;\n minCitiesCount = citiesCount;\n }\n }\n\n return ans;\n }\n\n private int[][] floydWarshall(int n, int[][] edges, int distanceThreshold) {\n int[][] dist = new int[n][n];\n Arrays.stream(dist).forEach(A -> Arrays.fill(A, distanceThreshold + 1));\n\n for (int i = 0; i < n; ++i)\n dist[i][i] = 0;\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n final int w = edge[2];\n dist[u][v] = w;\n dist[v][u] = w;\n }\n\n for (int k = 0; k < n; ++k)\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);\n\n return dist;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int findTheCity(int n, vector>& edges, int distanceThreshold) {\n int ans = -1;\n int minCitiesCount = n;\n const vector> dist = floydWarshall(n, edges, distanceThreshold);\n\n for (int i = 0; i < n; ++i) {\n int citiesCount = 0;\n for (int j = 0; j < n; ++j)\n if (dist[i][j] <= distanceThreshold)\n ++citiesCount;\n if (citiesCount <= minCitiesCount) {\n ans = i;\n minCitiesCount = citiesCount;\n }\n }\n\n return ans;\n }\n\n private:\n vector> floydWarshall(int n, const vector>& edges,\n int distanceThreshold) {\n vector> dist(n, vector(n, distanceThreshold + 1));\n\n for (int i = 0; i < n; ++i)\n dist[i][i] = 0;\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n const int w = edge[2];\n dist[u][v] = w;\n dist[v][u] = w;\n }\n\n for (int k = 0; k < n; ++k)\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n\n return dist;\n }\n};\n"} +{"task_num": 1340, "task_title": "Jump Game V", "difficulty": 3, "func_name": "maxJumps", "description": "Given an array of integers `arr` and an integer `d`. In one step you can jump\nfrom index `i` to index:\n\n* `i + x` where: `i + x < arr.length` and ` 0 < x <= d`.\n* `i - x` where: `i - x >= 0` and ` 0 < x <= d`.\n\nIn addition, you can only jump from index `i` to index `j` if `arr[i] >\narr[j]` and `arr[i] > arr[k]` for all indices `k` between `i` and `j` (More\nformally `min(i, j) < k < max(i, j)`).\n\nYou can choose any index of the array and start jumping. Return the maximum\nnumber of indices you can visit.\n\nNotice that you can not jump outside of the array at any time.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def maxJumps(self, arr: List[int], d: int) -> int:\n n = len(arr)\n dp = [1] * n\n stack = []\n\n for i in range(n + 1):\n while stack and (i == n or arr[stack[-1]] < arr[i]):\n indices = [stack.pop()]\n while stack and arr[stack[-1]] == arr[indices[0]]:\n indices.append(stack.pop())\n for j in indices:\n if i < n and i - j <= d:\n dp[i] = max(dp[i], dp[j] + 1)\n if stack and j - stack[-1] <= d:\n dp[stack[-1]] = max(dp[stack[-1]], dp[j] + 1)\n stack.append(i)\n\n return max(dp)\n", "java_solution": "class Solution {\n public int maxJumps(int[] arr, int d) {\n final int n = arr.length;\n // dp[i] := the maximum jumps starting from arr[i]\n int[] dp = new int[n];\n // a dcreasing stack that stores indices\n Deque stack = new ArrayDeque<>();\n\n for (int i = 0; i <= n; ++i) {\n while (!stack.isEmpty() && (i == n || arr[stack.peek()] < arr[i])) {\n List indices = new ArrayList<>(List.of(stack.pop()));\n while (!stack.isEmpty() && arr[stack.peek()] == arr[indices.get(0)])\n indices.add(stack.pop());\n for (final int j : indices) {\n if (i < n && i - j <= d)\n // Can jump from i to j.\n dp[i] = Math.max(dp[i], dp[j] + 1);\n if (!stack.isEmpty() && j - stack.peek() <= d)\n // Can jump from stack.peek() to j\n dp[stack.peek()] = Math.max(dp[stack.peek()], dp[j] + 1);\n }\n }\n stack.push(i);\n }\n\n return Arrays.stream(dp).max().getAsInt() + 1;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int maxJumps(vector& arr, int d) {\n const int n = arr.size();\n // dp[i] := the maximum jumps starting from arr[i]\n vector dp(n, 1);\n // a dcreasing stack that stores indices\n stack stack;\n\n for (int i = 0; i <= n; ++i) {\n while (!stack.empty() && (i == n || arr[stack.top()] < arr[i])) {\n vector indices{stack.top()};\n stack.pop();\n while (!stack.empty() && arr[stack.top()] == arr[indices[0]])\n indices.push_back(stack.top()), stack.pop();\n for (const int j : indices) {\n if (i < n && i - j <= d)\n // Can jump from i to j.\n dp[i] = max(dp[i], dp[j] + 1);\n if (!stack.empty() && j - stack.top() <= d)\n // Can jump from stack[-1] to j.\n dp[stack.top()] = max(dp[stack.top()], dp[j] + 1);\n }\n }\n stack.push(i);\n }\n\n return ranges::max(dp);\n }\n};\n"} +{"task_num": 1345, "task_title": "Jump Game IV", "difficulty": 3, "func_name": "minJumps", "description": "Given an array of integers `arr`, you are initially positioned at the first\nindex of the array.\n\nIn one step you can jump from index `i` to index:\n\n* `i + 1` where: `i + 1 < arr.length`.\n* `i - 1` where: `i - 1 >= 0`.\n* `j` where: `arr[i] == arr[j]` and `i != j`.\n\nReturn the minimum number of steps to reach the last index of the array.\n\nNotice that you can not jump outside of the array at any time.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minJumps(self, arr: List[int]) -> int:\n n = len(arr)\n graph = collections.defaultdict(list)\n step = 0\n q = collections.deque([0])\n seen = {0}\n\n for i, a in enumerate(arr):\n graph[a].append(i)\n\n while q:\n for _ in range(len(q)):\n i = q.popleft()\n if i == n - 1:\n return step\n seen.add(i)\n u = arr[i]\n if i + 1 < n:\n graph[u].append(i + 1)\n if i - 1 >= 0:\n graph[u].append(i - 1)\n for v in graph[u]:\n if v in seen:\n continue\n q.append(v)\n graph[u].clear()\n step += 1\n", "java_solution": "class Solution {\n public int minJumps(int[] arr) {\n final int n = arr.length;\n // {a: indices}\n Map> graph = new HashMap<>();\n Queue q = new ArrayDeque<>(List.of(0));\n boolean[] seen = new boolean[n];\n seen[0] = true;\n\n for (int i = 0; i < n; ++i) {\n graph.putIfAbsent(arr[i], new ArrayList<>());\n graph.get(arr[i]).add(i);\n }\n\n for (int step = 0; !q.isEmpty(); ++step) {\n for (int sz = q.size(); sz > 0; --sz) {\n final int i = q.poll();\n if (i == n - 1)\n return step;\n seen[i] = true;\n final int u = arr[i];\n if (i + 1 < n)\n graph.get(u).add(i + 1);\n if (i - 1 >= 0)\n graph.get(u).add(i - 1);\n for (final int v : graph.get(u)) {\n if (seen[v])\n continue;\n q.offer(v);\n }\n graph.get(u).clear();\n }\n }\n\n throw new IllegalArgumentException();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minJumps(vector& arr) {\n const int n = arr.size();\n // {a: indices}\n unordered_map> graph;\n queue q{{0}};\n vector seen(n);\n seen[0] = true;\n\n for (int i = 0; i < n; ++i)\n graph[arr[i]].push_back(i);\n\n for (int step = 0; !q.empty(); ++step) {\n for (int sz = q.size(); sz > 0; --sz) {\n const int i = q.front();\n q.pop();\n if (i == n - 1)\n return step;\n seen[i] = true;\n const int u = arr[i];\n if (i + 1 < n)\n graph[u].push_back(i + 1);\n if (i - 1 >= 0)\n graph[u].push_back(i - 1);\n for (const int v : graph[u]) {\n if (seen[v])\n continue;\n q.push(v);\n }\n graph[u].clear();\n }\n }\n\n throw;\n }\n};\n"} +{"task_num": 1377, "task_title": "Frog Position After T Seconds", "difficulty": 3, "func_name": "frogPosition", "description": "Given an undirected tree consisting of `n` vertices numbered from `1` to `n`.\nA frog starts jumping from vertex 1. In one second, the frog jumps from its\ncurrent vertex to another unvisited vertex if they are directly connected. The\nfrog can not jump back to a visited vertex. In case the frog can jump to\nseveral vertices, it jumps randomly to one of them with the same probability.\nOtherwise, when the frog can not jump to any unvisited vertex, it jumps\nforever on the same vertex.\n\nThe edges of the undirected tree are given in the array `edges`, where\n`edges[i] = [ai, bi]` means that exists an edge connecting the vertices `ai`\nand `bi`.\n\nReturn the probability that after `t` seconds the frog is on the vertex\n`target`. Answers within `10-5` of the actual answer will be accepted.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:\n tree = [[] for _ in range(n + 1)]\n q = collections.deque([1])\n seen = [False] * (n + 1)\n prob = [0] * (n + 1)\n\n prob[1] = 1\n seen[1] = True\n\n for u, v in edges:\n tree[u].append(v)\n tree[v].append(u)\n\n for _ in range(t):\n for _ in range(len(q)):\n a = q.popleft()\n nChildren = sum(not seen[b] for b in tree[a])\n for b in tree[a]:\n if seen[b]:\n continue\n seen[b] = True\n prob[b] = prob[a] / nChildren\n q.append(b)\n if nChildren > 0:\n prob[a] = 0\n\n return prob[target]\n", "java_solution": "class Solution {\n public double frogPosition(int n, int[][] edges, int t, int target) {\n List[] tree = new List[n + 1];\n Queue q = new ArrayDeque<>(List.of(1));\n boolean[] seen = new boolean[n + 1];\n double[] prob = new double[n + 1];\n\n seen[1] = true;\n prob[1] = 1.0;\n\n for (int i = 1; i <= n; ++i)\n tree[i] = new ArrayList<>();\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n tree[u].add(v);\n tree[v].add(u);\n }\n\n while (!q.isEmpty() && t-- > 0)\n for (int sz = q.size(); sz > 0; --sz) {\n final int a = q.poll();\n int nChildren = 0;\n for (final int b : tree[a])\n if (!seen[b])\n ++nChildren;\n for (final int b : tree[a]) {\n if (seen[b])\n continue;\n seen[b] = true;\n prob[b] = prob[a] / nChildren;\n q.add(b);\n }\n if (nChildren > 0)\n prob[a] = 0.0;\n }\n\n return prob[target];\n }\n}\n", "cpp_solution": "class Solution {\n public:\n double frogPosition(int n, vector>& edges, int t, int target) {\n vector> tree(n + 1);\n queue q{{1}};\n vector seen(n + 1);\n vector prob(n + 1);\n\n seen[1] = true;\n prob[1] = 1.0;\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n tree[u].push_back(v);\n tree[v].push_back(u);\n }\n\n while (!q.empty() && t-- > 0)\n for (int sz = q.size(); sz > 0; --sz) {\n const int a = q.front();\n q.pop();\n const int nChildren =\n ranges::count_if(tree[a], [&seen](int b) { return !seen[b]; });\n for (const int b : tree[a]) {\n if (seen[b])\n continue;\n seen[b] = true;\n prob[b] = prob[a] / nChildren;\n q.push(b);\n }\n if (nChildren > 0)\n prob[a] = 0.0;\n }\n\n return prob[target];\n }\n};\n"} +{"task_num": 1417, "task_title": "Reformat The String", "difficulty": 1, "func_name": "reformat", "description": "You are given an alphanumeric string `s`. (Alphanumeric string is a string\nconsisting of lowercase English letters and digits).\n\nYou have to find a permutation of the string where no letter is followed by\nanother letter and no digit is followed by another digit. That is, no two\nadjacent characters have the same type.\n\nReturn the reformatted string or return an empty string if it is impossible to\nreformat the string.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def reformat(self, s: str) -> str:\n A=[]\n for c in s:\n if c.isalpha():\n A.append(c)\n B=[]\n for c in s:\n if c.isdigit():\n B.append(c)\n\n if len(A) < len(B):\n A, B = B, A\n if len(A) - len(B) > 1:\n return ''\n\n ans = []\n\n for i in range(len(B)):\n ans.append(A[i])\n ans.append(B[i])\n\n if len(A) == len(B) + 1:\n ans.append(A[-1])\n return ''.join(ans)\n", "java_solution": "class Solution {\n public String reformat(String s) {\n List A = new ArrayList<>();\n List B = new ArrayList<>();\n\n for (final char c : s.toCharArray())\n if (Character.isAlphabetic(c))\n A.add(c);\n else\n B.add(c);\n\n if (A.size() < B.size()) {\n List temp = A;\n A = B;\n B = temp;\n }\n if (A.size() - B.size() > 1)\n return \"\";\n\n StringBuilder sb = new StringBuilder();\n\n for (int i = 0; i < B.size(); ++i) {\n sb.append(A.get(i));\n sb.append(B.get(i));\n }\n\n if (A.size() > B.size())\n sb.append(A.get(A.size() - 1));\n return sb.toString();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n string reformat(string s) {\n vector A;\n vector B;\n\n for (const char c : s)\n isalpha(c) ? A.push_back(c) : B.push_back(c);\n\n if (A.size() < B.size())\n swap(A, B);\n if (A.size() - B.size() > 1)\n return \"\";\n\n string ans;\n\n for (int i = 0; i < B.size(); ++i)\n ans += string{A[i], B[i]};\n\n if (A.size() > B.size())\n ans += A.back();\n return ans;\n }\n};\n"} +{"task_num": 1462, "task_title": "Course Schedule IV", "difficulty": 2, "func_name": "checkIfPrerequisite", "description": "There are a total of `numCourses` courses you have to take, labeled from `0`\nto `numCourses - 1`. You are given an array `prerequisites` where\n`prerequisites[i] = [ai, bi]` indicates that you must take course `ai` first\nif you want to take course `bi`.\n\n* For example, the pair `[0, 1]` indicates that you have to take course `0` before you can take course `1`.\n\nPrerequisites can also be indirect. If course `a` is a prerequisite of course\n`b`, and course `b` is a prerequisite of course `c`, then course `a` is a\nprerequisite of course `c`.\n\nYou are also given an array `queries` where `queries[j] = [uj, vj]`. For the\n`jth` query, you should answer whether course `uj` is a prerequisite of course\n`vj` or not.\n\nReturn a boolean array `answer`, where `answer[j]` is the answer to the `jth`\nquery.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n graph = [[] for _ in range(numCourses)]\n isPrerequisite = [[False] * numCourses for _ in range(numCourses)]\n\n for u, v in prerequisites:\n graph[u].append(v)\n\n for i in range(numCourses):\n self._dfs(graph, i, isPrerequisite[i])\n\n return [isPrerequisite[u][v] for u, v in queries]\n\n def _dfs(self, graph: List[List[int]], u: int, used: List[bool]) -> None:\n for v in graph[u]:\n if used[v]:\n continue\n used[v] = True\n self._dfs(graph, v, used)\n", "java_solution": "class Solution {\n public List checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {\n List ans = new ArrayList<>();\n List[] graph = new List[numCourses];\n\n for (int i = 0; i < numCourses; ++i)\n graph[i] = new ArrayList<>();\n\n for (int[] prerequisite : prerequisites) {\n final int u = prerequisite[0];\n final int v = prerequisite[1];\n graph[u].add(v);\n }\n\n // isPrerequisite[i][j] := true if course i is a prerequisite of course j\n boolean[][] isPrerequisite = new boolean[numCourses][numCourses];\n\n // DFS from every course.\n for (int i = 0; i < numCourses; ++i)\n dfs(graph, i, isPrerequisite[i]);\n\n for (int[] query : queries) {\n final int u = query[0];\n final int v = query[1];\n ans.add(isPrerequisite[u][v]);\n }\n\n return ans;\n }\n\n public void dfs(List[] graph, int u, boolean[] used) {\n for (final int v : graph[u]) {\n if (used[v])\n continue;\n used[v] = true;\n dfs(graph, v, used);\n }\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector checkIfPrerequisite(int numCourses,\n vector>& prerequisites,\n vector>& queries) {\n vector ans;\n vector> graph(numCourses);\n // isPrerequisite[i][j] := true if course i is a prerequisite of course j\n vector> isPrerequisite(numCourses, vector(numCourses));\n\n for (const vector& prerequisite : prerequisites) {\n const int u = prerequisite[0];\n const int v = prerequisite[1];\n graph[u].push_back(v);\n }\n\n // DFS from every course.\n for (int i = 0; i < numCourses; ++i)\n dfs(graph, i, isPrerequisite[i]);\n\n for (const vector& query : queries) {\n const int u = query[0];\n const int v = query[1];\n ans.push_back(isPrerequisite[u][v]);\n }\n\n return ans;\n }\n\n void dfs(const vector>& graph, int u, vector& used) {\n for (const int v : graph[u]) {\n if (used[v])\n continue;\n used[v] = true;\n dfs(graph, v, used);\n }\n }\n};\n"} +{"task_num": 1489, "task_title": "Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree", "difficulty": 3, "func_name": "findCriticalAndPseudoCriticalEdges", "description": "Given a weighted undirected connected graph with `n` vertices numbered from\n`0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]`\nrepresents a bidirectional and weighted edge between nodes `ai` and `bi`. A\nminimum spanning tree (MST) is a subset of the graph's edges that connects all\nvertices without cycles and with the minimum possible total edge weight.\n\nFind all the critical and pseudo-critical edges in the given graph's minimum\nspanning tree (MST). An MST edge whose deletion from the graph would cause the\nMST weight to increase is called a critical edge. On the other hand, a pseudo-\ncritical edge is that which can appear in some MSTs but not all.\n\nNote that you can return the indices of the edges in any order.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator, Union\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self.find(u)\n j = self.find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n criticalEdges = []\n pseudoCriticalEdges = []\n\n for i in range(len(edges)):\n edges[i].append(i)\n\n edges.sort(key=lambda x: x[2])\n\n def getMSTWeight(firstEdge: List[int], deletedEdgeIndex: int) -> Union[int, float]:\n mstWeight = 0\n uf = UnionFind(n)\n\n if firstEdge:\n uf.unionByRank(firstEdge[0], firstEdge[1])\n mstWeight += firstEdge[2]\n\n for u, v, weight, index in edges:\n if index == deletedEdgeIndex:\n continue\n if uf.find(u) == uf.find(v):\n continue\n uf.unionByRank(u, v)\n mstWeight += weight\n\n root = uf.find(0)\n if any(uf.find(i) != root for i in range(n)):\n return math.inf\n\n return mstWeight\n\n mstWeight = getMSTWeight([], -1)\n\n for edge in edges:\n index = edge[3]\n if getMSTWeight([], index) > mstWeight:\n criticalEdges.append(index)\n elif getMSTWeight(edge, -1) == mstWeight:\n pseudoCriticalEdges.append(index)\n\n return [criticalEdges, pseudoCriticalEdges]\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public void unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n public int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n\n private int[] id;\n private int[] rank;\n}\n\nclass Solution {\n public List> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) {\n List criticalEdges = new ArrayList<>();\n List pseudoCriticalEdges = new ArrayList<>();\n\n // Record the index information, so edges[i] := (u, v, weight, index).\n for (int i = 0; i < edges.length; ++i)\n edges[i] = new int[] {edges[i][0], edges[i][1], edges[i][2], i};\n\n // Sort by the weight.\n Arrays.sort(edges, Comparator.comparingInt(edge -> edge[2]));\n\n final int mstWeight = getMSTWeight(n, edges, new int[] {}, -1);\n\n for (int[] edge : edges) {\n final int index = edge[3];\n // Deleting the `edge` increases the MST's weight or makes the MST\n // invalid.\n if (getMSTWeight(n, edges, new int[] {}, index) > mstWeight)\n criticalEdges.add(index);\n // If an edge can be in any MST, we can always add `edge` to the edge set.\n else if (getMSTWeight(n, edges, edge, -1) == mstWeight)\n pseudoCriticalEdges.add(index);\n }\n\n return List.of(criticalEdges, pseudoCriticalEdges);\n }\n\n private int getMSTWeight(int n, int[][] edges, int[] firstEdge, int deletedEdgeIndex) {\n int mstWeight = 0;\n UnionFind uf = new UnionFind(n);\n\n if (firstEdge.length == 4) {\n uf.unionByRank(firstEdge[0], firstEdge[1]);\n mstWeight += firstEdge[2];\n }\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n final int weight = edge[2];\n final int index = edge[3];\n if (index == deletedEdgeIndex)\n continue;\n if (uf.find(u) == uf.find(v))\n continue;\n uf.unionByRank(u, v);\n mstWeight += weight;\n }\n\n final int root = uf.find(0);\n for (int i = 0; i < n; ++i)\n if (uf.find(i) != root)\n return Integer.MAX_VALUE;\n\n return mstWeight;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n), rank(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n void unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n\n private:\n vector id;\n vector rank;\n};\n\nclass Solution {\n public:\n vector> findCriticalAndPseudoCriticalEdges(\n int n, vector>& edges) {\n vector criticalEdges;\n vector pseudoCriticalEdges;\n\n // Record the index information, so edges[i] := (u, v, weight, index).\n for (int i = 0; i < edges.size(); ++i)\n edges[i].push_back(i);\n\n // Sort by the weight.\n ranges::sort(edges, ranges::less{},\n [](const vector& edge) { return edge[2]; });\n\n const int mstWeight = getMSTWeight(n, edges, {}, -1);\n\n for (const vector& edge : edges) {\n const int index = edge[3];\n // Deleting the `edge` increases the MST's weight or makes the MST\n // invalid.\n if (getMSTWeight(n, edges, {}, index) > mstWeight)\n criticalEdges.push_back(index);\n // If an edge can be in any MST, we can always add `edge` to the edge set.\n else if (getMSTWeight(n, edges, edge, -1) == mstWeight)\n pseudoCriticalEdges.push_back(index);\n }\n\n return {criticalEdges, pseudoCriticalEdges};\n }\n\n private:\n int getMSTWeight(int n, const vector>& edges,\n const vector& firstEdge, int deletedEdgeIndex) {\n int mstWeight = 0;\n UnionFind uf(n);\n\n if (!firstEdge.empty()) {\n uf.unionByRank(firstEdge[0], firstEdge[1]);\n mstWeight += firstEdge[2];\n }\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n const int weight = edge[2];\n const int index = edge[3];\n if (index == deletedEdgeIndex)\n continue;\n if (uf.find(u) == uf.find(v))\n continue;\n uf.unionByRank(u, v);\n mstWeight += weight;\n }\n\n const int root = uf.find(0);\n for (int i = 0; i < n; ++i)\n if (uf.find(i) != root)\n return INT_MAX;\n\n return mstWeight;\n }\n};\n"} +{"task_num": 1573, "task_title": "Number of Ways to Split a String", "difficulty": 2, "func_name": "numWays", "description": "Given a binary string `s`, you can split `s` into 3 non-empty strings `s1`,\n`s2`, and `s3` where `s1 + s2 + s3 = s`.\n\nReturn the number of ways `s` can be split such that the number of ones is the\nsame in `s1`, `s2`, and `s3`. Since the answer may be too large, return it\nmodulo `109 + 7`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def numWays(self, s: str) -> int:\n kMod = 1_000_000_007\n ones = s.count('1')\n if ones % 3 != 0:\n return 0\n if ones == 0:\n n = len(s)\n return (n - 1) * (n - 2) // 2 % kMod\n\n s1End = -1\n s2Start = -1\n s2End = -1\n s3Start = -1\n onesSoFar = 0\n\n for i, c in enumerate(s):\n if c == '1':\n onesSoFar += 1\n if s1End == -1 and onesSoFar == ones // 3:\n s1End = i\n elif s2Start == -1 and onesSoFar == ones // 3 + 1:\n s2Start = i\n if s2End == -1 and onesSoFar == ones // 3 * 2:\n s2End = i\n elif s3Start == -1 and onesSoFar == ones // 3 * 2 + 1:\n s3Start = i\n\n return (s2Start - s1End) * (s3Start - s2End) % kMod\n", "java_solution": "class Solution {\n public int numWays(String s) {\n final int MOD = 1_000_000_007;\n final int ones = (int) s.chars().filter(c -> c == '1').count();\n if (ones % 3 != 0)\n return 0;\n if (ones == 0) {\n final long n = s.length();\n return (int) ((n - 1) * (n - 2) / 2 % MOD);\n }\n\n int s1End = -1;\n int s2Start = -1;\n int s2End = -1;\n int s3Start = -1;\n int onesSoFar = 0;\n\n for (int i = 0; i < s.length(); ++i) {\n if (s.charAt(i) == '1')\n ++onesSoFar;\n if (s1End == -1 && onesSoFar == ones / 3)\n s1End = i;\n else if (s2Start == -1 && onesSoFar == ones / 3 + 1)\n s2Start = i;\n if (s2End == -1 && onesSoFar == ones / 3 * 2)\n s2End = i;\n else if (s3Start == -1 && onesSoFar == ones / 3 * 2 + 1)\n s3Start = i;\n }\n\n return (int) ((long) (s2Start - s1End) * (s3Start - s2End) % MOD);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int numWays(string s) {\n constexpr int kMod = 1'000'000'007;\n const int ones = ranges::count(s, '1');\n if (ones % 3 != 0)\n return 0;\n if (ones == 0) {\n const long n = s.size();\n return (n - 1) * (n - 2) / 2 % kMod;\n }\n\n int s1End = -1;\n int s2Start = -1;\n int s2End = -1;\n int s3Start = -1;\n int onesSoFar = 0;\n\n for (int i = 0; i < s.length(); ++i) {\n if (s[i] == '1')\n ++onesSoFar;\n if (s1End == -1 && onesSoFar == ones / 3)\n s1End = i;\n else if (s2Start == -1 && onesSoFar == ones / 3 + 1)\n s2Start = i;\n if (s2End == -1 && onesSoFar == ones / 3 * 2)\n s2End = i;\n else if (s3Start == -1 && onesSoFar == ones / 3 * 2 + 1)\n s3Start = i;\n }\n\n return static_cast(s2Start - s1End) * (s3Start - s2End) % kMod;\n }\n};\n"} +{"task_num": 1574, "task_title": "Shortest Subarray to be Removed to Make Array Sorted", "difficulty": 2, "func_name": "findLengthOfShortestSubarray", "description": "Given an integer array `arr`, remove a subarray (can be empty) from `arr` such\nthat the remaining elements in `arr` are non-decreasing.\n\nReturn the length of the shortest subarray to remove.\n\nA subarray is a contiguous subsequence of the array.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def findLengthOfShortestSubarray(self, arr: List[int]) -> int:\n n = len(arr)\n l = 0\n r = n - 1\n\n while l < n - 1 and arr[l + 1] >= arr[l]:\n l += 1\n while r > 0 and arr[r - 1] <= arr[r]:\n r -= 1\n ans = min(n - 1 - l, r)\n\n i = l\n j = n - 1\n while i >= 0 and j >= r and j > i:\n if arr[i] <= arr[j]:\n j -= 1\n else:\n i -= 1\n ans = min(ans, j - i)\n\n return ans\n", "java_solution": "class Solution {\n public int findLengthOfShortestSubarray(int[] arr) {\n final int n = arr.length;\n int l = 0;\n int r = n - 1;\n\n // arr[0..l] is non-decreasing prefix.\n while (l < n - 1 && arr[l + 1] >= arr[l])\n ++l;\n // arr[r..n - 1] is non-decreasing suffix.\n while (r > 0 && arr[r - 1] <= arr[r])\n --r;\n // Remove arr[l + 1..n - 1] or arr[0..r - 1]\n int ans = Math.min(n - 1 - l, r);\n\n // Since arr[0..l] and arr[r..n - 1] are non-decreasing, we place pointers\n // at the rightmost indices, l and n - 1, and greedily shrink them toward\n // the leftmost indices, 0 and r, respectively. By removing arr[i + 1..j],\n // we ensure that `arr` becomes non-decreasing.\n int i = l;\n int j = n - 1;\n while (i >= 0 && j >= r && j > i) {\n if (arr[i] <= arr[j])\n --j;\n else\n --i;\n ans = Math.min(ans, j - i);\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int findLengthOfShortestSubarray(vector& arr) {\n const int n = arr.size();\n int l = 0;\n int r = n - 1;\n\n // arr[0..l] is non-decreasing.\n while (l < n - 1 && arr[l + 1] >= arr[l])\n ++l;\n // arr[r..n - 1] is non-decreasing.\n while (r > 0 && arr[r - 1] <= arr[r])\n --r;\n // Remove arr[l + 1..n - 1] or arr[0..r - 1].\n int ans = min(n - 1 - l, r);\n\n // Since arr[0..l] and arr[r..n - 1] are non-decreasing, we place pointers\n // at the rightmost indices, l and n - 1, and greedily shrink them toward\n // the leftmost indices, 0 and r, respectively. By removing arr[i + 1..j],\n // we ensure that `arr` becomes non-decreasing.\n int i = l;\n int j = n - 1;\n while (i >= 0 && j >= r && j > i) {\n if (arr[i] <= arr[j])\n --j;\n else\n --i;\n ans = min(ans, j - i);\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1579, "task_title": "Remove Max Number of Edges to Keep Graph Fully Traversable", "difficulty": 3, "func_name": "maxNumEdgesToRemove", "description": "Alice and Bob have an undirected graph of `n` nodes and three types of edges:\n\n* Type 1: Can be traversed by Alice only.\n* Type 2: Can be traversed by Bob only.\n* Type 3: Can be traversed by both Alice and Bob.\n\nGiven an array `edges` where `edges[i] = [typei, ui, vi]` represents a\nbidirectional edge of type `typei` between nodes `ui` and `vi`, find the\nmaximum number of edges you can remove so that after removing the edges, the\ngraph can still be fully traversed by both Alice and Bob. The graph is fully\ntraversed by Alice and Bob if starting from any node, they can reach all other\nnodes.\n\nReturn the maximum number of edges you can remove, or return `-1` if Alice and\nBob cannot fully traverse the graph.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.count = n\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> bool:\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return False\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n self.count -= 1\n return True\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n alice = UnionFind(n)\n bob = UnionFind(n)\n requiredEdges = 0\n\n for type, u, v in sorted(edges, reverse=True):\n u -= 1\n v -= 1\n if type == 3:\n if alice.unionByRank(u, v) | bob.unionByRank(u, v):\n requiredEdges += 1\n elif type == 2:\n if bob.unionByRank(u, v):\n requiredEdges += 1\n else:\n if alice.unionByRank(u, v):\n requiredEdges += 1\n\n if alice.count == 1 and bob.count == 1:\n return len(edges) - requiredEdges\n else:\n return -1\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n count = n;\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public boolean unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return false;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n --count;\n return true;\n }\n\n public int getCount() {\n return count;\n }\n\n private int count;\n private int[] id;\n private int[] rank;\n\n private int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n}\n\nclass Solution {\n public int maxNumEdgesToRemove(int n, int[][] edges) {\n UnionFind alice = new UnionFind(n);\n UnionFind bob = new UnionFind(n);\n int requiredEdges = 0;\n\n // Greedily put type 3 edges in the front.\n Arrays.sort(edges, Comparator.comparingInt(edge -> - edge[0]));\n\n for (int[] edge : edges) {\n final int type = edge[0];\n final int u = edge[1] - 1;\n final int v = edge[2] - 1;\n switch (type) {\n case 3: // Can be traversed by Alice and Bob.\n // Note that we should use | instead of || because if the first\n // expression is true, short-circuiting will skip the second\n // expression.\n if (alice.unionByRank(u, v) | bob.unionByRank(u, v))\n ++requiredEdges;\n break;\n case 2: // Can be traversed by Bob.\n if (bob.unionByRank(u, v))\n ++requiredEdges;\n break;\n case 1: // Can be traversed by Alice.\n if (alice.unionByRank(u, v))\n ++requiredEdges;\n }\n }\n\n return alice.getCount() == 1 && bob.getCount() == 1 ? edges.length - requiredEdges : -1;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : count(n), id(n), rank(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n bool unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return false;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n --count;\n return true;\n }\n\n int getCount() const {\n return count;\n }\n\n private:\n int count;\n vector id;\n vector rank;\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n};\n\nclass Solution {\n public:\n int maxNumEdgesToRemove(int n, vector>& edges) {\n UnionFind alice(n);\n UnionFind bob(n);\n int requiredEdges = 0;\n\n // Greedily put type 3 edges in the front.\n ranges::sort(edges, ranges::greater{},\n [](const vector& edge) { return edge[0]; });\n\n for (const vector& edge : edges) {\n const int type = edge[0];\n const int u = edge[1] - 1;\n const int v = edge[2] - 1;\n switch (type) {\n case 3: // Can be traversed by Alice and Bob.\n // Note that we should use | instead of || because if the first\n // expression is true, short-circuiting will skip the second\n // expression.\n if (alice.unionByRank(u, v) | bob.unionByRank(u, v))\n ++requiredEdges;\n break;\n case 2: // Can be traversed by Bob.\n if (bob.unionByRank(u, v))\n ++requiredEdges;\n break;\n case 1: // Can be traversed by Alice.\n if (alice.unionByRank(u, v))\n ++requiredEdges;\n break;\n }\n }\n\n return alice.getCount() == 1 && bob.getCount() == 1\n ? edges.size() - requiredEdges\n : -1;\n }\n};\n"} +{"task_num": 1582, "task_title": "Special Positions in a Binary Matrix", "difficulty": 1, "func_name": "numSpecial", "description": "Given an `m x n` binary matrix `mat`, return the number of special positions\nin `mat`.\n\nA position `(i, j)` is called special if `mat[i][j] == 1` and all other\nelements in row `i` and column `j` are `0` (rows and columns are 0-indexed).\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def numSpecial(self, mat: List[List[int]]) -> int:\n m = len(mat)\n n = len(mat[0])\n ans = 0\n rowOnes = [0] * m\n colOnes = [0] * n\n\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 1:\n rowOnes[i] += 1\n colOnes[j] += 1\n\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 1 and rowOnes[i] == 1 and colOnes[j] == 1:\n ans += 1\n\n return ans\n", "java_solution": "class Solution {\n public int numSpecial(int[][] mat) {\n final int m = mat.length;\n final int n = mat[0].length;\n int ans = 0;\n int[] rowOnes = new int[m];\n int[] colOnes = new int[n];\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (mat[i][j] == 1) {\n ++rowOnes[i];\n ++colOnes[j];\n }\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (mat[i][j] == 1 && rowOnes[i] == 1 && colOnes[j] == 1)\n ++ans;\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int numSpecial(vector>& mat) {\n const int m = mat.size();\n const int n = mat[0].size();\n int ans = 0;\n vector rowOnes(m);\n vector colOnes(n);\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (mat[i][j] == 1) {\n ++rowOnes[i];\n ++colOnes[j];\n }\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (mat[i][j] == 1 && rowOnes[i] == 1 && colOnes[j] == 1)\n ++ans;\n\n return ans;\n }\n};\n"} +{"task_num": 1583, "task_title": "Count Unhappy Friends", "difficulty": 2, "func_name": "unhappyFriends", "description": "You are given a list of `preferences` for `n` friends, where `n` is always\neven.\n\nFor each person `i`, `preferences[i]` contains a list of friends sorted in the\norder of preference. In other words, a friend earlier in the list is more\npreferred than a friend later in the list. Friends in each list are denoted by\nintegers from `0` to `n-1`.\n\nAll the friends are divided into pairs. The pairings are given in a list\n`pairs`, where `pairs[i] = [xi, yi]` denotes `xi` is paired with `yi` and `yi`\nis paired with `xi`.\n\nHowever, this pairing may cause some of the friends to be unhappy. A friend\n`x` is unhappy if `x` is paired with `y` and there exists a friend `u` who is\npaired with `v` but:\n\n* `x` prefers `u` over `y`, and\n* `u` prefers `x` over `v`.\n\nReturn the number of unhappy friends.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:\n ans = 0\n matches = [0] * n\n prefer = [{} for _ in range(n)]\n\n for x, y in pairs:\n matches[x] = y\n matches[y] = x\n\n for i in range(n):\n for j in range(n - 1):\n prefer[i][preferences[i][j]] = j\n\n for x in range(n):\n for u in prefer[x].keys():\n y = matches[x]\n v = matches[u]\n if prefer[x][u] < prefer[x][y] and prefer[u][x] < prefer[u][v]:\n ans += 1\n break\n\n return ans\n", "java_solution": "class Solution {\n public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {\n int ans = 0;\n int[] matches = new int[n];\n Map[] prefer = new Map[n];\n\n for (int[] pair : pairs) {\n final int x = pair[0];\n final int y = pair[1];\n matches[x] = y;\n matches[y] = x;\n }\n\n for (int i = 0; i < n; ++i)\n prefer[i] = new HashMap<>();\n\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n - 1; ++j)\n prefer[i].put(preferences[i][j], j);\n\n for (int x = 0; x < n; ++x)\n for (final int u : preferences[x]) {\n final int y = matches[x];\n final int v = matches[u];\n if (prefer[x].get(u) < prefer[x].get(y) && prefer[u].get(x) < prefer[u].get(v)) {\n ++ans;\n break;\n }\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int unhappyFriends(int n, vector>& preferences,\n vector>& pairs) {\n int ans = 0;\n vector matches(n);\n vector> prefer(n);\n\n for (const vector& pair : pairs) {\n const int x = pair[0];\n const int y = pair[1];\n matches[x] = y;\n matches[y] = x;\n }\n\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n - 1; ++j)\n prefer[i][preferences[i][j]] = j;\n\n for (int x = 0; x < n; ++x)\n for (const auto& [u, _] : prefer[x]) {\n const int y = matches[x];\n const int v = matches[u];\n if (prefer[x][u] < prefer[x][y] && prefer[u][x] < prefer[u][v]) {\n ++ans;\n break;\n }\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1591, "task_title": "Strange Printer II", "difficulty": 3, "func_name": "isPrintable", "description": "There is a strange printer with the following two special requirements:\n\n* On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.\n* Once the printer has used a color for the above operation, the same color cannot be used again.\n\nYou are given a `m x n` matrix `targetGrid`, where `targetGrid[row][col]` is\nthe color in the position `(row, col)` of the grid.\n\nReturn `true` if it is possible to print the matrix `targetGrid`, otherwise,\nreturn `false`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nfrom enum import Enum\n\n\nclass State(Enum):\n kInit = 0\n kVisiting = 1\n kVisited = 2\n\n\nclass Solution:\n def isPrintable(self, targetGrid: List[List[int]]) -> bool:\n kMaxColor = 60\n m = len(targetGrid)\n n = len(targetGrid[0])\n\n graph = [set() for _ in range(kMaxColor + 1)]\n\n for color in range(1, kMaxColor + 1):\n minI = m\n minJ = n\n maxI = -1\n maxJ = -1\n for i in range(m):\n for j in range(n):\n if targetGrid[i][j] == color:\n minI = min(minI, i)\n minJ = min(minJ, j)\n maxI = max(maxI, i)\n maxJ = max(maxJ, j)\n\n for i in range(minI, maxI + 1):\n for j in range(minJ, maxJ + 1):\n if targetGrid[i][j] != color:\n graph[color].add(targetGrid[i][j])\n\n states = [State.kInit] * (kMaxColor + 1)\n\n def hasCycle(u: int) -> bool:\n if states[u] == State.kVisiting:\n return True\n if states[u] == State.kVisited:\n return False\n\n states[u] = State.kVisiting\n if any(hasCycle(v) for v in graph[u]):\n return True\n states[u] = State.kVisited\n\n return False\n\n for i in range(1, kMaxColor + 1):\n if hasCycle(i):\n return False\n return True\n", "java_solution": "enum State { INIT, VISITING, VISITED }\n\nclass Solution {\n public boolean isPrintable(int[][] targetGrid) {\n final int MAX_COLOR = 60;\n final int m = targetGrid.length;\n final int n = targetGrid[0].length;\n // graph[u] := {v1, v2} means v1 and v2 cover u\n Set[] graph = new HashSet[MAX_COLOR + 1];\n\n for (int color = 1; color <= MAX_COLOR; ++color) {\n // Get the rectangle of the current color.\n int minI = m;\n int minJ = n;\n int maxI = -1;\n int maxJ = -1;\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (targetGrid[i][j] == color) {\n minI = Math.min(minI, i);\n minJ = Math.min(minJ, j);\n maxI = Math.max(maxI, i);\n maxJ = Math.max(maxJ, j);\n }\n // Add any color covering the current as the children.\n graph[color] = new HashSet<>();\n for (int i = minI; i <= maxI; ++i)\n for (int j = minJ; j <= maxJ; ++j)\n if (targetGrid[i][j] != color) {\n graph[color].add(targetGrid[i][j]);\n }\n }\n\n State[] states = new State[MAX_COLOR + 1];\n\n for (int color = 1; color <= MAX_COLOR; ++color)\n if (hasCycle(graph, color, states))\n return false;\n\n return true;\n }\n\n private boolean hasCycle(Set[] graph, int u, State[] states) {\n if (states[u] == State.VISITING)\n return true;\n if (states[u] == State.VISITED)\n return false;\n states[u] = State.VISITING;\n for (int v : graph[u])\n if (hasCycle(graph, v, states))\n return true;\n states[u] = State.VISITED;\n return false;\n }\n}\n", "cpp_solution": "enum class State { kInit, kVisiting, kVisited };\n\nclass Solution {\n public:\n bool isPrintable(vector>& targetGrid) {\n constexpr int kMaxColor = 60;\n const int m = targetGrid.size();\n const int n = targetGrid[0].size();\n // graph[u] := {v1, v2} means v1 and v2 cover u\n vector> graph(kMaxColor + 1);\n\n for (int color = 1; color <= kMaxColor; ++color) {\n // Get the rectangle of the current color.\n int minI = m;\n int minJ = n;\n int maxI = -1;\n int maxJ = -1;\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (targetGrid[i][j] == color) {\n minI = min(minI, i);\n minJ = min(minJ, j);\n maxI = max(maxI, i);\n maxJ = max(maxJ, j);\n }\n // Add any color covering the current as the children.\n for (int i = minI; i <= maxI; ++i)\n for (int j = minJ; j <= maxJ; ++j)\n if (targetGrid[i][j] != color)\n graph[color].insert(targetGrid[i][j]);\n }\n\n vector states(kMaxColor + 1);\n\n for (int color = 1; color <= kMaxColor; ++color)\n if (hasCycle(graph, color, states))\n return false;\n\n return true;\n }\n\n private:\n bool hasCycle(const vector>& graph, int u,\n vector& states) {\n if (states[u] == State::kVisiting)\n return true;\n if (states[u] == State::kVisited)\n return false;\n states[u] = State::kVisiting;\n for (const int v : graph[u])\n if (hasCycle(graph, v, states))\n return true;\n states[u] = State::kVisited;\n return false;\n }\n};\n"} +{"task_num": 1604, "task_title": "Alert Using Same Key-Card Three or More Times in a One Hour Period", "difficulty": 2, "func_name": "alertNames", "description": "LeetCode company workers use key-cards to unlock office doors. Each time a\nworker uses their key-card, the security system saves the worker's name and\nthe time when it was used. The system emits an alert if any worker uses the\nkey-card three or more times in a one-hour period.\n\nYou are given a list of strings `keyName` and `keyTime` where `[keyName[i],\nkeyTime[i]]` corresponds to a person's name and the time when their key-card\nwas used in a single day.\n\nAccess times are given in the 24-hour time format \"HH:MM\", such as `\"23:51\"`\nand `\"09:49\"`.\n\nReturn a list of unique worker names who received an alert for frequent\nkeycard use. Sort the names in ascending order alphabetically.\n\nNotice that `\"10:00\"` \\- `\"11:00\"` is considered to be within a one-hour\nperiod, while `\"22:51\"` \\- `\"23:52\"` is not considered to be within a one-hour\nperiod.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:\n nameToMinutes = collections.defaultdict(list)\n\n for name, time in zip(keyName, keyTime):\n minutes = self._getMinutes(time)\n nameToMinutes[name].append(minutes)\n\n res=[]\n for name, minutes in nameToMinutes.items():\n if self._hasAlert(minutes):\n res.append(name)\n return sorted(res)\n\n def _hasAlert(self, minutes: List[int]) -> bool:\n if len(minutes) > 70:\n return True\n minutes.sort()\n for i in range(2, len(minutes)):\n if minutes[i - 2] + 60 >= minutes[i]:\n return True\n return False\n\n def _getMinutes(self, time: str) -> int:\n h, m = map(int, time.split(':'))\n return 60 * h + m\n", "java_solution": "class Solution {\n public List alertNames(String[] keyName, String[] keyTime) {\n List ans = new ArrayList<>();\n HashMap> nameToMinutes = new HashMap<>();\n\n for (int i = 0; i < keyName.length; i++) {\n final int minutes = getMinutes(keyTime[i]);\n nameToMinutes.putIfAbsent(keyName[i], new ArrayList<>());\n nameToMinutes.get(keyName[i]).add(minutes);\n }\n\n for (Map.Entry> entry : nameToMinutes.entrySet()) {\n final String name = entry.getKey();\n List minutes = entry.getValue();\n if (hasAlert(minutes))\n ans.add(name);\n }\n\n Collections.sort(ans);\n return ans;\n }\n\n private boolean hasAlert(List minutes) {\n if (minutes.size() > 70)\n return true;\n Collections.sort(minutes);\n for (int i = 2; i < minutes.size(); i++)\n if (minutes.get(i - 2) + 60 >= minutes.get(i))\n return true;\n return false;\n }\n\n private int getMinutes(String time) {\n final int h = Integer.parseInt(time.substring(0, 2));\n final int m = Integer.parseInt(time.substring(3));\n return 60 * h + m;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector alertNames(vector& keyName, vector& keyTime) {\n vector ans;\n unordered_map> nameToMinutes;\n\n for (int i = 0; i < keyName.size(); ++i) {\n const int minutes = getMinutes(keyTime[i]);\n nameToMinutes[keyName[i]].push_back(minutes);\n }\n\n for (auto& [name, minutes] : nameToMinutes)\n if (hasAlert(minutes))\n ans.push_back(name);\n\n ranges::sort(ans);\n return ans;\n }\n\n private:\n // Returns true if any worker uses the key-card three or more times in an\n // one-hour period.\n bool hasAlert(vector& minutes) {\n if (minutes.size() > 70)\n return true;\n ranges::sort(minutes);\n for (int i = 2; i < minutes.size(); ++i)\n if (minutes[i - 2] + 60 >= minutes[i])\n return true;\n return false;\n }\n\n int getMinutes(const string& time) {\n const int h = stoi(time.substr(0, 2));\n const int m = stoi(time.substr(3));\n return 60 * h + m;\n }\n};\n"} +{"task_num": 1615, "task_title": "Maximal Network Rank", "difficulty": 2, "func_name": "maximalNetworkRank", "description": "There is an infrastructure of `n` cities with some number of `roads`\nconnecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a\nbidirectional road between cities `ai` and `bi`.\n\nThe network rank of two different cities is defined as the total number of\ndirectly connected roads to either city. If a road is directly connected to\nboth cities, it is only counted once.\n\nThe maximal network rank of the infrastructure is the maximum network rank of\nall pairs of different cities.\n\nGiven the integer `n` and the array `roads`, return the maximal network rank\nof the entire infrastructure.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:\n degrees = [0] * n\n\n for u, v in roads:\n degrees[u] += 1\n degrees[v] += 1\n\n maxDegree1 = 0\n maxDegree2 = 0\n for degree in degrees:\n if degree > maxDegree1:\n maxDegree2 = maxDegree1\n maxDegree1 = degree\n elif degree > maxDegree2:\n maxDegree2 = degree\n\n countMaxDegree1 = 0\n countMaxDegree2 = 0\n for degree in degrees:\n if degree == maxDegree1:\n countMaxDegree1 += 1\n elif degree == maxDegree2:\n countMaxDegree2 += 1\n\n if countMaxDegree1 == 1:\n edgeCount = self._getEdgeCount(roads, degrees, maxDegree1, maxDegree2) + self._getEdgeCount(roads, degrees, maxDegree2, maxDegree1)\n return maxDegree1 + maxDegree2 - (countMaxDegree2 == edgeCount)\n else:\n edgeCount = self._getEdgeCount(roads, degrees, maxDegree1, maxDegree1)\n maxPossibleEdgeCount = countMaxDegree1 * (countMaxDegree1 - 1) // 2\n return 2 * maxDegree1 - (maxPossibleEdgeCount == edgeCount)\n\n def _getEdgeCount(self, roads: List[List[int]], degrees: List[int], degreeU: int, degreeV: int) -> int:\n edgeCount = 0\n for u, v in roads:\n if degrees[u] == degreeU and degrees[v] == degreeV:\n edgeCount += 1\n return edgeCount\n", "java_solution": "class Solution {\n public int maximalNetworkRank(int n, int[][] roads) {\n int[] degrees = new int[n];\n\n for (int[] road : roads) {\n final int u = road[0];\n final int v = road[1];\n ++degrees[u];\n ++degrees[v];\n }\n\n // Find the first maximum and the second maximum degrees.\n int maxDegree1 = 0;\n int maxDegree2 = 0;\n for (final int degree : degrees)\n if (degree > maxDegree1) {\n maxDegree2 = maxDegree1;\n maxDegree1 = degree;\n } else if (degree > maxDegree2) {\n maxDegree2 = degree;\n }\n\n // There can be multiple nodes with `maxDegree1` or `maxDegree2`.\n // Find the counts of such nodes.\n int countMaxDegree1 = 0;\n int countMaxDegree2 = 0;\n for (final int degree : degrees)\n if (degree == maxDegree1)\n ++countMaxDegree1;\n else if (degree == maxDegree2)\n ++countMaxDegree2;\n\n if (countMaxDegree1 == 1) {\n // 1. If there is only one node with degree = `maxDegree1`, then we'll\n // need to use the node with degree = `maxDegree2`. The answer in general\n // will be (maxDegree1 + maxDegree2), but if the two nodes that we're\n // considering are connected, then we'll have to subtract 1.\n final int edgeCount = getEdgeCount(roads, degrees, maxDegree1, maxDegree2) +\n getEdgeCount(roads, degrees, maxDegree2, maxDegree1);\n return maxDegree1 + maxDegree2 - (countMaxDegree2 == edgeCount ? 1 : 0);\n } else {\n // 2. If there are more than one node with degree = `maxDegree1`, then we\n // can consider `maxDegree1` twice, and we don't need to use `maxDegree2`.\n // The answer in general will be 2 * maxDegree1, but if the two nodes that\n // we're considering are connected, then we'll have to subtract 1.\n final int edgeCount = getEdgeCount(roads, degrees, maxDegree1, maxDegree1);\n final int maxPossibleEdgeCount = countMaxDegree1 * (countMaxDegree1 - 1) / 2;\n return 2 * maxDegree1 - (maxPossibleEdgeCount == edgeCount ? 1 : 0);\n }\n }\n\n // Returns the number of edges (u, v) where degress[u] == degreeU and\n // degrees[v] == degreeV.\n private int getEdgeCount(int[][] roads, int[] degrees, int degreeU, int degreeV) {\n int edgeCount = 0;\n for (int[] road : roads) {\n final int u = road[0];\n final int v = road[1];\n if (degrees[u] == degreeU && degrees[v] == degreeV)\n ++edgeCount;\n }\n return edgeCount;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int maximalNetworkRank(int n, vector>& roads) {\n vector degrees(n);\n\n for (const vector& road : roads) {\n const int u = road[0];\n const int v = road[1];\n ++degrees[u];\n ++degrees[v];\n }\n\n // Find the first maximum and the second maximum degrees.\n int maxDegree1 = 0;\n int maxDegree2 = 0;\n for (const int degree : degrees) {\n if (degree > maxDegree1) {\n maxDegree2 = maxDegree1;\n maxDegree1 = degree;\n } else if (degree > maxDegree2) {\n maxDegree2 = degree;\n }\n }\n\n // There can be multiple nodes with `maxDegree1` or `maxDegree2`.\n // Find the counts of such nodes.\n int countMaxDegree1 = 0;\n int countMaxDegree2 = 0;\n for (const int degree : degrees)\n if (degree == maxDegree1)\n ++countMaxDegree1;\n else if (degree == maxDegree2)\n ++countMaxDegree2;\n\n if (countMaxDegree1 == 1) {\n // 1. If there is only one node with degree = `maxDegree1`, then we'll\n // need to use the node with degree = `maxDegree2`. The answer in general\n // will be (maxDegree1 + maxDegree2), but if the two nodes that we're\n // considering are connected, then we'll have to subtract 1.\n const int edgeCount =\n getEdgeCount(roads, degrees, maxDegree1, maxDegree2) +\n getEdgeCount(roads, degrees, maxDegree2, maxDegree1);\n return maxDegree1 + maxDegree2 - (countMaxDegree2 == edgeCount ? 1 : 0);\n } else {\n // 2. If there are more than one node with degree = `maxDegree1`, then we\n // can consider `maxDegree1` twice, and we don't need to use `maxDegree2`.\n // The answer in general will be 2 * maxDegree1, but if the two nodes that\n // we're considering are connected, then we'll have to subtract 1.\n const int edgeCount =\n getEdgeCount(roads, degrees, maxDegree1, maxDegree1);\n const int maxPossibleEdgeCount =\n countMaxDegree1 * (countMaxDegree1 - 1) / 2;\n return 2 * maxDegree1 - (maxPossibleEdgeCount == edgeCount ? 1 : 0);\n }\n }\n\n private:\n // Returns the number of edges (u, v) where degress[u] == degreeU and\n // degrees[v] == degreeV.\n int getEdgeCount(const vector>& roads, const vector& degrees,\n int degreeU, int degreeV) {\n int edgeCount = 0;\n for (const vector& road : roads) {\n const int u = road[0];\n const int v = road[1];\n if (degrees[u] == degreeU && degrees[v] == degreeV)\n ++edgeCount;\n }\n return edgeCount;\n }\n};\n"} +{"task_num": 1616, "task_title": "Split Two Strings to Make Palindrome", "difficulty": 2, "func_name": "checkPalindromeFormation", "description": "You are given two strings `a` and `b` of the same length. Choose an index and\nsplit both strings at the same index, splitting `a` into two strings:\n`aprefix` and `asuffix` where `a = aprefix + asuffix`, and splitting `b` into\ntwo strings: `bprefix` and `bsuffix` where `b = bprefix + bsuffix`. Check if\n`aprefix + bsuffix` or `bprefix + asuffix` forms a palindrome.\n\nWhen you split a string `s` into `sprefix` and `ssuffix`, either `ssuffix` or\n`sprefix` is allowed to be empty. For example, if `s = \"abc\"`, then `\"\" +\n\"abc\"`, `\"a\" + \"bc\"`, `\"ab\" + \"c\"` , and `\"abc\" + \"\"` are valid splits.\n\nReturn `true` if it is possible to form a palindrome string, otherwise return\n`false`.\n\nNotice that `x + y` denotes the concatenation of strings `x` and `y`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def checkPalindromeFormation(self, a: str, b: str) -> bool:\n return self._check(a, b) or self._check(b, a)\n\n def _check(self, a: str, b: str) -> bool:\n i, j = 0, len(a) - 1\n while i < j:\n if a[i] != b[j]:\n return self._isPalindrome(a, i, j) or self._isPalindrome(b, i, j)\n i += 1\n j -= 1\n return True\n\n def _isPalindrome(self, s: str, i: int, j: int) -> bool:\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n", "java_solution": "class Solution {\n public boolean checkPalindromeFormation(String a, String b) {\n return check(a, b) || check(b, a);\n }\n\n private boolean check(String a, String b) {\n for (int i = 0, j = a.length() - 1; i < j; ++i, --j)\n if (a.charAt(i) != b.charAt(j))\n // a[0:i] + a[i..j] + b[j + 1:] or\n // a[0:i] + b[i..j] + b[j + 1:]\n return isPalindrome(a, i, j) || isPalindrome(b, i, j);\n return true;\n }\n\n private boolean isPalindrome(String s, int i, int j) {\n while (i < j)\n if (s.charAt(i++) != s.charAt(j--))\n return false;\n return true;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool checkPalindromeFormation(string a, string b) {\n return check(a, b) || check(b, a);\n }\n\n private:\n bool check(const string& a, const string& b) {\n for (int i = 0, j = a.length() - 1; i < j; ++i, --j)\n if (a[i] != b[j])\n // a[0:i] + a[i..j] + b[j + 1:] or\n // a[0:i] + b[i..j] + b[j + 1:]\n return isPalindrome(a, i, j) || isPalindrome(b, i, j);\n return true;\n }\n\n bool isPalindrome(const string& s, int i, int j) {\n while (i < j)\n if (s[i++] != s[j--])\n return false;\n return true;\n }\n};\n"} +{"task_num": 1617, "task_title": "Count Subtrees With Max Distance Between Cities", "difficulty": 3, "func_name": "countSubgraphsForEachDiameter", "description": "There are `n` cities numbered from `1` to `n`. You are given an array `edges`\nof size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge\nbetween cities `ui` and `vi`. There exists a unique path between each pair of\ncities. In other words, the cities form a tree.\n\nA subtree is a subset of cities where every city is reachable from every other\ncity in the subset, where the path between each pair passes through only the\ncities from the subset. Two subtrees are different if there is a city in one\nsubtree that is not present in the other.\n\nFor each `d` from `1` to `n-1`, find the number of subtrees in which the\nmaximum distance between any two cities in the subtree is equal to `d`.\n\nReturn an array of size `n-1` where the `dth` element (1-indexed) is the\nnumber of subtrees in which the maximum distance between any two cities is\nequal to `d`.\n\nNotice that the distance between the two cities is the number of edges in the\npath between them.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n maxMask = 1 << n\n dist = self._floydWarshall(n, edges)\n ans = [0] * (n - 1)\n\n for mask in range(maxMask):\n maxDist = self._getMaxDist(mask, dist, n)\n if maxDist > 0:\n ans[maxDist - 1] += 1\n\n return ans\n\n def _floydWarshall(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n dist = [[n] * n for _ in range(n)]\n\n for i in range(n):\n dist[i][i] = 0\n\n for u, v in edges:\n dist[u - 1][v - 1] = 1\n dist[v - 1][u - 1] = 1\n\n for k in range(n):\n for i in range(n):\n for j in range(n):\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n\n return dist\n\n def _getMaxDist(self, mask: int, dist: List[List[int]], n: int) -> int:\n maxDist = 0\n edgeCount = 0\n cityCount = 0\n for u in range(n):\n if (mask >> u) & 1 == 0:\n continue\n cityCount += 1\n for v in range(u + 1, n):\n if (mask >> v) & 1 == 0:\n continue\n if dist[u][v] == 1:\n edgeCount += 1\n maxDist = max(maxDist, dist[u][v])\n\n if edgeCount == cityCount - 1:\n return maxDist\n else:\n return 0\n", "java_solution": "class Solution {\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n final int maxMask = 1 << n;\n final int[][] dist = floydWarshall(n, edges);\n int[] ans = new int[n - 1];\n\n // mask := the subset of the cities\n for (int mask = 0; mask < maxMask; ++mask) {\n int maxDist = getMaxDist(mask, dist, n);\n if (maxDist > 0)\n ++ans[maxDist - 1];\n }\n\n return ans;\n }\n\n private int[][] floydWarshall(int n, int[][] edges) {\n int[][] dist = new int[n][n];\n for (int i = 0; i < n; ++i)\n Arrays.fill(dist[i], n);\n\n for (int i = 0; i < n; ++i)\n dist[i][i] = 0;\n\n for (int[] edge : edges) {\n final int u = edge[0] - 1;\n final int v = edge[1] - 1;\n dist[u][v] = 1;\n dist[v][u] = 1;\n }\n\n for (int k = 0; k < n; ++k)\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);\n\n return dist;\n }\n\n private int getMaxDist(int mask, int[][] dist, int n) {\n int maxDist = 0;\n int edgeCount = 0;\n int cityCount = 0;\n for (int u = 0; u < n; ++u) {\n if ((mask >> u & 1) == 0) // u is not in the subset.\n continue;\n ++cityCount;\n for (int v = u + 1; v < n; ++v) {\n if ((mask >> v & 1) == 0) // v is not in the subset.\n continue;\n if (dist[u][v] == 1) // u and v are connected.\n ++edgeCount;\n maxDist = Math.max(maxDist, dist[u][v]);\n }\n }\n return edgeCount == cityCount - 1 ? maxDist : 0;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector countSubgraphsForEachDiameter(int n, vector>& edges) {\n const int maxMask = 1 << n;\n const vector> dist = floydWarshall(n, edges);\n vector ans(n - 1);\n\n // mask := the subset of the cities\n for (int mask = 0; mask < maxMask; ++mask) {\n const int maxDist = getMaxDist(mask, dist, n);\n if (maxDist > 0)\n ++ans[maxDist - 1];\n }\n\n return ans;\n }\n\n private:\n vector> floydWarshall(int n, const vector>& edges) {\n vector> dist(n, vector(n, n));\n\n for (int i = 0; i < n; ++i)\n dist[i][i] = 0;\n\n for (const vector& edge : edges) {\n const int u = edge[0] - 1;\n const int v = edge[1] - 1;\n dist[u][v] = 1;\n dist[v][u] = 1;\n }\n\n for (int k = 0; k < n; ++k)\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n\n return dist;\n }\n\n int getMaxDist(int mask, const vector>& dist, int n) {\n int maxDist = 0;\n int edgeCount = 0;\n int cityCount = 0;\n for (int u = 0; u < n; ++u) {\n if ((mask >> u & 1) == 0) // u is not in the subset.\n continue;\n ++cityCount;\n for (int v = u + 1; v < n; ++v) {\n if ((mask >> v & 1) == 0) // v is not in the subset.\n continue;\n if (dist[u][v] == 1) // u and v are connected.\n ++edgeCount;\n maxDist = max(maxDist, dist[u][v]);\n }\n }\n return edgeCount == cityCount - 1 ? maxDist : 0;\n }\n};\n"} +{"task_num": 1627, "task_title": "Graph Connectivity With Threshold", "difficulty": 3, "func_name": "areConnected", "description": "We have `n` cities labeled from `1` to `n`. Two different cities with labels\n`x` and `y` are directly connected by a bidirectional road if and only if `x`\nand `y` share a common divisor strictly greater than some `threshold`. More\nformally, cities with labels `x` and `y` have a road between them if there\nexists an integer `z` such that all of the following are true:\n\n* `x % z == 0`,\n* `y % z == 0`, and\n* `z > threshold`.\n\nGiven the two integers, `n` and `threshold`, and an array of `queries`, you\nmust determine for each `queries[i] = [ai, bi]` if cities `ai` and `bi` are\nconnected directly or indirectly. (i.e. there is some path between them).\n\nReturn an array `answer`, where `answer.length == queries.length` and\n`answer[i]` is `true` if for the `ith` query, there is a path between `ai` and\n`bi`, or `answer[i]` is `false` if there is no path.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> bool:\n i = self.find(u)\n j = self.find(v)\n if i == j:\n return False\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n return True\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n uf = UnionFind(n + 1)\n\n for z in range(threshold + 1, n + 1):\n for x in range(z * 2, n + 1, z):\n uf.unionByRank(z, x)\n\n return [uf.find(a) == uf.find(b) for a, b in queries]\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public boolean unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return false;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n return true;\n }\n\n public int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n\n private int[] id;\n private int[] rank;\n}\n\nclass Solution {\n public List areConnected(int n, int threshold, int[][] queries) {\n List ans = new ArrayList<>();\n UnionFind uf = new UnionFind(n + 1);\n\n for (int z = threshold + 1; z <= n; ++z)\n for (int x = z * 2; x <= n; x += z)\n uf.unionByRank(z, x);\n\n for (int[] query : queries) {\n final int a = query[0];\n final int b = query[1];\n ans.add(uf.find(a) == uf.find(b));\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n), rank(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n bool unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return false;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n return true;\n }\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n\n private:\n vector id;\n vector rank;\n};\n\nclass Solution {\n public:\n vector areConnected(int n, int threshold,\n vector>& queries) {\n vector ans;\n UnionFind uf(n + 1);\n\n for (int z = threshold + 1; z <= n; ++z)\n for (int x = z * 2; x <= n; x += z)\n uf.unionByRank(z, x);\n\n for (const vector& query : queries) {\n const int a = query[0];\n const int b = query[1];\n ans.push_back(uf.find(a) == uf.find(b));\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1631, "task_title": "Path With Minimum Effort", "difficulty": 2, "func_name": "minimumEffortPath", "description": "You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D\narray of size `rows x columns`, where `heights[row][col]` represents the\nheight of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`,\nand you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e.,\n0-indexed). You can move up, down, left, or right, and you wish to find a\nroute that requires the minimum effort.\n\nA route's effort is the maximum absolute difference in heights between two\nconsecutive cells of the route.\n\nReturn the minimum effort required to travel from the top-left cell to the\nbottom-right cell.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumEffortPath(self, heights: List[List[int]]) -> int:\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(heights)\n n = len(heights[0])\n diff = [[math.inf] * n for _ in range(m)]\n seen = set()\n\n minHeap = [(0, 0, 0)]\n diff[0][0] = 0\n\n while minHeap:\n d, i, j = heapq.heappop(minHeap)\n if i == m - 1 and j == n - 1:\n return d\n seen.add((i, j))\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if (x, y) in seen:\n continue\n newDiff = abs(heights[i][j] - heights[x][y])\n maxDiff = max(diff[i][j], newDiff)\n if diff[x][y] > maxDiff:\n diff[x][y] = maxDiff\n heapq.heappush(minHeap, (diff[x][y], x, y))\n", "java_solution": "class Solution {\n public int minimumEffortPath(int[][] heights) {\n // d := the maximum difference of (i, j) and its neighbors\n record T(int i, int j, int d) {}\n final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n final int m = heights.length;\n final int n = heights[0].length;\n Queue minHeap = new PriorityQueue<>(Comparator.comparingInt(T::d));\n // dist[i][j] := the maximum absolute difference to reach (i, j)\n int[][] diff = new int[m][n];\n Arrays.stream(diff).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));\n boolean[][] seen = new boolean[m][n];\n\n minHeap.offer(new T(0, 0, 0));\n diff[0][0] = 0;\n\n while (!minHeap.isEmpty()) {\n final int i = minHeap.peek().i;\n final int j = minHeap.peek().j;\n final int d = minHeap.poll().d;\n if (i == m - 1 && j == n - 1)\n return d;\n seen[i][j] = true;\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n final int newDiff = Math.abs(heights[i][j] - heights[x][y]);\n final int maxDiff = Math.max(diff[i][j], newDiff);\n if (diff[x][y] > maxDiff) {\n diff[x][y] = maxDiff;\n minHeap.offer(new T(x, y, maxDiff));\n }\n }\n }\n\n throw new IllegalArgumentException();\n }\n}\n", "cpp_solution": "struct T {\n int i;\n int j;\n int d; // the maximum difference of (i, j) and its neighbors\n};\n\nclass Solution {\n public:\n int minimumEffortPath(vector>& heights) {\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n const int m = heights.size();\n const int n = heights[0].size();\n auto compare = [](const T& a, const T& b) { return a.d > b.d; };\n priority_queue, decltype(compare)> minHeap(compare);\n // diff[i][j] := the maximum absolute difference to reach (i, j)\n vector> diff(m, vector(n, INT_MAX));\n vector> seen(m, vector(n));\n\n minHeap.emplace(0, 0, 0);\n diff[0][0] = 0;\n\n while (!minHeap.empty()) {\n const auto [i, j, d] = minHeap.top();\n minHeap.pop();\n if (i == m - 1 && j == n - 1)\n return d;\n seen[i][j] = true;\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n const int newDiff = abs(heights[i][j] - heights[x][y]);\n const int maxDiff = max(diff[i][j], newDiff);\n if (diff[x][y] > maxDiff) {\n diff[x][y] = maxDiff;\n minHeap.emplace(x, y, maxDiff);\n }\n }\n }\n\n throw;\n }\n};\n"} +{"task_num": 1632, "task_title": "Rank Transform of a Matrix", "difficulty": 3, "func_name": "matrixRankTransform", "description": "Given an `m x n` `matrix`, return a new matrix `answer` where\n`answer[row][col]` is the rank of `matrix[row][col]`.\n\nThe rank is an integer that represents how large an element is compared to\nother elements. It is calculated using the following rules:\n\n* The rank is an integer starting from `1`.\n* If two elements `p` and `q` are in the same row or column, then: \n* If `p < q` then `rank(p) < rank(q)`\n* If `p == q` then `rank(p) == rank(q)`\n* If `p > q` then `rank(p) > rank(q)`\n* The rank should be as small as possible.\n\nThe test cases are generated so that `answer` is unique under the given rules.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self):\n self.id = {}\n\n def union(self, u: int, v: int) -> None:\n self.id.setdefault(u, u)\n self.id.setdefault(v, v)\n i = self._find(u)\n j = self._find(v)\n if i != j:\n self.id[i] = j\n\n def getGroupIdToValues(self) -> Dict[int, List[int]]:\n groupIdToValues = collections.defaultdict(list)\n for u in self.id.keys():\n groupIdToValues[self._find(u)].append(u)\n return groupIdToValues\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]:\n m = len(matrix)\n n = len(matrix[0])\n ans = [[0] * n for _ in range(m)]\n valToGrids = collections.defaultdict(list)\n maxRankSoFar = [0] * (m + n)\n\n for i, row in enumerate(matrix):\n for j, val in enumerate(row):\n valToGrids[val].append((i, j))\n\n for _, grids in sorted(valToGrids.items()):\n uf = UnionFind()\n for i, j in grids:\n uf.union(i, j + m)\n for values in uf.getGroupIdToValues().values():\n maxRank = max(maxRankSoFar[i] for i in values)\n for i in values:\n maxRankSoFar[i] = maxRank + 1\n for i, j in grids:\n ans[i][j] = maxRankSoFar[i]\n\n return ans\n", "java_solution": "class UnionFind {\n public void union(int u, int v) {\n id.putIfAbsent(u, u);\n id.putIfAbsent(v, v);\n final int i = find(u);\n final int j = find(v);\n if (i != j)\n id.put(i, j);\n }\n\n public Map> getGroupIdToValues() {\n Map> groupIdToValues = new HashMap<>();\n for (Map.Entry entry : id.entrySet()) {\n final int u = entry.getKey();\n final int i = find(u);\n groupIdToValues.putIfAbsent(i, new ArrayList<>());\n groupIdToValues.get(i).add(u);\n }\n return groupIdToValues;\n }\n\n private Map id = new HashMap<>();\n\n private int find(int u) {\n return id.getOrDefault(u, u) == u ? u : find(id.get(u));\n }\n}\n\nclass Solution {\n public int[][] matrixRankTransform(int[][] matrix) {\n final int m = matrix.length;\n final int n = matrix[0].length;\n int[][] ans = new int[m][n];\n // {val: [(i, j)]}\n TreeMap>> valToGrids = new TreeMap<>();\n // rank[i] := the maximum rank of the row or column so far\n int[] maxRankSoFar = new int[m + n];\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j) {\n final int val = matrix[i][j];\n valToGrids.putIfAbsent(val, new ArrayList<>());\n valToGrids.get(val).add(new Pair<>(i, j));\n }\n\n for (Map.Entry>> entry : valToGrids.entrySet()) {\n final int val = entry.getKey();\n List> grids = entry.getValue();\n UnionFind uf = new UnionFind();\n for (Pair grid : grids) {\n final int i = grid.getKey();\n final int j = grid.getValue();\n // Union i-th row with j-th col.\n uf.union(i, j + m);\n }\n for (List values : uf.getGroupIdToValues().values()) {\n // Get the maximum rank of all the included rows and columns.\n int maxRank = 0;\n for (final int i : values)\n maxRank = Math.max(maxRank, maxRankSoFar[i]);\n // Update all the rows and columns to maxRank + 1.\n for (final int i : values)\n maxRankSoFar[i] = maxRank + 1;\n }\n for (Pair grid : grids) {\n final int i = grid.getKey();\n final int j = grid.getValue();\n ans[i][j] = maxRankSoFar[i];\n }\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n void union_(int u, int v) {\n if (!id.contains(u))\n id[u] = u;\n if (!id.contains(v))\n id[v] = v;\n const int i = find(u);\n const int j = find(v);\n if (i != j)\n id[i] = j;\n }\n\n unordered_map> getGroupIdToValues() {\n unordered_map> groupIdToValues;\n for (const auto& [u, _] : id)\n groupIdToValues[find(u)].push_back(u);\n return groupIdToValues;\n }\n\n private:\n unordered_map id;\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n};\n\nclass Solution {\n public:\n vector> matrixRankTransform(vector>& matrix) {\n const int m = matrix.size();\n const int n = matrix[0].size();\n vector> ans(m, vector(n));\n // {val: [(i, j)]}\n map>> valToGrids;\n // rank[i] := the maximum rank of the row or column so far\n vector maxRankSoFar(m + n);\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n valToGrids[matrix[i][j]].emplace_back(i, j);\n\n for (const auto& [val, grids] : valToGrids) {\n UnionFind uf;\n for (const auto& [i, j] : grids)\n // Union i-th row with j-th col.\n uf.union_(i, j + m);\n for (const auto& [groupId, values] : uf.getGroupIdToValues()) {\n // Get the maximum rank of all the included rows and columns.\n int maxRank = 0;\n for (const int i : values)\n maxRank = max(maxRank, maxRankSoFar[i]);\n // Update all the rows and columns to maxRank + 1.\n for (const int i : values)\n maxRankSoFar[i] = maxRank + 1;\n }\n for (const auto& [i, j] : grids)\n ans[i][j] = maxRankSoFar[i];\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1654, "task_title": "Minimum Jumps to Reach Home", "difficulty": 2, "func_name": "minimumJumps", "description": "A certain bug's home is on the x-axis at position `x`. Help them get there\nfrom position `0`.\n\nThe bug jumps according to the following rules:\n\n* It can jump exactly `a` positions forward (to the right).\n* It can jump exactly `b` positions backward (to the left).\n* It cannot jump backward twice in a row.\n* It cannot jump to any `forbidden` positions.\n\nThe bug may jump forward beyond its home, but it cannot jump to positions\nnumbered with negative integers.\n\nGiven an array of integers `forbidden`, where `forbidden[i]` means that the\nbug cannot jump to the position `forbidden[i]`, and integers `a`, `b`, and\n`x`, return the minimum number of jumps needed for the bug to reach its home.\nIf there is no possible sequence of jumps that lands the bug on position `x`,\nreturn `-1.`\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nfrom enum import Enum\n\n\nclass Direction(Enum):\n kForward = 0\n kBackward = 1\n\n\nclass Solution:\n def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:\n furthest = max(x + a + b, max(pos + a + b for pos in forbidden))\n seenForward = {pos for pos in forbidden}\n seenBackward = {pos for pos in forbidden}\n\n q = collections.deque([(Direction.kForward, 0)])\n\n ans = 0\n while q:\n for _ in range(len(q)):\n dir, pos = q.popleft()\n if pos == x:\n return ans\n forward = pos + a\n backward = pos - b\n if forward <= furthest and forward not in seenForward:\n seenForward.add(forward)\n q.append((Direction.kForward, forward))\n if dir == Direction.kForward and backward >= 0 and backward not in seenBackward:\n seenBackward.add(backward)\n q.append((Direction.kBackward, backward))\n ans += 1\n\n return -1\n", "java_solution": "enum Direction { FORWARD, BACKWARD }\n\nclass Solution {\n public int minimumJumps(int[] forbidden, int a, int b, int x) {\n int furthest = x + a + b;\n Set seenForward = new HashSet<>();\n Set seenBackward = new HashSet<>();\n\n for (final int pos : forbidden) {\n seenForward.add(pos);\n seenBackward.add(pos);\n furthest = Math.max(furthest, pos + a + b);\n }\n\n // (direction, position)\n Queue> q = new ArrayDeque<>(List.of(new Pair<>(Direction.FORWARD, 0)));\n\n for (int ans = 0; !q.isEmpty(); ++ans)\n for (int sz = q.size(); sz > 0; --sz) {\n Direction dir = q.peek().getKey();\n final int pos = q.poll().getValue();\n if (pos == x)\n return ans;\n final int forward = pos + a;\n final int backward = pos - b;\n if (forward <= furthest && seenForward.add(forward))\n q.offer(new Pair<>(Direction.FORWARD, forward));\n // It cannot jump backward twice in a row.\n if (dir == Direction.FORWARD && backward >= 0 && seenBackward.add(backward))\n q.offer(new Pair<>(Direction.BACKWARD, backward));\n }\n\n return -1;\n }\n}\n", "cpp_solution": "enum class Direction { kForward, kBackward };\n\nclass Solution {\n public:\n int minimumJumps(vector& forbidden, int a, int b, int x) {\n int furthest = x + a + b;\n unordered_set seenForward;\n unordered_set seenBackward;\n\n for (const int pos : forbidden) {\n seenForward.insert(pos);\n seenBackward.insert(pos);\n furthest = max(furthest, pos + a + b);\n }\n\n // (direction, position)\n queue> q{{{Direction::kForward, 0}}};\n\n for (int ans = 0; !q.empty(); ++ans)\n for (int sz = q.size(); sz > 0; --sz) {\n const auto [dir, pos] = q.front();\n q.pop();\n if (pos == x)\n return ans;\n const int forward = pos + a;\n const int backward = pos - b;\n if (forward <= furthest && seenForward.insert(forward).second)\n q.emplace(Direction::kForward, forward);\n // It cannot jump backward twice in a row.\n if (dir == Direction::kForward && backward >= 0 &&\n seenBackward.insert(backward).second)\n q.emplace(Direction::kBackward, backward);\n }\n\n return -1;\n }\n};\n"} +{"task_num": 1655, "task_title": "Distribute Repeating Integers", "difficulty": 3, "func_name": "canDistribute", "description": "You are given an array of `n` integers, `nums`, where there are at most `50`\nunique values in the array. You are also given an array of `m` customer order\nquantities, `quantity`, where `quantity[i]` is the amount of integers the\n`ith` customer ordered. Determine if it is possible to distribute `nums` such\nthat:\n\n* The `ith` customer gets exactly `quantity[i]` integers,\n* The integers the `ith` customer gets are all equal, and\n* Every customer is satisfied.\n\nReturn `true` if it is possible to distribute `nums` according to the above\nconditions.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def canDistribute(self, nums: List[int], quantity: List[int]) -> bool:\n freqs = list(collections.Counter(nums).values())\n validDistribution = self._getValidDistribution(freqs, quantity)\n n = len(freqs)\n m = len(quantity)\n maxMask = 1 << m\n dp = [[False] * maxMask for _ in range(n + 1)]\n dp[n][maxMask - 1] = True\n\n for i in range(n - 1, -1, -1):\n for mask in range(maxMask):\n dp[i][mask] = dp[i + 1][mask]\n availableMask = ~mask & (maxMask - 1)\n submask = availableMask\n while submask > 0:\n if validDistribution[i][submask]:\n dp[i][mask] = dp[i][mask] or dp[i + 1][mask | submask]\n submask = (submask - 1) & availableMask\n\n return dp[0][0]\n\n def _getValidDistribution(self, freqs: List[int], quantity: List[int]) -> List[List[bool]]:\n maxMask = 1 << len(quantity)\n validDistribution = [[False] * maxMask for _ in range(len(freqs))]\n for i, freq in enumerate(freqs):\n for mask in range(maxMask):\n if freq >= self._getQuantitySum(quantity, mask):\n validDistribution[i][mask] = True\n return validDistribution\n\n def _getQuantitySum(self, quantity: List[int], mask: int) -> int:\n res=[]\n for i, q in enumerate(quantity):\n if mask >> i & 1:\n res.append(q)\n return sum(res)\n", "java_solution": "class Solution {\n public boolean canDistribute(int[] nums, int[] quantity) {\n List freqs = getFreqs(nums);\n // validDistribution[i][j] := true if it's possible to distribute the i-th\n // freq into a subset of quantity represented by the bitmask j\n boolean[][] validDistribution = getValidDistribution(freqs, quantity);\n final int n = freqs.size();\n final int m = quantity.length;\n final int maxMask = 1 << m;\n // dp[i][j] := true if it's possible to distribute freqs[i..n), where j is\n // the bitmask of the selected quantity\n boolean[][] dp = new boolean[n + 1][maxMask];\n dp[n][maxMask - 1] = true;\n\n for (int i = n - 1; i >= 0; --i)\n for (int mask = 0; mask < maxMask; ++mask) {\n dp[i][mask] = dp[i + 1][mask];\n final int availableMask = ~mask & (maxMask - 1);\n for (int submask = availableMask; submask > 0; submask = (submask - 1) & availableMask)\n if (validDistribution[i][submask])\n dp[i][mask] = dp[i][mask] || dp[i + 1][mask | submask];\n }\n\n return dp[0][0];\n }\n\n private List getFreqs(int[] nums) {\n List freqs = new ArrayList<>();\n Map count = new HashMap<>();\n for (final int num : nums)\n count.merge(num, 1, Integer::sum);\n return new ArrayList<>(count.values());\n }\n\n boolean[][] getValidDistribution(List freqs, int[] quantity) {\n final int maxMask = 1 << quantity.length;\n boolean[][] validDistribution = new boolean[freqs.size()][maxMask];\n for (int i = 0; i < freqs.size(); ++i)\n for (int mask = 0; mask < maxMask; ++mask)\n if (freqs.get(i) >= getQuantitySum(quantity, mask))\n validDistribution[i][mask] = true;\n return validDistribution;\n }\n\n // Returns the sum of the selected quantity represented by `mask`.\n int getQuantitySum(int[] quantity, int mask) {\n int sum = 0;\n for (int i = 0; i < quantity.length; ++i)\n if ((mask >> i & 1) == 1)\n sum += quantity[i];\n return sum;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool canDistribute(vector& nums, vector& quantity) {\n // validDistribution[i][j] := true if it's possible to distribute the i-th\n // freq into a subset of quantity represented by the bitmask j\n const vector freqs = getFreqs(nums);\n const vector> validDistribution =\n getValidDistribuition(freqs, quantity);\n const int n = freqs.size();\n const int m = quantity.size();\n const int maxMask = 1 << m;\n // dp[i][j] := true if it's possible to distribute freqs[i..n), where j is\n // the bitmask of the selected quantity\n vector> dp(n + 1, vector(maxMask));\n dp[n][maxMask - 1] = true;\n\n for (int i = n - 1; i >= 0; --i)\n for (int mask = 0; mask < maxMask; ++mask) {\n dp[i][mask] = dp[i + 1][mask];\n const int availableMask = ~mask & (maxMask - 1);\n for (int submask = availableMask; submask > 0;\n submask = (submask - 1) & availableMask)\n if (validDistribution[i][submask])\n dp[i][mask] = dp[i][mask] || dp[i + 1][mask | submask];\n }\n\n return dp[0][0];\n }\n\n private:\n vector getFreqs(const vector& nums) {\n vector freqs;\n unordered_map count;\n for (const int num : nums)\n ++count[num];\n for (const auto& [_, freq] : count)\n freqs.push_back(freq);\n return freqs;\n }\n\n vector> getValidDistribuition(const vector& freqs,\n const vector& quantity) {\n const int maxMask = 1 << quantity.size();\n vector> validDistribution(freqs.size(), vector(maxMask));\n for (int i = 0; i < freqs.size(); ++i)\n for (int mask = 0; mask < maxMask; ++mask)\n if (freqs[i] >= getQuantitySum(quantity, mask))\n validDistribution[i][mask] = true;\n return validDistribution;\n }\n\n // Returns the sum of the selected quantity represented by `mask`.\n int getQuantitySum(const vector& quantity, int mask) {\n int sum = 0;\n for (int i = 0; i < quantity.size(); ++i)\n if (mask >> i & 1)\n sum += quantity[i];\n return sum;\n }\n};\n"} +{"task_num": 1681, "task_title": "Minimum Incompatibility", "difficulty": 3, "func_name": "minimumIncompatibility", "description": "You are given an integer array `nums`\u200b\u200b\u200b and an integer `k`. You are asked to\ndistribute this array into `k` subsets of equal size such that there are no\ntwo equal elements in the same subset.\n\nA subset's incompatibility is the difference between the maximum and minimum\nelements in that array.\n\nReturn the minimum possible sum of incompatibilities of the `k` subsets after\ndistributing the array optimally, or return `-1` if it is not possible.\n\nA subset is a group integers that appear in the array with no particular\norder.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def __init__(self):\n self.kMaxNum = 16\n\n def minimumIncompatibility(self, nums: List[int], k: int) -> int:\n kMaxCompatibility = (16 - 1) * (16 // 2)\n n = len(nums)\n subsetSize = n // k\n maxMask = 1 << n\n incompatibilities = self._getIncompatibilities(nums, subsetSize)\n\n dp = [kMaxCompatibility] * maxMask\n dp[0] = 0\n\n for mask in range(1, maxMask):\n if mask.bit_count() % subsetSize != 0:\n continue\n submask = mask\n while submask > 0:\n if incompatibilities[submask] != -1:\n dp[mask] = min(dp[mask], dp[mask - submask] + incompatibilities[submask])\n submask = (submask - 1) & mask\n\n if dp[-1] != kMaxCompatibility:\n return dp[-1]\n else:\n return -1\n\n def _getIncompatibilities(self, nums: List[int], subsetSize: int) -> List[int]:\n maxMask = 1 << len(nums)\n incompatibilities = [-1] * maxMask\n for mask in range(maxMask):\n if mask.bit_count() == subsetSize and self._isUnique(nums, mask, subsetSize):\n incompatibilities[mask] = self._getIncompatibility(nums, mask)\n return incompatibilities\n\n def _isUnique(self, nums: List[int], mask: int, subsetSize: int) -> bool:\n used = 0\n for i, num in enumerate(nums):\n if mask >> i & 1:\n used |= 1 << num\n return used.bit_count() == subsetSize\n\n def _getIncompatibility(self, nums: List[int], mask: int) -> int:\n mini = self.kMaxNum\n maxi = 0\n for i, num in enumerate(nums):\n if mask >> i & 1:\n maxi = max(maxi, num)\n mini = min(mini, num)\n return maxi - mini\n", "java_solution": "class Solution {\n public int minimumIncompatibility(int[] nums, int k) {\n final int MAX_COMPATIBILITY = (16 - 1) * (16 / 2);\n final int n = nums.length;\n final int subsetSize = n / k;\n final int maxMask = 1 << n;\n final int[] incompatibilities = getIncompatibilities(nums, subsetSize);\n // dp[i] := the minimum possible sum of incompatibilities of the subset\n // of numbers represented by the bitmask i\n int[] dp = new int[maxMask];\n Arrays.fill(dp, MAX_COMPATIBILITY);\n dp[0] = 0;\n\n for (int mask = 1; mask < maxMask; ++mask) {\n // The number of 1s in `mask` isn't a multiple of `subsetSize`.\n if (Integer.bitCount(mask) % subsetSize != 0)\n continue;\n // https://cp-algorithms.com/algebra/all-submasks.html\n for (int submask = mask; submask > 0; submask = (submask - 1) & mask)\n if (incompatibilities[submask] != -1) // valid submask\n dp[mask] = Math.min(dp[mask], dp[mask - submask] + incompatibilities[submask]);\n }\n\n return dp[maxMask - 1] == MAX_COMPATIBILITY ? -1 : dp[maxMask - 1];\n }\n\n private static final int MAX_NUM = 16;\n\n // Returns an incompatibilities array where\n // * incompatibilities[i] := the incompatibility of the subset of numbers\n // represented by the bitmask i\n // * incompatibilities[i] := -1 if the number of 1s in the bitmask i is not\n // `subsetSize`\n private int[] getIncompatibilities(int[] nums, int subsetSize) {\n final int maxMask = 1 << nums.length;\n int[] incompatibilities = new int[maxMask];\n Arrays.fill(incompatibilities, -1);\n for (int mask = 0; mask < maxMask; ++mask)\n if (Integer.bitCount(mask) == subsetSize && isUnique(nums, mask, subsetSize))\n incompatibilities[mask] = getIncompatibility(nums, mask);\n return incompatibilities;\n }\n\n // Returns true if the numbers selected by `mask` are unique.\n //\n // e.g. If we call isUnique(0b1010, 2, [1, 2, 1, 4]), `used` variable\n // will be 0b1, which only has one 1 (less than `subsetSize`). In this case,\n // we should return false.\n private boolean isUnique(int[] nums, int mask, int subsetSize) {\n int used = 0;\n for (int i = 0; i < nums.length; ++i)\n if ((mask >> i & 1) == 1)\n used |= 1 << nums[i];\n return Integer.bitCount(used) == subsetSize;\n }\n\n // Returns the incompatibility of the selected numbers represented by the\n // `mask`.\n private int getIncompatibility(int[] nums, int mask) {\n int mn = MAX_NUM;\n int mx = 0;\n for (int i = 0; i < nums.length; ++i)\n if ((mask >> i & 1) == 1) {\n mx = Math.max(mx, nums[i]);\n mn = Math.min(mn, nums[i]);\n }\n return mx - mn;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minimumIncompatibility(vector& nums, int k) {\n constexpr int kMaxCompatibility = (16 - 1) * (16 / 2);\n const int n = nums.size();\n const int subsetSize = n / k;\n const int maxMask = 1 << n;\n const vector incompatibilities =\n getIncompatibilities(nums, subsetSize);\n // dp[i] := the minimum possible sum of incompatibilities of the subset\n // of numbers represented by the bitmask i\n vector dp(maxMask, kMaxCompatibility);\n dp[0] = 0;\n\n for (unsigned mask = 1; mask < maxMask; ++mask) {\n // The number of 1s in `mask` isn't a multiple of `subsetSize`.\n if (popcount(mask) % subsetSize != 0)\n continue;\n // https://cp-algorithms.com/algebra/all-submasks.html\n for (int submask = mask; submask > 0; submask = (submask - 1) & mask)\n if (incompatibilities[submask] != -1) // valid subset\n dp[mask] =\n min(dp[mask], dp[mask - submask] + incompatibilities[submask]);\n }\n\n return dp.back() == kMaxCompatibility ? -1 : dp.back();\n }\n\n private:\n static constexpr int kMaxNum = 16;\n\n // Returns an incompatibilities array where\n // * incompatibilities[i] := the incompatibility of the subset of numbers\n // represented by the bitmask i\n // * incompatibilities[i] := -1 if the number of 1s in the bitmask i is not\n // `subsetSize`\n vector getIncompatibilities(const vector& nums, int subsetSize) {\n const int maxMask = 1 << nums.size();\n vector incompatibilities(maxMask, -1);\n for (unsigned mask = 0; mask < maxMask; ++mask)\n if (popcount(mask) == subsetSize && isUnique(nums, mask, subsetSize))\n incompatibilities[mask] = getIncompatibility(nums, mask);\n return incompatibilities;\n }\n\n // Returns true if the numbers selected by `mask` are unique.\n //\n // e.g. If we call isUnique(0b1010, 2, [1, 2, 1, 4]), `used` variable\n // will be 0b1, which only has one 1 (less than `subsetSize`). In this case,\n // we should return false.\n bool isUnique(const vector& nums, int mask, int subsetSize) {\n unsigned used = 0;\n for (int i = 0; i < nums.size(); ++i)\n if (mask >> i & 1)\n used |= 1 << nums[i];\n return popcount(used) == subsetSize;\n }\n\n // Returns the incompatibility of the selected numbers represented by the\n // `mask`.\n int getIncompatibility(const vector& nums, int mask) {\n int mn = kMaxNum;\n int mx = 0;\n for (int i = 0; i < nums.size(); ++i)\n if (mask >> i & 1) {\n mx = max(mx, nums[i]);\n mn = min(mn, nums[i]);\n }\n return mx - mn;\n }\n};\n"} +{"task_num": 1687, "task_title": "Delivering Boxes from Storage to Ports", "difficulty": 3, "func_name": "boxDelivering", "description": "You have the task of delivering some boxes from storage to their ports using\nonly one ship. However, this ship has a limit on the number of boxes and the\ntotal weight that it can carry.\n\nYou are given an array `boxes`, where `boxes[i] = [ports\u200b\u200bi\u200b, weighti]`, and\nthree integers `portsCount`, `maxBoxes`, and `maxWeight`.\n\n* `ports\u200b\u200bi` is the port where you need to deliver the `ith` box and `weightsi` is the weight of the `ith` box.\n* `portsCount` is the number of ports.\n* `maxBoxes` and `maxWeight` are the respective box and weight limits of the ship.\n\nThe boxes need to be delivered in the order they are given. The ship will\nfollow these steps:\n\n* The ship will take some number of boxes from the `boxes` queue, not violating the `maxBoxes` and `maxWeight` constraints.\n* For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered.\n* The ship then makes a return trip to storage to take more boxes from the queue.\n\nThe ship must end at storage after all the boxes have been delivered.\n\nReturn the minimum number of trips the ship needs to make to deliver all boxes\nto their respective ports.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int:\n n = len(boxes)\n dp = [0] * (n + 1)\n trips = 2\n weight = 0\n\n l = 0\n for r in range(n):\n weight += boxes[r][1]\n\n if r > 0 and boxes[r][0] != boxes[r - 1][0]:\n trips += 1\n\n while r - l + 1 > maxBoxes or weight > maxWeight or (l < r and dp[l + 1] == dp[l]):\n weight -= boxes[l][1]\n if boxes[l][0] != boxes[l + 1][0]:\n trips -= 1\n l += 1\n\n dp[r + 1] = dp[l] + trips\n\n return dp[n]\n", "java_solution": "class Solution {\n public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) {\n final int n = boxes.length;\n // dp[i] := the minimum trips to deliver boxes[0..i) and return to the\n // storage\n int[] dp = new int[n + 1];\n int trips = 2;\n int weight = 0;\n\n for (int l = 0, r = 0; r < n; ++r) {\n weight += boxes[r][1];\n\n // The current box is different from the previous one, need to make one\n // more trip.\n if (r > 0 && boxes[r][0] != boxes[r - 1][0])\n ++trips;\n\n while (r - l + 1 > maxBoxes || weight > maxWeight ||\n // Loading boxes[l] in the previous turn is always no bad than\n // loading it in this turn.\n (l < r && dp[l + 1] == dp[l])) {\n weight -= boxes[l][1];\n if (boxes[l][0] != boxes[l + 1][0])\n --trips;\n ++l;\n }\n\n // the minimum trips to deliver boxes[0..r]\n // = the minimum trips to deliver boxes[0..l) +\n // trips to deliver boxes[l..r]\n dp[r + 1] = dp[l] + trips;\n }\n\n return dp[n];\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int boxDelivering(vector>& boxes, int portsCount, int maxBoxes,\n int maxWeight) {\n const int n = boxes.size();\n // dp[i] := the minimum trips to deliver boxes[0..i) and return to the\n // storage\n vector dp(n + 1);\n int trips = 2;\n int weight = 0;\n\n for (int l = 0, r = 0; r < n; ++r) {\n weight += boxes[r][1];\n\n // The current box is different from the previous one, need to make one\n // more trip.\n if (r > 0 && boxes[r][0] != boxes[r - 1][0])\n ++trips;\n\n while (r - l + 1 > maxBoxes || weight > maxWeight ||\n // Loading boxes[l] in the previous turn is always no bad than\n // loading it in this turn.\n (l < r && dp[l + 1] == dp[l])) {\n weight -= boxes[l][1];\n if (boxes[l][0] != boxes[l + 1][0])\n --trips;\n ++l;\n }\n\n // min trips to deliver boxes[0..r]\n // = min trips to deliver boxes[0..l) + trips to deliver boxes[l..r]\n dp[r + 1] = dp[l] + trips;\n }\n\n return dp[n];\n }\n};\n"} +{"task_num": 1705, "task_title": "Maximum Number of Eaten Apples", "difficulty": 2, "func_name": "eatenApples", "description": "There is a special kind of apple tree that grows apples every day for `n`\ndays. On the `ith` day, the tree grows `apples[i]` apples that will rot after\n`days[i]` days, that is on day `i + days[i]` the apples will be rotten and\ncannot be eaten. On some days, the apple tree does not grow any apples, which\nare denoted by `apples[i] == 0` and `days[i] == 0`.\n\nYou decided to eat at most one apple a day (to keep the doctors away). Note\nthat you can keep eating after the first `n` days.\n\nGiven two integer arrays `days` and `apples` of length `n`, return the maximum\nnumber of apples you can eat.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n n = len(apples)\n ans = 0\n minHeap = []\n\n i = 0\n while i < n or minHeap:\n while minHeap and minHeap[0][0] <= i:\n heapq.heappop(minHeap)\n if i < n and apples[i] > 0:\n heapq.heappush(minHeap, (i + days[i], apples[i]))\n if minHeap:\n rottenDay, numApples = heapq.heappop(minHeap)\n if numApples > 1:\n heapq.heappush(minHeap, (rottenDay, numApples - 1))\n ans += 1\n i += 1\n\n return ans\n", "java_solution": "class Solution {\n public int eatenApples(int[] apples, int[] days) {\n final int n = apples.length;\n int ans = 0;\n // (the rotten day, the number of apples)\n Queue> minHeap =\n new PriorityQueue<>(Comparator.comparingInt(Pair::getKey));\n\n for (int i = 0; i < n || !minHeap.isEmpty(); ++i) {\n // Remove the rotten apples.\n while (!minHeap.isEmpty() && minHeap.peek().getKey() <= i)\n minHeap.poll();\n // Add today's apples.\n if (i < n && apples[i] > 0)\n minHeap.offer(new Pair<>(i + days[i], apples[i]));\n // Eat one apple today.\n if (!minHeap.isEmpty()) {\n final int rottenDay = minHeap.peek().getKey();\n final int numApples = minHeap.poll().getValue();\n if (numApples > 1)\n minHeap.offer(new Pair<>(rottenDay, numApples - 1));\n ++ans;\n }\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int eatenApples(vector& apples, vector& days) {\n const int n = apples.size();\n int ans = 0;\n using P = pair; // (the rotten day, the number of apples)\n priority_queue, greater<>> minHeap;\n\n for (int i = 0; i < n || !minHeap.empty(); ++i) { // i := day\n // Remove the rotten apples.\n while (!minHeap.empty() && minHeap.top().first <= i)\n minHeap.pop();\n // Add today's apples.\n if (i < n && apples[i] > 0)\n minHeap.emplace(i + days[i], apples[i]);\n // Eat one apple today.\n if (!minHeap.empty()) {\n const auto [rottenDay, numApples] = minHeap.top();\n minHeap.pop();\n if (numApples > 1)\n minHeap.emplace(rottenDay, numApples - 1);\n ++ans;\n }\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1706, "task_title": "Where Will the Ball Fall", "difficulty": 2, "func_name": "findBall", "description": "You have a 2-D `grid` of size `m x n` representing a box, and you have `n`\nballs. The box is open on the top and bottom sides.\n\nEach cell in the box has a diagonal board spanning two corners of the cell\nthat can redirect a ball to the right or to the left.\n\n* A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`.\n* A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`.\n\nWe drop one ball at the top of each column of the box. Each ball can get stuck\nin the box or fall out of the bottom. A ball gets stuck if it hits a \"V\"\nshaped pattern between two boards or if a board redirects the ball into either\nwall of the box.\n\nReturn an array `answer` of size `n` where `answer[i]` is the column that the\nball falls out of at the bottom after dropping the ball from the `ith` column\nat the top, or `-1` if the ball gets stuck in the box.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def findBall(self, grid: List[List[int]]) -> List[int]:\n m = len(grid)\n n = len(grid[0])\n dp = [i for i in range(n)]\n ans = [-1] * n\n\n for i in range(m):\n newDp = [-1] * n\n for j in range(n):\n if j + grid[i][j] < 0 or j + grid[i][j] == n:\n continue\n if grid[i][j] == 1 and grid[i][j + 1] == -1 or grid[i][j] == -1 and grid[i][j - 1] == 1:\n continue\n newDp[j + grid[i][j]] = dp[j]\n dp = newDp\n\n for i, ball in enumerate(dp):\n if ball != -1:\n ans[ball] = i\n\n return ans\n", "java_solution": "class Solution {\n public int[] findBall(int[][] grid) {\n final int m = grid.length;\n final int n = grid[0].length;\n // dp[i] := status of the i-th column\n // -1 := empty, 0 := b0, 1 := b1, ...\n int[] dp = new int[n];\n // ans[i] := the i-th ball's final position\n int[] ans = new int[n];\n Arrays.fill(ans, -1);\n\n for (int i = 0; i < n; ++i)\n dp[i] = i;\n\n for (int i = 0; i < m; ++i) {\n int[] newDp = new int[n];\n Arrays.fill(newDp, -1);\n for (int j = 0; j < n; ++j) {\n // out-of-bounds\n if (j + grid[i][j] < 0 || j + grid[i][j] == n)\n continue;\n // Stuck\n if (grid[i][j] == 1 && grid[i][j + 1] == -1 || grid[i][j] == -1 && grid[i][j - 1] == 1)\n continue;\n newDp[j + grid[i][j]] = dp[j];\n }\n dp = newDp;\n }\n\n for (int i = 0; i < n; ++i)\n if (dp[i] != -1)\n ans[dp[i]] = i;\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector findBall(vector>& grid) {\n const int m = grid.size();\n const int n = grid[0].size();\n // dp[i] := status of the i-th column\n // -1 := empty, 0 := b0, 1 := b1, ...\n vector dp(n);\n // ans[i] := the i-th ball's final position\n vector ans(n, -1);\n\n iota(dp.begin(), dp.end(), 0);\n\n for (int i = 0; i < m; ++i) {\n vector newDp(n, -1);\n for (int j = 0; j < n; ++j) {\n // out-of-bounds\n if (j + grid[i][j] < 0 || j + grid[i][j] == n)\n continue;\n // Stuck\n if (grid[i][j] == 1 && grid[i][j + 1] == -1 ||\n grid[i][j] == -1 && grid[i][j - 1] == 1)\n continue;\n newDp[j + grid[i][j]] = dp[j];\n }\n dp = std::move(newDp);\n }\n\n for (int i = 0; i < n; ++i)\n if (dp[i] != -1)\n ans[dp[i]] = i;\n\n return ans;\n }\n};\n"} +{"task_num": 1707, "task_title": "Maximum XOR With an Element From Array", "difficulty": 3, "func_name": "maximizeXor", "description": "You are given an array `nums` consisting of non-negative integers. You are\nalso given a `queries` array, where `queries[i] = [xi, mi]`.\n\nThe answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and\nany element of `nums` that does not exceed `mi`. In other words, the answer is\n`max(nums[j] XOR xi)` for all `j` such that `nums[j] <= mi`. If all elements\nin `nums` are larger than `mi`, then the answer is `-1`.\n\nReturn an integer array `answer` where `answer.length == queries.length` and\n`answer[i]` is the answer to the `ith` query.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator, Optional\n\nclass TrieNode:\n def __init__(self):\n self.children: List[Optional[TrieNode]] = [None] * 2\n\n\nclass BitTrie:\n def __init__(self, maxBit: int):\n self.maxBit = maxBit\n self.root = TrieNode()\n\n def insert(self, num: int) -> None:\n node = self.root\n for i in range(self.maxBit, -1, -1):\n bit = num >> i & 1\n if not node.children[bit]:\n node.children[bit] = TrieNode()\n node = node.children[bit]\n\n def getMaxXor(self, num: int) -> int:\n maxXor = 0\n node = self.root\n for i in range(self.maxBit, -1, -1):\n bit = num >> i & 1\n toggleBit = bit ^ 1\n if node.children[toggleBit]:\n maxXor = maxXor | 1 << i\n node = node.children[toggleBit]\n elif node.children[bit]:\n node = node.children[bit]\n else:\n return 0\n return maxXor\n\n\nclass IndexedQuery:\n def __init__(self, queryIndex: int, x: int, m: int):\n self.queryIndex = queryIndex\n self.x = x\n self.m = m\n\n def __iter__(self):\n yield self.queryIndex\n yield self.x\n yield self.m\n\n\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n ans = [-1] * len(queries)\n maxBit = int(math.log2(max(max(nums), max(x for x, _ in queries))))\n bitTrie = BitTrie(maxBit)\n\n nums.sort()\n\n i = 0\n for queryIndex, x, m in sorted([IndexedQuery(i, x, m) for i, (x, m) in enumerate(queries)], key=lambda iq: iq.m):\n while i < len(nums) and nums[i] <= m:\n bitTrie.insert(nums[i])\n i += 1\n if i > 0 and nums[i - 1] <= m:\n ans[queryIndex] = bitTrie.getMaxXor(x)\n\n return ans\n", "java_solution": "class TrieNode {\n public TrieNode[] children = new TrieNode[2];\n}\n\nclass BitTrie {\n public BitTrie(int maxBit) {\n this.maxBit = maxBit;\n }\n\n public void insert(int num) {\n TrieNode node = root;\n for (int i = maxBit; i >= 0; --i) {\n final int bit = (int) (num >> i & 1);\n if (node.children[bit] == null)\n node.children[bit] = new TrieNode();\n node = node.children[bit];\n }\n }\n\n public int getMaxXor(int num) {\n int maxXor = 0;\n TrieNode node = root;\n for (int i = maxBit; i >= 0; --i) {\n final int bit = (int) (num >> i & 1);\n final int toggleBit = bit ^ 1;\n if (node.children[toggleBit] != null) {\n maxXor = maxXor | 1 << i;\n node = node.children[toggleBit];\n } else if (node.children[bit] != null) {\n node = node.children[bit];\n } else { // There's nothing in the Bit Trie.\n return 0;\n }\n }\n return maxXor;\n }\n\n private int maxBit;\n private TrieNode root = new TrieNode();\n}\n\nclass Solution {\n public int[] maximizeXor(int[] nums, int[][] queries) {\n int[] ans = new int[queries.length];\n Arrays.fill(ans, -1);\n final int maxNumInNums = Arrays.stream(nums).max().getAsInt();\n final int maxNumInQuery = Arrays.stream(queries).mapToInt(query -> query[0]).max().getAsInt();\n final int maxBit = (int) (Math.log(Math.max(maxNumInNums, maxNumInQuery)) / Math.log(2));\n BitTrie bitTrie = new BitTrie(maxBit);\n\n Arrays.sort(nums);\n\n int i = 0; // nums' index\n for (IndexedQuery indexedQuery : getIndexedQueries(queries)) {\n final int queryIndex = indexedQuery.queryIndex;\n final int x = indexedQuery.x;\n final int m = indexedQuery.m;\n while (i < nums.length && nums[i] <= m)\n bitTrie.insert(nums[i++]);\n if (i > 0 && nums[i - 1] <= m)\n ans[queryIndex] = bitTrie.getMaxXor(x);\n }\n\n return ans;\n }\n\n private record IndexedQuery(int queryIndex, int x, int m){};\n\n private IndexedQuery[] getIndexedQueries(int[][] queries) {\n IndexedQuery[] indexedQueries = new IndexedQuery[queries.length];\n for (int i = 0; i < queries.length; ++i)\n indexedQueries[i] = new IndexedQuery(i, queries[i][0], queries[i][1]);\n Arrays.sort(indexedQueries, Comparator.comparingInt(IndexedQuery::m));\n return indexedQueries;\n }\n}\n", "cpp_solution": "struct TrieNode {\n vector> children;\n TrieNode() : children(2) {}\n};\n\nclass BitTrie {\n public:\n BitTrie(int maxBit) : maxBit(maxBit) {}\n\n void insert(int num) {\n shared_ptr node = root;\n for (int i = maxBit; i >= 0; --i) {\n const int bit = num >> i & 1;\n if (node->children[bit] == nullptr)\n node->children[bit] = make_shared();\n node = node->children[bit];\n }\n }\n\n int getMaxXor(int num) {\n int maxXor = 0;\n shared_ptr node = root;\n for (int i = maxBit; i >= 0; --i) {\n const int bit = num >> i & 1;\n const int toggleBit = bit ^ 1;\n if (node->children[toggleBit] != nullptr) {\n maxXor = maxXor | 1 << i;\n node = node->children[toggleBit];\n } else if (node->children[bit] != nullptr) {\n node = node->children[bit];\n } else { // There's nothing in the Bit Trie.\n return 0;\n }\n }\n return maxXor;\n }\n\n private:\n const int maxBit;\n shared_ptr root = make_shared();\n};\n\nstruct IndexedQuery {\n int queryIndex;\n int x;\n int m;\n};\n\nclass Solution {\n public:\n vector maximizeXor(vector& nums, vector>& queries) {\n vector ans(queries.size(), -1);\n const int maxNumInNums = ranges::max(nums);\n const int maxNumInQuery = ranges::max_element(queries, ranges::less{},\n [](const vector& query) {\n return query[0];\n })->at(0);\n const int maxBit = static_cast(log2(max(maxNumInNums, maxNumInQuery)));\n BitTrie bitTrie(maxBit);\n\n ranges::sort(nums);\n\n int i = 0; // nums' index\n for (const auto& [queryIndex, x, m] : getIndexedQueries(queries)) {\n while (i < nums.size() && nums[i] <= m)\n bitTrie.insert(nums[i++]);\n if (i > 0 && nums[i - 1] <= m)\n ans[queryIndex] = bitTrie.getMaxXor(x);\n }\n\n return ans;\n }\n\n private:\n vector getIndexedQueries(const vector>& queries) {\n vector indexedQueries;\n for (int i = 0; i < queries.size(); ++i)\n indexedQueries.emplace_back(i, queries[i][0], queries[i][1]);\n ranges::sort(\n indexedQueries, ranges::less{},\n [](const IndexedQuery& indexedQuery) { return indexedQuery.m; });\n return indexedQueries;\n }\n};\n"} +{"task_num": 1717, "task_title": "Maximum Score From Removing Substrings", "difficulty": 2, "func_name": "maximumGain", "description": "You are given a string `s` and two integers `x` and `y`. You can perform two\ntypes of operations any number of times.\n\n* Remove substring `\"ab\"` and gain `x` points. \n* For example, when removing `\"ab\"` from `\"cabxbae\"` it becomes `\"cxbae\"`.\n* Remove substring `\"ba\"` and gain `y` points. \n* For example, when removing `\"ba\"` from `\"cabxbae\"` it becomes `\"cabxe\"`.\n\nReturn the maximum points you can gain after applying the above operations on\n`s`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def maximumGain(self, s: str, x: int, y: int) -> int:\n if x > y:\n return self._gain(s, 'ab', x, 'ba', y)\n else:\n return self._gain(s, 'ba', y, 'ab', x)\n\n def _gain(self, s: str, sub1: str, point1: int, sub2: str, point2: int) -> int:\n points = 0\n stack1 = []\n stack2 = []\n\n for c in s:\n if stack1 and stack1[-1] == sub1[0] and c == sub1[1]:\n stack1.pop()\n points += point1\n else:\n stack1.append(c)\n\n for c in stack1:\n if stack2 and stack2[-1] == sub2[0] and c == sub2[1]:\n stack2.pop()\n points += point2\n else:\n stack2.append(c)\n\n return points\n", "java_solution": "class Solution {\n public int maximumGain(String s, int x, int y) {\n // The assumption that gain(\"ab\") > gain(\"ba\") while removing \"ba\" first is\n // optimal is contradicted. Only \"b(ab)a\" satisfies the condition of\n // preventing two \"ba\" removals, but after removing \"ab\", we can still\n // remove one \"ba\", resulting in a higher gain. Thus, removing \"ba\" first is\n // not optimal.\n return x > y ? gain(s, \"ab\", x, \"ba\", y) : gain(s, \"ba\", y, \"ab\", x);\n }\n\n // Returns the points gained by first removing sub1 (\"ab\" | \"ba\") from s with\n // point1, then removing sub2 (\"ab\" | \"ba\") from s with point2.\n private int gain(final String s, final String sub1, int point1, final String sub2, int point2) {\n int points = 0;\n Stack stack1 = new Stack<>();\n Stack stack2 = new Stack<>();\n\n // Remove \"sub1\" from s with point1 gain.\n for (final char c : s.toCharArray())\n if (!stack1.isEmpty() && stack1.peek() == sub1.charAt(0) && c == sub1.charAt(1)) {\n stack1.pop();\n points += point1;\n } else {\n stack1.push(c);\n }\n\n // Remove \"sub2\" from s with point2 gain.\n for (final char c : stack1)\n if (!stack2.isEmpty() && stack2.peek() == sub2.charAt(0) && c == sub2.charAt(1)) {\n stack2.pop();\n points += point2;\n } else {\n stack2.push(c);\n }\n\n return points;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int maximumGain(string s, int x, int y) {\n // The assumption that gain(\"ab\") > gain(\"ba\") while removing \"ba\" first is\n // optimal is contradicted. Only \"b(ab)a\" satisfies the condition of\n // preventing two \"ba\" removals, but after removing \"ab\", we can still\n // remove one \"ba\", resulting in a higher gain. Thus, removing \"ba\" first is\n // not optimal.\n return x > y ? gain(s, \"ab\", x, \"ba\", y) : gain(s, \"ba\", y, \"ab\", x);\n }\n\n private:\n // Returns the points gained by first removing sub1 (\"ab\" | \"ba\") from s with\n // point1, then removing sub2 (\"ab\" | \"ba\") from s with point2.\n int gain(const string& s, const string& sub1, int point1, const string& sub2,\n int point2) {\n int points = 0;\n vector stack1;\n vector stack2;\n\n // Remove \"sub1\" from s with point1 gain.\n for (const char c : s)\n if (!stack1.empty() && stack1.back() == sub1[0] && c == sub1[1]) {\n stack1.pop_back();\n points += point1;\n } else {\n stack1.push_back(c);\n }\n\n // Remove \"sub2\" from s with point2 gain.\n for (const char c : stack1)\n if (!stack2.empty() && stack2.back() == sub2[0] && c == sub2[1]) {\n stack2.pop_back();\n points += point2;\n } else {\n stack2.push_back(c);\n }\n\n return points;\n }\n};\n"} +{"task_num": 1719, "task_title": "Number Of Ways To Reconstruct A Tree", "difficulty": 3, "func_name": "checkWays", "description": "You are given an array `pairs`, where `pairs[i] = [xi, yi]`, and:\n\n* There are no duplicates.\n* `xi < yi`\n\nLet `ways` be the number of rooted trees that satisfy the following\nconditions:\n\n* The tree consists of nodes whose values appeared in `pairs`.\n* A pair `[xi, yi]` exists in `pairs` if and only if `xi` is an ancestor of `yi` or `yi` is an ancestor of `xi`.\n* Note: the tree does not have to be a binary tree.\n\nTwo ways are considered to be different if there is at least one node that has\ndifferent parents in both ways.\n\nReturn:\n\n* `0` if `ways == 0`\n* `1` if `ways == 1`\n* `2` if `ways > 1`\n\nA rooted tree is a tree that has a single root node, and all edges are\noriented to be outgoing from the root.\n\nAn ancestor of a node is any node on the path from the root to that node\n(excluding the node itself). The root has no ancestors.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def checkWays(self, pairs: List[List[int]]) -> int:\n kMax = 501\n graph = collections.defaultdict(list)\n degrees = [0] * kMax\n connected = [[False] * kMax for _ in range(kMax)]\n\n for u, v in pairs:\n graph[u].append(v)\n graph[v].append(u)\n degrees[u] += 1\n degrees[v] += 1\n connected[u][v] = True\n connected[v][u] = True\n\n for _, children in graph.items():\n children.sort(key=lambda a: degrees[a], reverse=True)\n\n root = next((i for i, d in enumerate(degrees) if d == len(graph) - 1), -1)\n if root == -1:\n return 0\n\n hasMoreThanOneWay = False\n\n def dfs(u: int, ancestors: List[int], seen: List[bool]) -> bool:\n nonlocal hasMoreThanOneWay\n seen[u] = True\n for ancestor in ancestors:\n if not connected[u][ancestor]:\n return False\n ancestors.append(u)\n for v in graph[u]:\n if seen[v]:\n continue\n if degrees[v] == degrees[u]:\n hasMoreThanOneWay = True\n if not dfs(v, ancestors, seen):\n return False\n ancestors.pop()\n return True\n\n if not dfs(root, [], [False] * kMax):\n return 0\n if hasMoreThanOneWay:\n return 2\n else:\n return 1\n", "java_solution": "class Solution {\n public int checkWays(int[][] pairs) {\n final int MAX = 501;\n Map> graph = new HashMap<>();\n int[] degrees = new int[MAX];\n boolean[][] connected = new boolean[MAX][MAX];\n\n for (int[] pair : pairs) {\n final int u = pair[0];\n final int v = pair[1];\n graph.putIfAbsent(u, new ArrayList<>());\n graph.putIfAbsent(v, new ArrayList<>());\n graph.get(u).add(v);\n graph.get(v).add(u);\n ++degrees[u];\n ++degrees[v];\n connected[u][v] = true;\n connected[v][u] = true;\n }\n\n // For each node, sort its children by degrees in descending order.\n for (final int u : graph.keySet())\n graph.get(u).sort(Comparator.comparingInt(a -> - degrees[a]));\n\n final int root = getRoot(degrees, graph.keySet().size());\n if (root == -1)\n return 0;\n if (!dfs(graph, root, degrees, connected, new ArrayList<>(), new boolean[MAX]))\n return 0;\n return hasMoreThanOneWay ? 2 : 1;\n }\n\n private boolean hasMoreThanOneWay = false;\n\n // Returns the root by finding the node with a degree that equals to n - 1.\n private int getRoot(int[] degrees, int n) {\n for (int i = 1; i < degrees.length; ++i)\n if (degrees[i] == n - 1)\n return i;\n return -1;\n }\n\n // Returns true if each node rooted at u is connected to all of its ancestors.\n private boolean dfs(Map> graph, int u, int[] degrees,\n boolean[][] connected, List ancestors, boolean[] seen) {\n seen[u] = true;\n\n for (final int ancestor : ancestors)\n if (!connected[u][ancestor])\n return false;\n\n ancestors.add(u);\n\n for (final int v : graph.get(u)) {\n if (seen[v])\n continue;\n // We can swap u with v, so there are more than one way.\n if (degrees[v] == degrees[u])\n hasMoreThanOneWay = true;\n if (!dfs(graph, v, degrees, connected, ancestors, seen))\n return false;\n }\n\n ancestors.remove(ancestors.size() - 1);\n return true;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int checkWays(vector>& pairs) {\n constexpr int kMax = 501;\n unordered_map> graph;\n vector degrees(kMax);\n vector> connected(kMax, vector(kMax));\n\n for (const vector& pair : pairs) {\n const int u = pair[0];\n const int v = pair[1];\n graph[u].push_back(v);\n graph[v].push_back(u);\n ++degrees[u];\n ++degrees[v];\n connected[u][v] = true;\n connected[v][u] = true;\n }\n\n // For each node, sort its children by degrees in descending order.\n for (auto& [_, children] : graph)\n ranges::sort(children, ranges::greater{},\n [°rees](int child) { return degrees[child]; });\n\n const int root = getRoot(degrees, graph.size());\n if (root == -1)\n return 0;\n if (!dfs(graph, root, degrees, connected, {}, vector(kMax)))\n return 0;\n return hasMoreThanOneWay ? 2 : 1;\n }\n\n private:\n bool hasMoreThanOneWay = false;\n\n // Returns the root by finding the node with a degree that equals to n - 1.\n int getRoot(const vector& degrees, int n) {\n for (int i = 1; i < degrees.size(); ++i)\n if (degrees[i] == n - 1)\n return i;\n return -1;\n }\n\n // Returns true if each node rooted at u is connected to all of its ancestors.\n bool dfs(const unordered_map>& graph, int u,\n vector& degrees, vector>& connected,\n vector&& ancestors, vector&& seen) {\n seen[u] = true;\n\n for (const int ancestor : ancestors)\n if (!connected[u][ancestor])\n return false;\n\n ancestors.push_back(u);\n\n for (const int v : graph.at(u)) {\n if (seen[v])\n continue;\n // We can swap u with v, so there are more than one way.\n if (degrees[v] == degrees[u])\n hasMoreThanOneWay = true;\n if (!dfs(graph, v, degrees, connected, std::move(ancestors),\n std::move(seen)))\n return false;\n }\n\n ancestors.pop_back();\n return true;\n }\n};\n"} +{"task_num": 1722, "task_title": "Minimize Hamming Distance After Swap Operations", "difficulty": 2, "func_name": "minimumHammingDistance", "description": "You are given two integer arrays, `source` and `target`, both of length `n`.\nYou are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai,\nbi]` indicates that you are allowed to swap the elements at index `ai` and\nindex `bi` (0-indexed) of array `source`. Note that you can swap elements at a\nspecific pair of indices multiple times and in any order.\n\nThe Hamming distance of two arrays of the same length, `source` and `target`,\nis the number of positions where the elements are different. Formally, it is\nthe number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]`\n(0-indexed).\n\nReturn the minimum Hamming distance of `source` and `target` after performing\nany amount of swap operations on array `source`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self.find(u)\n j = self.find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n n = len(source)\n ans = 0\n uf = UnionFind(n)\n groupIdToCount = [collections.Counter() for _ in range(n)]\n\n for a, b in allowedSwaps:\n uf.unionByRank(a, b)\n\n for i in range(n):\n groupIdToCount[uf.find(i)][source[i]] += 1\n\n for i in range(n):\n groupId = uf.find(i)\n count = groupIdToCount[groupId]\n if target[i] not in count:\n ans += 1\n else:\n count[target[i]] -= 1\n if count[target[i]] == 0:\n del count[target[i]]\n\n return ans\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public void unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n public int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n\n private int[] id;\n private int[] rank;\n}\n\nclass Solution {\n public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) {\n final int n = source.length;\n int ans = 0;\n UnionFind uf = new UnionFind(n);\n Map[] groupIdToCount = new Map[n];\n\n for (int i = 0; i < n; ++i)\n groupIdToCount[i] = new HashMap<>();\n\n for (int[] allowedSwap : allowedSwaps) {\n final int a = allowedSwap[0];\n final int b = allowedSwap[1];\n uf.unionByRank(a, b);\n }\n\n for (int i = 0; i < n; ++i)\n groupIdToCount[uf.find(i)].merge(source[i], 1, Integer::sum);\n\n for (int i = 0; i < n; ++i) {\n final int groupId = uf.find(i);\n Map count = groupIdToCount[groupId];\n if (!count.containsKey(target[i]))\n ++ans;\n else if (count.merge(target[i], -1, Integer::sum) == 0)\n count.remove(target[i]);\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n), rank(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n void unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n\n private:\n vector id;\n vector rank;\n};\n\nclass Solution {\n public:\n int minimumHammingDistance(vector& source, vector& target,\n vector>& allowedSwaps) {\n const int n = source.size();\n int ans = 0;\n UnionFind uf(n);\n vector> groupIdToCount(n);\n\n for (const vector& allowedSwap : allowedSwaps) {\n const int a = allowedSwap[0];\n const int b = allowedSwap[1];\n uf.unionByRank(a, b);\n }\n\n for (int i = 0; i < n; ++i)\n ++groupIdToCount[uf.find(i)][source[i]];\n\n for (int i = 0; i < n; ++i) {\n const int groupId = uf.find(i);\n unordered_map& count = groupIdToCount[groupId];\n if (!count.contains(target[i]))\n ++ans;\n else if (--count[target[i]] == 0)\n count.erase(target[i]);\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1735, "task_title": "Count Ways to Make Array With Product", "difficulty": 3, "func_name": "waysToFillArray", "description": "You are given a 2D integer array, `queries`. For each `queries[i]`, where\n`queries[i] = [ni, ki]`, find the number of different ways you can place\npositive integers into an array of size `ni` such that the product of the\nintegers is `ki`. As the number of ways may be too large, the answer to the\n`ith` query is the number of ways modulo `109 + 7`.\n\nReturn an integer array `answer` where `answer.length == queries.length`, and\n`answer[i]` is the answer to the `ith` query.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def waysToFillArray(self, queries: List[List[int]]) -> List[int]:\n kMod = 1_000_000_007\n kMax = 10_000\n minPrimeFactors = self._sieveEratosthenes(kMax + 1)\n\n @functools.lru_cache(None)\n def fact(i: int) -> int:\n return 1 if i <= 1 else i * fact(i - 1) % kMod\n\n @functools.lru_cache(None)\n def inv(i: int) -> int:\n return pow(i, kMod - 2, kMod)\n\n @functools.lru_cache(None)\n def nCk(n: int, k: int) -> int:\n return fact(n) * inv(fact(k)) * inv(fact(n - k)) % kMod\n\n ans = []\n\n for n, k in queries:\n res = 1\n for freq in self._getPrimeFactorsCount(k, minPrimeFactors).values():\n res = res * nCk(n - 1 + freq, freq) % kMod\n ans.append(res)\n\n return ans\n\n def _sieveEratosthenes(self, n: int) -> List[int]:\n minPrimeFactors = [i for i in range(n + 1)]\n for i in range(2, int(n**0.5) + 1):\n if minPrimeFactors[i] == i:\n for j in range(i * i, n, i):\n minPrimeFactors[j] = min(minPrimeFactors[j], i)\n return minPrimeFactors\n\n def _getPrimeFactorsCount(self, num: int, minPrimeFactors: List[int]) -> Dict[int, int]:\n count = collections.Counter()\n while num > 1:\n divisor = minPrimeFactors[num]\n while num % divisor == 0:\n num //= divisor\n count[divisor] += 1\n return count\n", "java_solution": "class Solution {\n public int[] waysToFillArray(int[][] queries) {\n final int MAX = 10_000;\n final int MAX_FREQ = 13; // 2^13 = 8192 < MAX\n final int[] minPrimeFactors = sieveEratosthenes(MAX + 1);\n final long[][] factAndInvFact = getFactAndInvFact(MAX + MAX_FREQ - 1);\n final long[] fact = factAndInvFact[0];\n final long[] invFact = factAndInvFact[1];\n int[] ans = new int[queries.length];\n\n for (int i = 0; i < queries.length; ++i) {\n final int n = queries[i][0];\n final int k = queries[i][1];\n int res = 1;\n for (final int freq : getPrimeFactorsCount(k, minPrimeFactors).values())\n res = (int) ((long) res * nCk(n - 1 + freq, freq, fact, invFact) % MOD);\n ans[i] = res;\n }\n\n return ans;\n }\n\n private static final int MOD = 1_000_000_007;\n\n // Gets the minimum prime factor of i, where 1 < i <= n.\n private int[] sieveEratosthenes(int n) {\n int[] minPrimeFactors = new int[n + 1];\n for (int i = 2; i <= n; ++i)\n minPrimeFactors[i] = i;\n for (int i = 2; i * i < n; ++i)\n if (minPrimeFactors[i] == i) // `i` is prime.\n for (int j = i * i; j < n; j += i)\n minPrimeFactors[j] = Math.min(minPrimeFactors[j], i);\n return minPrimeFactors;\n }\n\n private Map getPrimeFactorsCount(int num, int[] minPrimeFactors) {\n Map count = new HashMap<>();\n while (num > 1) {\n final int divisor = minPrimeFactors[num];\n while (num % divisor == 0) {\n num /= divisor;\n count.put(divisor, count.merge(divisor, 1, Integer::sum));\n }\n }\n return count;\n }\n\n private long[][] getFactAndInvFact(int n) {\n long[] fact = new long[n + 1];\n long[] invFact = new long[n + 1];\n long[] inv = new long[n + 1];\n fact[0] = invFact[0] = 1;\n inv[0] = inv[1] = 1;\n for (int i = 1; i <= n; ++i) {\n if (i >= 2)\n inv[i] = MOD - MOD / i * inv[MOD % i] % MOD;\n fact[i] = fact[i - 1] * i % MOD;\n invFact[i] = invFact[i - 1] * inv[i] % MOD;\n }\n return new long[][] {fact, invFact};\n }\n\n private int nCk(int n, int k, long[] fact, long[] invFact) {\n return (int) (fact[n] * invFact[k] % MOD * invFact[n - k] % MOD);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector waysToFillArray(vector>& queries) {\n constexpr int kMax = 10000;\n constexpr int kMaxFreq = 13; // 2^13 = 8192 < kMax\n const vector minPrimeFactors = sieveEratosthenes(kMax + 1);\n const auto [fact, invFact] = getFactAndInvFact(kMax + kMaxFreq - 1);\n vector ans;\n\n for (const vector& query : queries) {\n const int n = query[0];\n const int k = query[1];\n int res = 1;\n for (const auto& [_, freq] : getPrimeFactorsCount(k, minPrimeFactors))\n res = static_cast(res) * nCk(n - 1 + freq, freq, fact, invFact) %\n kMod;\n ans.push_back(res);\n }\n\n return ans;\n }\n\n private:\n static constexpr int kMod = 1'000'000'007;\n\n // Gets the minimum prime factor of i, where 1 < i <= n.\n vector sieveEratosthenes(int n) {\n vector minPrimeFactors(n + 1);\n iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2);\n for (int i = 2; i * i < n; ++i)\n if (minPrimeFactors[i] == i) // `i` is prime.\n for (int j = i * i; j < n; j += i)\n minPrimeFactors[j] = min(minPrimeFactors[j], i);\n return minPrimeFactors;\n }\n\n unordered_map getPrimeFactorsCount(\n int num, const vector& minPrimeFactors) {\n unordered_map count;\n while (num > 1) {\n const int divisor = minPrimeFactors[num];\n while (num % divisor == 0) {\n num /= divisor;\n ++count[divisor];\n }\n }\n return count;\n }\n\n pair, vector> getFactAndInvFact(int n) {\n vector fact(n + 1);\n vector invFact(n + 1);\n vector inv(n + 1);\n fact[0] = invFact[0] = 1;\n inv[0] = inv[1] = 1;\n for (int i = 1; i <= n; ++i) {\n if (i >= 2)\n inv[i] = kMod - kMod / i * inv[kMod % i] % kMod;\n fact[i] = fact[i - 1] * i % kMod;\n invFact[i] = invFact[i - 1] * inv[i] % kMod;\n }\n return {fact, invFact};\n }\n\n int nCk(int n, int k, const vector& fact, const vector& invFact) {\n return fact[n] * invFact[k] % kMod * invFact[n - k] % kMod;\n }\n};\n"} +{"task_num": 1765, "task_title": "Map of Highest Peak", "difficulty": 2, "func_name": "highestPeak", "description": "You are given an integer matrix `isWater` of size `m x n` that represents a\nmap of land and water cells.\n\n* If `isWater[i][j] == 0`, cell `(i, j)` is a land cell.\n* If `isWater[i][j] == 1`, cell `(i, j)` is a water cell.\n\nYou must assign each cell a height in a way that follows these rules:\n\n* The height of each cell must be non-negative.\n* If the cell is a water cell, its height must be `0`.\n* Any two adjacent cells must have an absolute height difference of at most `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).\n\nFind an assignment of heights such that the maximum height in the matrix is\nmaximized.\n\nReturn an integer matrix `height` of size `m x n` where `height[i][j]` is cell\n`(i, j)`'s height. If there are multiple solutions, return any of them.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(isWater)\n n = len(isWater[0])\n ans = [[-1] * n for _ in range(m)]\n q = collections.deque()\n\n for i in range(m):\n for j in range(n):\n if isWater[i][j] == 1:\n q.append((i, j))\n ans[i][j] = 0\n\n while q:\n i, j = q.popleft()\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if ans[x][y] != -1:\n continue\n ans[x][y] = ans[i][j] + 1\n q.append((x, y))\n\n return ans\n", "java_solution": "class Solution {\n public int[][] highestPeak(int[][] isWater) {\n final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n final int m = isWater.length;\n final int n = isWater[0].length;\n int[][] ans = new int[m][n];\n Arrays.stream(ans).forEach(A -> Arrays.fill(A, -1));\n Queue> q = new ArrayDeque<>();\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (isWater[i][j] == 1) {\n q.offer(new Pair<>(i, j));\n ans[i][j] = 0;\n }\n\n while (!q.isEmpty()) {\n final int i = q.peek().getKey();\n final int j = q.poll().getValue();\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (ans[x][y] != -1)\n continue;\n ans[x][y] = ans[i][j] + 1;\n q.offer(new Pair<>(x, y));\n }\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector> highestPeak(vector>& isWater) {\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n const int m = isWater.size();\n const int n = isWater[0].size();\n vector> ans(m, vector(n, -1));\n queue> q;\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (isWater[i][j] == 1) {\n q.emplace(i, j);\n ans[i][j] = 0;\n }\n\n while (!q.empty()) {\n const auto [i, j] = q.front();\n q.pop();\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (ans[x][y] != -1)\n continue;\n ans[x][y] = ans[i][j] + 1;\n q.emplace(x, y);\n }\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1782, "task_title": "Count Pairs Of Nodes", "difficulty": 3, "func_name": "countPairs", "description": "You are given an undirected graph defined by an integer `n`, the number of\nnodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i]\n= [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.\nYou are also given an integer array `queries`.\n\nLet `incident(a, b)` be defined as the number of edges that are connected to\neither node `a` or `b`.\n\nThe answer to the `jth` query is the number of pairs of nodes `(a, b)` that\nsatisfy both of the following conditions:\n\n* `a < b`\n* `incident(a, b) > queries[j]`\n\nReturn an array `answers` such that `answers.length == queries.length` and\n`answers[j]` is the answer of the `jth` query.\n\nNote that there can be multiple edges between the same two nodes.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n ans = [0] * len(queries)\n\n count = [0] * (n + 1)\n\n shared = [collections.Counter() for _ in range(n + 1)]\n\n for u, v in edges:\n count[u] += 1\n count[v] += 1\n shared[min(u, v)][max(u, v)] += 1\n\n sortedCount = sorted(count)\n\n for k, query in enumerate(queries):\n i = 1\n j = n\n while i < j:\n if sortedCount[i] + sortedCount[j] > query:\n ans[k] += j - i\n j -= 1\n else:\n i += 1\n for i in range(1, n + 1):\n for j, sh in shared[i].items():\n if count[i] + count[j] > query and count[i] + count[j] - sh <= query:\n ans[k] -= 1\n\n return ans\n", "java_solution": "class Solution {\n public int[] countPairs(int n, int[][] edges, int[] queries) {\n int[] ans = new int[queries.length];\n\n // count[i] := the number of edges of node i\n int[] count = new int[n + 1];\n\n // shared[i][j] := the number of edges incident to i or j, where i < j\n Map[] shared = new Map[n + 1];\n\n for (int i = 1; i <= n; ++i)\n shared[i] = new HashMap<>();\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n ++count[u];\n ++count[v];\n shared[Math.min(u, v)].merge(Math.max(u, v), 1, Integer::sum);\n }\n\n int[] sortedCount = count.clone();\n Arrays.sort(sortedCount);\n\n int k = 0;\n for (final int query : queries) {\n for (int i = 1, j = n; i < j;)\n if (sortedCount[i] + sortedCount[j] > query)\n // sortedCount[i] + sortedCount[j] > query\n // sortedCount[i + 1] + sortedCount[j] > query\n // ...\n // sortedCount[j - 1] + sortedCount[j] > query\n // So, there are (j - 1) - i + 1 = j - i pairs > query\n ans[k] += (j--) - i;\n else\n ++i;\n for (int i = 1; i <= n; ++i)\n for (Map.Entry p : shared[i].entrySet()) {\n final int j = p.getKey();\n final int sh = p.getValue();\n if (count[i] + count[j] > query && count[i] + count[j] - sh <= query)\n --ans[k];\n }\n ++k;\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector countPairs(int n, vector>& edges,\n vector& queries) {\n vector ans(queries.size());\n\n // count[i] := the number of edges of node i\n vector count(n + 1);\n\n // shared[i][j] := the number of edges incident to i or j, where i < j\n vector> shared(n + 1);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n ++count[u];\n ++count[v];\n ++shared[min(u, v)][max(u, v)];\n }\n\n vector sortedCount(count);\n ranges::sort(sortedCount);\n\n int k = 0;\n for (const int query : queries) {\n for (int i = 1, j = n; i < j;)\n if (sortedCount[i] + sortedCount[j] > query)\n // sortedCount[i] + sortedCount[j] > query\n // sortedCount[i + 1] + sortedCount[j] > query\n // ...\n // sortedCount[j - 1] + sortedCount[j] > query\n // So, there are (j - 1) - i + 1 = j - i pairs > query\n ans[k] += (j--) - i;\n else\n ++i;\n for (int i = 1; i <= n; ++i)\n for (const auto& [j, sh] : shared[i])\n if (count[i] + count[j] > query && count[i] + count[j] - sh <= query)\n --ans[k];\n ++k;\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1786, "task_title": "Number of Restricted Paths From First to Last Node", "difficulty": 2, "func_name": "countRestrictedPaths", "description": "There is an undirected weighted connected graph. You are given a positive\ninteger `n` which denotes that the graph has `n` nodes labeled from `1` to\n`n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes\nthat there is an edge between nodes `ui` and `vi` with weight equal to\n`weighti`.\n\nA path from node `start` to node `end` is a sequence of nodes `[z0, z1, z2,\n..., zk]` such that `z0 = start` and `zk = end` and there is an edge between\n`zi` and `zi+1` where `0 <= i <= k-1`.\n\nThe distance of a path is the sum of the weights on the edges of the path. Let\n`distanceToLastNode(x)` denote the shortest distance of a path between node\n`n` and node `x`. A restricted path is a path that also satisfies that\n`distanceToLastNode(zi) > distanceToLastNode(zi+1)` where `0 <= i <= k-1`.\n\nReturn the number of restricted paths from node `1` to node `n`. Since that\nnumber may be too large, return it modulo `109 + 7`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = [[] for _ in range(n)]\n\n for u, v, w in edges:\n graph[u - 1].append((v - 1, w))\n graph[v - 1].append((u - 1, w))\n\n return self._dijkstra(graph, 0, n - 1)\n\n def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, dst: int) -> int:\n kMod = 10**9 + 7\n ways = [0] * len(graph)\n dist = [math.inf] * len(graph)\n\n ways[dst] = 1\n dist[dst] = 0\n minHeap = [(dist[dst], dst)]\n\n while minHeap:\n d, u = heapq.heappop(minHeap)\n if d > dist[u]:\n continue\n for v, w in graph[u]:\n if d + w < dist[v]:\n dist[v] = d + w\n heapq.heappush(minHeap, (dist[v], v))\n if dist[v] < dist[u]:\n ways[u] += ways[v]\n ways[u] %= kMod\n\n return ways[src]\n", "java_solution": "class Solution {\n public int countRestrictedPaths(int n, int[][] edges) {\n List>[] graph = new List[n];\n Arrays.setAll(graph, i -> new ArrayList<>());\n\n for (int[] edge : edges) {\n final int u = edge[0] - 1;\n final int v = edge[1] - 1;\n final int w = edge[2];\n graph[u].add(new Pair<>(v, w));\n graph[v].add(new Pair<>(u, w));\n }\n\n return dijkstra(graph, 0, n - 1);\n }\n\n private int dijkstra(List>[] graph, int src, int dst) {\n final int MOD = 1_000_000_007;\n // ways[i] := the number of restricted path from i to n\n long[] ways = new long[graph.length];\n // dist[i] := the distance to the last node of i\n long[] dist = new long[graph.length];\n Arrays.fill(dist, Long.MAX_VALUE);\n\n ways[dst] = 1;\n dist[dst] = 0;\n // (d, u)\n Queue> minHeap =\n new PriorityQueue<>(Comparator.comparingLong(Pair::getKey));\n minHeap.offer(new Pair<>(dist[dst], dst));\n\n while (!minHeap.isEmpty()) {\n final long d = minHeap.peek().getKey();\n final int u = minHeap.poll().getValue();\n if (d > dist[u])\n continue;\n for (Pair pair : graph[u]) {\n final int v = pair.getKey();\n final int w = pair.getValue();\n if (d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.offer(new Pair<>(dist[v], v));\n }\n if (dist[v] < dist[u]) {\n ways[u] += ways[v];\n ways[u] %= MOD;\n }\n }\n }\n\n return (int) ways[src];\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int countRestrictedPaths(int n, vector>& edges) {\n vector>> graph(n);\n\n for (const vector& edge : edges) {\n const int u = edge[0] - 1;\n const int v = edge[1] - 1;\n const int w = edge[2];\n graph[u].emplace_back(v, w);\n graph[v].emplace_back(u, w);\n }\n\n return dijkstra(graph, 0, n - 1);\n }\n\n private:\n int dijkstra(const vector>>& graph, int src, int dst) {\n constexpr int kMod = 1'000'000'007;\n // ways[i] := the number of restricted path from i to n\n vector ways(graph.size());\n // dist[i] := the distance to the last node of i\n vector dist(graph.size(), LONG_MAX);\n\n ways[dst] = 1;\n dist[dst] = 0;\n using P = pair; // (d, u)\n priority_queue, greater<>> minHeap;\n minHeap.emplace(dist[dst], dst);\n\n while (!minHeap.empty()) {\n const auto [d, u] = minHeap.top();\n minHeap.pop();\n if (d > dist[u])\n continue;\n for (const auto& [v, w] : graph[u]) {\n if (d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.emplace(dist[v], v);\n }\n if (dist[v] < dist[u]) {\n ways[u] += ways[v];\n ways[u] %= kMod;\n }\n }\n }\n\n return ways[src];\n }\n};\n"} +{"task_num": 1793, "task_title": "Maximum Score of a Good Subarray", "difficulty": 3, "func_name": "maximumScore", "description": "You are given an array of integers `nums` (0-indexed) and an integer `k`.\n\nThe score of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ...,\nnums[j]) * (j - i + 1)`. A good subarray is a subarray where `i <= k <= j`.\n\nReturn the maximum possible score of a good subarray.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def maximumScore(self, nums: List[int], k: int) -> int:\n ans = 0\n stack = []\n\n for i in range(len(nums) + 1):\n while stack and (i == len(nums) or nums[stack[-1]] > nums[i]):\n h = nums[stack.pop()]\n w = i - stack[-1] - 1 if stack else i\n if (not stack or stack[-1] + 1 <= k) and i - 1 >= k:\n ans = max(ans, h * w)\n stack.append(i)\n\n return ans\n", "java_solution": "class Solution {\n // Similar to 84. Largest Rectangle in Histogram\n public int maximumScore(int[] nums, int k) {\n int ans = 0;\n Deque stack = new ArrayDeque<>();\n\n for (int i = 0; i <= nums.length; ++i) {\n while (!stack.isEmpty() && (i == nums.length || nums[stack.peek()] > nums[i])) {\n final int h = nums[stack.pop()];\n final int w = stack.isEmpty() ? i : i - stack.peek() - 1;\n if ((stack.isEmpty() || stack.peek() + 1 <= k) && i - 1 >= k)\n ans = Math.max(ans, h * w);\n }\n stack.push(i);\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n // Similar to 84. Largest Rectangle in Histogram\n int maximumScore(vector& nums, int k) {\n int ans = 0;\n stack stack;\n\n for (int i = 0; i <= nums.size(); ++i) {\n while (!stack.empty() &&\n (i == nums.size() || nums[stack.top()] > nums[i])) {\n const int h = nums[stack.top()];\n stack.pop();\n const int w = stack.empty() ? i : i - stack.top() - 1;\n if ((stack.empty() || stack.top() + 1 <= k) && i - 1 >= k)\n ans = max(ans, h * w);\n }\n stack.push(i);\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1805, "task_title": "Number of Different Integers in a String", "difficulty": 1, "func_name": "numDifferentIntegers", "description": "You are given a string `word` that consists of digits and lowercase English\nletters.\n\nYou will replace every non-digit character with a space. For example,\n`\"a123bc34d8ef34\"` will become `\" 123 34 8 34\"`. Notice that you are left with\nsome integers that are separated by at least one space: `\"123\"`, `\"34\"`,\n`\"8\"`, and `\"34\"`.\n\nReturn the number of different integers after performing the replacement\noperations on `word`.\n\nTwo integers are considered different if their decimal representations without\nany leading zeros are different.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def numDifferentIntegers(self, word: str) -> int:\n nums = set()\n curr = []\n\n for c in word:\n if c.isdigit():\n curr.append(c)\n elif curr:\n nums.add(''.join(self._removeLeadingZeros(curr)))\n curr = []\n\n if curr:\n nums.add(''.join(self._removeLeadingZeros(curr)))\n\n return len(nums)\n\n def _removeLeadingZeros(self, s: str) -> str:\n index = next((i for i, c in enumerate(s) if c != '0'), -1)\n if index == -1:\n return ['0']\n else:\n return s[index:]\n", "java_solution": "class Solution {\n public int numDifferentIntegers(String word) {\n HashSet nums = new HashSet<>();\n StringBuilder sb = new StringBuilder();\n\n for (final char c : word.toCharArray())\n if (Character.isDigit(c)) {\n sb.append(c);\n } else if (sb.length() > 0) {\n nums.add(removeLeadingZeros(sb.toString()));\n sb = new StringBuilder();\n }\n\n if (sb.length() > 0)\n nums.add(removeLeadingZeros(sb.toString()));\n return nums.size();\n }\n\n private String removeLeadingZeros(final String s) {\n int index = 0;\n while (index < s.length() && s.charAt(index) == '0')\n ++index;\n return index == s.length() ? \"0\" : s.substring(index);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int numDifferentIntegers(string word) {\n unordered_set nums;\n string curr;\n\n for (const char c : word)\n if (isdigit(c)) {\n curr += c;\n } else if (curr.length() > 0) {\n nums.insert(removeLeadingZeros(curr));\n curr = \"\";\n }\n\n if (curr.length() > 0)\n nums.insert(removeLeadingZeros(curr));\n return nums.size();\n }\n\n private:\n string removeLeadingZeros(const string& s) {\n const int index = s.find_first_not_of('0');\n return index == string::npos ? \"0\" : s.substr(index);\n }\n};\n"} +{"task_num": 1857, "task_title": "Largest Color Value in a Directed Graph", "difficulty": 3, "func_name": "largestPathValue", "description": "There is a directed graph of `n` colored nodes and `m` edges. The nodes are\nnumbered from `0` to `n - 1`.\n\nYou are given a string `colors` where `colors[i]` is a lowercase English\nletter representing the color of the `ith` node in this graph (0-indexed). You\nare also given a 2D array `edges` where `edges[j] = [aj, bj]` indicates that\nthere is a directed edge from node `aj` to node `bj`.\n\nA valid path in the graph is a sequence of nodes `x1 -> x2 -> x3 -> ... -> xk`\nsuch that there is a directed edge from `xi` to `xi+1` for every `1 <= i < k`.\nThe color value of the path is the number of nodes that are colored the most\nfrequently occurring color along that path.\n\nReturn the largest color value of any valid path in the given graph, or `-1`\nif the graph contains a cycle.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def largestPathValue(self, colors: str, edges: List[List[int]]) -> int:\n n = len(colors)\n ans = 0\n processed = 0\n graph = [[] for _ in range(n)]\n inDegrees = [0] * n\n q = collections.deque()\n count = [[0] * 26 for _ in range(n)]\n\n for u, v in edges:\n graph[u].append(v)\n inDegrees[v] += 1\n\n for i, degree in enumerate(inDegrees):\n if degree == 0:\n q.append(i)\n\n while q:\n u = q.popleft()\n processed += 1\n count[u][ord(colors[u]) - ord('a')] += 1\n ans = max(ans, count[u][ord(colors[u]) - ord('a')])\n for v in graph[u]:\n for i in range(26):\n count[v][i] = max(count[v][i], count[u][i])\n inDegrees[v] -= 1\n if inDegrees[v] == 0:\n q.append(v)\n\n if processed == n:\n return ans\n else:\n return -1\n", "java_solution": "class Solution {\n public int largestPathValue(String colors, int[][] edges) {\n final int n = colors.length();\n int ans = 0;\n int processed = 0;\n List[] graph = new List[n];\n int[] inDegrees = new int[n];\n int[][] count = new int[n][26];\n Arrays.setAll(graph, i -> new ArrayList<>());\n\n // Build the graph.\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n graph[u].add(v);\n ++inDegrees[v];\n }\n\n // Perform topological sorting.\n Queue q = IntStream.range(0, n)\n .filter(i -> inDegrees[i] == 0)\n .boxed()\n .collect(Collectors.toCollection(ArrayDeque::new));\n\n while (!q.isEmpty()) {\n final int out = q.poll();\n ++processed;\n ans = Math.max(ans, ++count[out][colors.charAt(out) - 'a']);\n for (final int in : graph[out]) {\n for (int i = 0; i < 26; ++i)\n count[in][i] = Math.max(count[in][i], count[out][i]);\n if (--inDegrees[in] == 0)\n q.offer(in);\n }\n }\n\n return processed == n ? ans : -1;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int largestPathValue(string colors, vector>& edges) {\n const int n = colors.length();\n int ans = 0;\n int processed = 0;\n vector> graph(n);\n vector inDegrees(n);\n queue q;\n vector> count(n, vector(26));\n\n // Build the graph.\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n graph[u].push_back(v);\n ++inDegrees[v];\n }\n\n // Perform topological sorting.\n for (int i = 0; i < n; ++i)\n if (inDegrees[i] == 0)\n q.push(i);\n\n while (!q.empty()) {\n const int out = q.front();\n q.pop();\n ++processed;\n ans = max(ans, ++count[out][colors[out] - 'a']);\n for (const int in : graph[out]) {\n for (int i = 0; i < 26; ++i)\n count[in][i] = max(count[in][i], count[out][i]);\n if (--inDegrees[in] == 0)\n q.push(in);\n }\n }\n\n return processed == n ? ans : -1;\n }\n};\n"} +{"task_num": 1878, "task_title": "Get Biggest Three Rhombus Sums in a Grid", "difficulty": 2, "func_name": "getBiggestThree", "description": "You are given an `m x n` integer matrix `grid`\u200b\u200b\u200b.\n\nA rhombus sum is the sum of the elements that form the border of a regular\nrhombus shape in `grid`\u200b\u200b\u200b. The rhombus must have the shape of a square\nrotated 45 degrees with each of the corners centered in a grid cell. Below is\nan image of four valid rhombus shapes with the corresponding colored cells\nthat should be included in each rhombus sum:\n\nNote that the rhombus can have an area of 0, which is depicted by the purple\nrhombus in the bottom right corner.\n\nReturn the biggest three distinct rhombus sums in the `grid` in descending\norder. If there are less than three distinct values, return all of them.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nfrom sortedcontainers import SortedSet\n\n\nclass Solution:\n def getBiggestThree(self, grid: List[List[int]]) -> List[int]:\n m = len(grid)\n n = len(grid[0])\n sums = SortedSet()\n\n for i in range(m):\n for j in range(n):\n sz = 0\n while i + sz < m and i - sz >= 0 and j + 2 * sz < n:\n summ = grid[i][j] if sz == 0 else self._getSum(grid, i, j, sz)\n sums.add(summ)\n if len(sums) > 3:\n sums.pop(0)\n sz += 1\n\n return reversed(sums)\n\n def _getSum(self, grid: List[List[int]], i: int, j: int, sz: int) -> int:\n x = i\n y = j\n summ = 0\n\n for _ in range(sz):\n x -= 1\n y += 1\n summ += grid[x][y]\n\n for _ in range(sz):\n x += 1\n y += 1\n summ += grid[x][y]\n\n for _ in range(sz):\n x += 1\n y -= 1\n summ += grid[x][y]\n\n for _ in range(sz):\n x -= 1\n y -= 1\n summ += grid[x][y]\n\n return summ\n", "java_solution": "class Solution {\n public int[] getBiggestThree(int[][] grid) {\n final int m = grid.length;\n final int n = grid[0].length;\n TreeSet sums = new TreeSet<>();\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n for (int sz = 0; i + sz < m && i - sz >= 0 && j + 2 * sz < n; ++sz) {\n final int sum = sz == 0 ? grid[i][j] : getSum(grid, i, j, sz);\n sums.add(sum);\n if (sums.size() > 3)\n sums.pollFirst();\n }\n\n return sums.descendingSet().stream().mapToInt(Integer::intValue).toArray();\n }\n\n // Returns the sum of the rhombus, where the top grid is (i, j) and the edge\n // size is `sz`.\n private int getSum(int[][] grid, int i, int j, int sz) {\n int x = i;\n int y = j;\n int sum = 0;\n\n // Go left down.\n for (int k = 0; k < sz; ++k)\n sum += grid[--x][++y];\n\n // Go right down.\n for (int k = 0; k < sz; ++k)\n sum += grid[++x][++y];\n\n // Go right up.\n for (int k = 0; k < sz; ++k)\n sum += grid[++x][--y];\n\n // Go left up.\n for (int k = 0; k < sz; ++k)\n sum += grid[--x][--y];\n\n return sum;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector getBiggestThree(vector>& grid) {\n const int m = grid.size();\n const int n = grid[0].size();\n set sums;\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n for (int sz = 0; i + sz < m && i - sz >= 0 && j + 2 * sz < n; ++sz) {\n const int sum = sz == 0 ? grid[i][j] : getSum(grid, i, j, sz);\n sums.insert(sum);\n if (sums.size() > 3)\n sums.erase(sums.begin());\n }\n\n return vector(sums.rbegin(), sums.rend());\n }\n\n private:\n // Returns the sum of the rhombus, where the top grid is (i, j) and the edge\n // size is `sz`.\n int getSum(const vector>& grid, int i, int j, int sz) {\n int x = i;\n int y = j;\n int sum = 0;\n\n // Go left down.\n for (int k = 0; k < sz; ++k)\n sum += grid[--x][++y];\n\n // Go right down.\n for (int k = 0; k < sz; ++k)\n sum += grid[++x][++y];\n\n // Go right up.\n for (int k = 0; k < sz; ++k)\n sum += grid[++x][--y];\n\n // Go left up.\n for (int k = 0; k < sz; ++k)\n sum += grid[--x][--y];\n\n return sum;\n }\n};\n"} +{"task_num": 1896, "task_title": "Minimum Cost to Change the Final Value of Expression", "difficulty": 3, "func_name": "minOperationsToFlip", "description": "You are given a valid boolean expression as a string `expression` consisting\nof the characters `'1'`,`'0'`,`'&'` (bitwise AND operator),`'|'` (bitwise OR\noperator),`'('`, and `')'`.\n\n* For example, `\"()1|1\"` and `\"(1)&()\"` are not valid while `\"1\"`, `\"(((1))|(0))\"`, and `\"1|(0&(1))\"` are valid expressions.\n\nReturn the minimum cost to change the final value of the expression.\n\n* For example, if `expression = \"1|1|(0&0)&1\"`, its value is `1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1`. We want to apply operations so that the new expression evaluates to `0`.\n\nThe cost of changing the final value of an expression is the number of\noperations performed on the expression. The types of operations are described\nas follows:\n\n* Turn a `'1'` into a `'0'`.\n* Turn a `'0'` into a `'1'`.\n* Turn a `'&'` into a `'|'`.\n* Turn a `'|'` into a `'&'`.\n\nNote: `'&'` does not take precedence over `'|'` in the order of calculation.\nEvaluate parentheses first, then in left-to-right order.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minOperationsToFlip(self, expression: str) -> int:\n stack = []\n\n for e in expression:\n if e in '(&|':\n stack.append((e, 0))\n continue\n if e == ')':\n lastPair = stack.pop()\n stack.pop()\n else: \n lastPair = (e, 1)\n if stack and stack[-1][0] in '&|':\n op = stack.pop()[0]\n a, costA = stack.pop()\n b, costB = lastPair\n if op == '&':\n if a == '0' and b == '0':\n lastPair = ('0', 1 + min(costA, costB))\n elif a == '0' and b == '1':\n lastPair = ('0', 1)\n elif a == '1' and b == '0':\n lastPair = ('0', 1)\n else:\n lastPair = ('1', min(costA, costB))\n else:\n if a == '0' and b == '0':\n lastPair = ('0', min(costA, costB))\n elif a == '0' and b == '1':\n lastPair = ('1', 1)\n elif a == '1' and b == '0':\n lastPair = ('1', 1)\n else:\n lastPair = ('1', 1 + min(costA, costB))\n stack.append(lastPair)\n\n return stack[-1][1]\n", "java_solution": "class Solution {\n public int minOperationsToFlip(String expression) {\n // [(the expression, the cost to toggle the expression)]\n Deque> stack = new ArrayDeque<>();\n Pair lastPair = null;\n\n for (final char e : expression.toCharArray()) {\n if (e == '(' || e == '&' || e == '|') {\n // These aren't expressions, so the cost is meaningless.\n stack.push(new Pair<>(e, 0));\n continue;\n }\n if (e == ')') {\n lastPair = stack.pop();\n stack.pop(); // Pop '('.\n } else { // e == '0' || e == '1'\n // Store the '0' or '1'. The cost to change their values is just 1,\n // whether it's changing '0' to '1' or '1' to '0'.\n lastPair = new Pair<>(e, 1);\n }\n if (!stack.isEmpty() && (stack.peek().getKey() == '&' || stack.peek().getKey() == '|')) {\n final char op = stack.pop().getKey();\n final char a = stack.peek().getKey();\n final int costA = stack.pop().getValue();\n final char b = lastPair.getKey();\n final int costB = lastPair.getValue();\n // Determine the cost to toggle op(a, b).\n if (op == '&') {\n if (a == '0' && b == '0')\n // Change '&' to '|' and a|b to '1'.\n lastPair = new Pair<>('0', 1 + Math.min(costA, costB));\n else if (a == '0' && b == '1')\n // Change '&' to '|'.\n lastPair = new Pair<>('0', 1);\n else if (a == '1' && b == '0')\n // Change '&' to '|'.\n lastPair = new Pair<>('0', 1);\n else // a == '1' and b == '1'\n // Change a|b to '0'.\n lastPair = new Pair<>('1', Math.min(costA, costB));\n } else { // op == '|'\n if (a == '0' && b == '0')\n // Change a|b to '1'.\n lastPair = new Pair<>('0', Math.min(costA, costB));\n else if (a == '0' && b == '1')\n // Change '|' to '&'.\n lastPair = new Pair<>('1', 1);\n else if (a == '1' && b == '0')\n // Change '|' to '&'.\n lastPair = new Pair<>('1', 1);\n else // a == '1' and b == '1'\n // Change '|' to '&' and a|b to '0'.\n lastPair = new Pair<>('1', 1 + Math.min(costA, costB));\n }\n }\n stack.push(lastPair);\n }\n\n return stack.peek().getValue();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minOperationsToFlip(string expression) {\n // [(the expression, the cost to toggle the expression)]\n stack> stack;\n pair lastPair;\n\n for (const char e : expression) {\n if (e == '(' || e == '&' || e == '|') {\n // These aren't expressions, so the cost is meaningless.\n stack.push({e, 0});\n continue;\n }\n if (e == ')') {\n lastPair = stack.top();\n stack.pop();\n stack.pop(); // Pop '('.\n } else { // e == '0' || e == '1'\n // Store the '0' or '1'. The cost to change their values is just 1,\n // whether it's changing '0' to '1' or '1' to '0'.\n lastPair = {e, 1};\n }\n if (!stack.empty() &&\n (stack.top().first == '&' || stack.top().first == '|')) {\n const char op = stack.top().first;\n stack.pop();\n const auto [a, costA] = stack.top();\n stack.pop();\n const auto [b, costB] = lastPair;\n // Determine the cost to toggle op(a, b).\n if (op == '&') {\n if (a == '0' && b == '0')\n // Change '&' to '|' and a|b to '1'.\n lastPair = {'0', 1 + min(costA, costB)};\n else if (a == '0' && b == '1')\n // Change '&' to '|'.\n lastPair = {'0', 1};\n else if (a == '1' && b == '0')\n // Change '&' to '|'.\n lastPair = {'0', 1};\n else // a == '1' and b == '1'\n // Change a|b to '0'.\n lastPair = {'1', min(costA, costB)};\n } else { // op == '|'\n if (a == '0' && b == '0')\n // Change a|b to '1'.\n lastPair = {'0', min(costA, costB)};\n else if (a == '0' && b == '1')\n // Change '|' to '&'.\n lastPair = {'1', 1};\n else if (a == '1' && b == '0')\n // Change '|' to '&'.\n lastPair = {'1', 1};\n else // a == '1' and b == '1'\n // Change '|' to '&' and a|b to '0'.\n lastPair = {'1', 1 + min(costA, costB)};\n }\n }\n stack.push(lastPair);\n }\n\n return stack.top().second;\n }\n};\n"} +{"task_num": 1906, "task_title": "Minimum Absolute Difference Queries", "difficulty": 2, "func_name": "minDifference", "description": "The minimum absolute difference of an array `a` is defined as the minimum\nvalue of `|a[i] - a[j]|`, where `0 <= i < j < a.length` and `a[i] != a[j]`. If\nall elements of `a` are the same, the minimum absolute difference is `-1`.\n\n* For example, the minimum absolute difference of the array `[5,2,3,7,2]` is `|2 - 3| = 1`. Note that it is not `0` because `a[i]` and `a[j]` must be different.\n\nYou are given an integer array `nums` and the array `queries` where\n`queries[i] = [li, ri]`. For each query `i`, compute the minimum absolute\ndifference of the subarray `nums[li...ri]` containing the elements of `nums`\nbetween the 0-based indices `li` and `ri` (inclusive).\n\nReturn an array `ans` where `ans[i]` is the answer to the `ith` query.\n\nA subarray is a contiguous sequence of elements in an array.\n\nThe value of `|x|` is defined as:\n\n* `x` if `x >= 0`.\n* `-x` if `x < 0`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom bisect import bisect_left\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n numToIndices = [[] for _ in range(101)]\n\n for i, num in enumerate(nums):\n numToIndices[num].append(i)\n\n if len(numToIndices[nums[0]]) == len(nums):\n return [-1] * len(queries)\n\n ans = []\n\n for l, r in queries:\n prevNum = -1\n minDiff = 101\n for num in range(1, 101):\n indices = numToIndices[num]\n i = bisect_left(indices, l)\n if i == len(indices) or indices[i] > r:\n continue\n if prevNum != -1:\n minDiff = min(minDiff, num - prevNum)\n prevNum = num\n ans.append(-1 if minDiff == 101 else minDiff)\n\n return ans\n", "java_solution": "class Solution {\n public int[] minDifference(int[] nums, int[][] queries) {\n int[] ans = new int[queries.length];\n List[] numToIndices = new List[101];\n\n for (int i = 1; i <= 100; ++i)\n numToIndices[i] = new ArrayList<>();\n\n for (int i = 0; i < nums.length; ++i)\n numToIndices[nums[i]].add(i);\n\n if (numToIndices[nums[0]].size() == nums.length) {\n Arrays.fill(ans, -1);\n return ans;\n }\n\n for (int i = 0; i < queries.length; ++i) {\n final int l = queries[i][0];\n final int r = queries[i][1];\n int prevNum = -1;\n int minDiff = 101;\n for (int num = 1; num <= 100; ++num) {\n List indices = numToIndices[num];\n final int j = firstGreaterEqual(indices, l);\n if (j == indices.size() || indices.get(j) > r)\n continue;\n if (prevNum != -1)\n minDiff = Math.min(minDiff, num - prevNum);\n prevNum = num;\n }\n ans[i] = minDiff == 101 ? -1 : minDiff;\n }\n\n return ans;\n }\n\n private int firstGreaterEqual(List A, int target) {\n final int i = Collections.binarySearch(A, target);\n return i < 0 ? -i - 1 : i;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector minDifference(vector& nums, vector>& queries) {\n vector> numToIndices(101);\n\n for (int i = 0; i < nums.size(); ++i)\n numToIndices[nums[i]].push_back(i);\n\n if (numToIndices[nums[0]].size() == nums.size())\n return vector(queries.size(), -1);\n\n vector ans;\n\n for (const vector& query : queries) {\n const int l = query[0];\n const int r = query[1];\n int prevNum = -1;\n int minDiff = 101;\n for (int num = 1; num <= 100; ++num) {\n const auto& indices = numToIndices[num];\n const auto it = ranges::lower_bound(indices, l);\n if (it == indices.cend() || *it > r)\n continue;\n if (prevNum != -1)\n minDiff = min(minDiff, num - prevNum);\n prevNum = num;\n }\n ans.push_back(minDiff == 101 ? -1 : minDiff);\n }\n\n return ans;\n }\n};\n"} +{"task_num": 1923, "task_title": "Longest Common Subpath", "difficulty": 3, "func_name": "longestCommonSubpath", "description": "There is a country of `n` cities numbered from `0` to `n - 1`. In this\ncountry, there is a road connecting every pair of cities.\n\nThere are `m` friends numbered from `0` to `m - 1` who are traveling through\nthe country. Each one of them will take a path consisting of some cities. Each\npath is represented by an integer array that contains the visited cities in\norder. The path may contain a city more than once, but the same city will not\nbe listed consecutively.\n\nGiven an integer `n` and a 2D integer array `paths` where `paths[i]` is an\ninteger array representing the path of the `ith` friend, return the length of\nthe longest common subpath that is shared by every friend's path, or `0` if\nthere is no common subpath at all.\n\nA subpath of a path is a contiguous sequence of cities within that path.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator, Set\n\nclass Solution:\n def __init__(self):\n self.kMod = 8_417_508_174_513\n self.kBase = 165_131\n\n def longestCommonSubpath(self, n: int, paths: List[List[int]]) -> int:\n l = 0\n r = len(paths[0])\n\n while l < r:\n m = l + (r - l + 1) // 2\n if self._checkCommonSubpath(paths, m):\n l = m\n else:\n r = m - 1\n\n return l\n\n def _checkCommonSubpath(self, paths: List[List[int]], m: int) -> bool:\n hashSets = [self._rabinKarp(path, m) for path in paths]\n\n for subpathHash in hashSets[0]:\n if all(subpathHash in hashSet for hashSet in hashSets):\n return True\n\n return False\n\n def _rabinKarp(self, path: List[int], m: int) -> Set[int]:\n hashes = set()\n maxPower = 1\n hash = 0\n\n for i, num in enumerate(path):\n hash = (hash * self.kBase + num) % self.kMod\n if i >= m:\n hash = (hash - path[i - m] * maxPower % self.kMod + self.kMod) % self.kMod\n else:\n maxPower = maxPower * self.kBase % self.kMod\n if i >= m - 1:\n hashes.add(hash)\n\n return hashes\n", "java_solution": "class Solution {\n public int longestCommonSubpath(int n, int[][] paths) {\n int l = 0;\n int r = paths[0].length;\n\n while (l < r) {\n final int m = l + (r - l + 1) / 2;\n if (checkCommonSubpath(paths, m))\n l = m;\n else\n r = m - 1;\n }\n\n return l;\n }\n\n private static final long BASE = 165_131L;\n private static final long HASH = 8_417_508_174_513L;\n\n // Returns true if there's a common subpath of length m for all the paths.\n private boolean checkCommonSubpath(int[][] paths, int m) {\n Set[] hashSets = new Set[paths.length];\n\n // Calculate the hash values for subpaths of length m for every path.\n for (int i = 0; i < paths.length; ++i)\n hashSets[i] = rabinKarp(paths[i], m);\n\n // Check if there is a common subpath of length m.\n for (final long subpathHash : hashSets[0])\n if (Arrays.stream(hashSets).allMatch(hashSet -> hashSet.contains(subpathHash)))\n return true;\n\n return false;\n }\n\n // Returns the hash values for subpaths of length m in the path.\n private Set rabinKarp(int[] path, int m) {\n Set hashes = new HashSet<>();\n long maxPower = 1;\n long hash = 0;\n for (int i = 0; i < path.length; ++i) {\n hash = (hash * BASE + path[i]) % HASH;\n if (i >= m)\n hash = (hash - path[i - m] * maxPower % HASH + HASH) % HASH;\n else\n maxPower = maxPower * BASE % HASH;\n if (i >= m - 1)\n hashes.add(hash);\n }\n return hashes;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int longestCommonSubpath(int n, vector>& paths) {\n int l = 0;\n int r = paths[0].size();\n\n while (l < r) {\n const int m = l + (r - l + 1) / 2;\n if (checkCommonSubpath(paths, m))\n l = m;\n else\n r = m - 1;\n }\n\n return l;\n }\n\n static constexpr long kBase = 165'131;\n static constexpr long kHash = 8'417'508'174'513;\n\n // Returns true if there's a common subpath of length m for all the paths.\n bool checkCommonSubpath(const vector>& paths, int m) {\n vector> hashSets;\n\n // Calculate the hash values for subpaths of length m for every path.\n for (const vector& path : paths)\n hashSets.push_back(rabinKarp(path, m));\n\n // Check if there is a common subpath of length m.\n for (const long subpathHash : hashSets[0])\n if (ranges::all_of(hashSets,\n [subpathHash](const unordered_set& hashSet) {\n return hashSet.contains(subpathHash);\n }))\n return true;\n\n return false;\n }\n\n // Returns the hash values for subpaths of length m in the path.\n unordered_set rabinKarp(const vector& path, int m) {\n unordered_set hashes;\n long maxPower = 1;\n long hash = 0;\n for (int i = 0; i < path.size(); ++i) {\n hash = (hash * kBase + path[i]) % kHash;\n if (i >= m)\n hash = (hash - path[i - m] * maxPower % kHash + kHash) % kHash;\n else\n maxPower = maxPower * kBase % kHash;\n if (i >= m - 1)\n hashes.insert(hash);\n }\n return hashes;\n }\n};\n"} +{"task_num": 1926, "task_title": "Nearest Exit from Entrance in Maze", "difficulty": 2, "func_name": "nearestExit", "description": "You are given an `m x n` matrix `maze` (0-indexed) with empty cells\n(represented as `'.'`) and walls (represented as `'+'`). You are also given\nthe `entrance` of the maze, where `entrance = [entrancerow, entrancecol]`\ndenotes the row and column of the cell you are initially standing at.\n\nIn one step, you can move one cell up, down, left, or right. You cannot step\ninto a cell with a wall, and you cannot step outside the maze. Your goal is to\nfind the nearest exit from the `entrance`. An exit is defined as an empty cell\nthat is at the border of the `maze`. The `entrance` does not count as an exit.\n\nReturn the number of steps in the shortest path from the `entrance` to the\nnearest exit, or `-1` if no such path exists.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(maze)\n n = len(maze[0])\n ans = 0\n q = collections.deque([(entrance[0], entrance[1])])\n seen = {(entrance[0], entrance[1])}\n\n while q:\n ans += 1\n for _ in range(len(q)):\n i, j = q.popleft()\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if (x, y) in seen or maze[x][y] == '+':\n continue\n if x == 0 or x == m - 1 or y == 0 or y == n - 1:\n return ans\n q.append((x, y))\n seen.add((x, y))\n\n return -1\n", "java_solution": "class Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n final int m = maze.length;\n final int n = maze[0].length;\n Queue> q =\n new ArrayDeque<>(List.of(new Pair<>(entrance[0], entrance[1])));\n boolean[][] seen = new boolean[m][n];\n seen[entrance[0]][entrance[1]] = true;\n\n for (int step = 1; !q.isEmpty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n final int i = q.peek().getKey();\n final int j = q.poll().getValue();\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (seen[x][y] || maze[x][y] == '+')\n continue;\n if (x == 0 || x == m - 1 || y == 0 || y == n - 1)\n return step;\n q.offer(new Pair<>(x, y));\n seen[x][y] = true;\n }\n }\n\n return -1;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int nearestExit(vector>& maze, vector& entrance) {\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n const int m = maze.size();\n const int n = maze[0].size();\n queue> q{{{entrance[0], entrance[1]}}};\n vector> seen(m, vector(n));\n seen[entrance[0]][entrance[1]] = true;\n\n for (int step = 1; !q.empty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n const auto [i, j] = q.front();\n q.pop();\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (seen[x][y] || maze[x][y] == '+')\n continue;\n if (x == 0 || x == m - 1 || y == 0 || y == n - 1)\n return step;\n q.emplace(x, y);\n seen[x][y] = true;\n }\n }\n\n return -1;\n }\n};\n"} +{"task_num": 1928, "task_title": "Minimum Cost to Reach Destination in Time", "difficulty": 3, "func_name": "minCost", "description": "There is a country of `n` cities numbered from `0` to `n - 1` where all the\ncities are connected by bi-directional roads. The roads are represented as a\n2D integer array `edges` where `edges[i] = [xi, yi, timei]` denotes a road\nbetween cities `xi` and `yi` that takes `timei` minutes to travel. There may\nbe multiple roads of differing travel times connecting the same two cities,\nbut no road connects a city to itself.\n\nEach time you pass through a city, you must pay a passing fee. This is\nrepresented as a 0-indexed integer array `passingFees` of length `n` where\n`passingFees[j]` is the amount of dollars you must pay when you pass through\ncity `j`.\n\nIn the beginning, you are at city `0` and want to reach city `n - 1` in\n`maxTime` minutes or less. The cost of your journey is the summation of\npassing fees for each city that you passed through at some moment of your\njourney (including the source and destination cities).\n\nGiven `maxTime`, `edges`, and `passingFees`, return the minimum cost to\ncomplete your journey, or `-1` if you cannot complete it within `maxTime`\nminutes.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minCost(self, maxTime: int, edges: List[List[int]], passingFees: List[int]) -> int:\n n = len(passingFees)\n graph = [[] for _ in range(n)]\n\n for u, v, w in edges:\n graph[u].append((v, w))\n graph[v].append((u, w))\n\n return self._dijkstra(graph, 0, n - 1, maxTime, passingFees)\n\n def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, dst: int, maxTime: int, passingFees: List[int]) -> int:\n cost = [math.inf for _ in range(len(graph))]\n dist = [maxTime + 1 for _ in range(len(graph))]\n\n cost[src] = passingFees[src]\n dist[src] = 0\n minHeap = [(cost[src], dist[src], src)]\n\n while minHeap:\n currCost, d, u = heapq.heappop(minHeap)\n if u == dst:\n return cost[dst]\n if d > dist[u] and currCost > cost[u]:\n continue\n for v, w in graph[u]:\n if d + w > maxTime:\n continue\n if currCost + passingFees[v] < cost[v]:\n cost[v] = currCost + passingFees[v]\n dist[v] = d + w\n heapq.heappush(minHeap, (cost[v], dist[v], v))\n elif d + w < dist[v]:\n dist[v] = d + w\n heapq.heappush(minHeap, (currCost + passingFees[v], dist[v], v))\n\n return -1\n", "java_solution": "class Solution {\n public int minCost(int maxTime, int[][] edges, int[] passingFees) {\n final int n = passingFees.length;\n List>[] graph = new List[n];\n Arrays.setAll(graph, i -> new ArrayList<>());\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n final int t = edge[2];\n graph[u].add(new Pair<>(v, t));\n graph[v].add(new Pair<>(u, t));\n }\n\n return dijkstra(graph, 0, n - 1, maxTime, passingFees);\n }\n\n private int dijkstra(List>[] graph, int src, int dst, int maxTime,\n int[] passingFees) {\n int[] cost = new int[graph.length]; // cost[i] := the minimum cost to reach the i-th city\n int[] dist = new int[graph.length]; // dist[i] := the minimum distance to reach the i-th city\n Arrays.fill(cost, Integer.MAX_VALUE);\n Arrays.fill(dist, maxTime + 1);\n\n cost[0] = passingFees[0];\n dist[0] = 0;\n Queue minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) {\n { offer(new int[] {cost[src], dist[src], src}); } // (cost[u], dist[u], u)\n };\n\n while (!minHeap.isEmpty()) {\n final int currCost = minHeap.peek()[0];\n final int d = minHeap.peek()[1];\n final int u = minHeap.poll()[2];\n if (u == dst)\n return cost[dst];\n if (d > dist[u] && currCost > cost[u])\n continue;\n for (Pair pair : graph[u]) {\n final int v = pair.getKey();\n final int w = pair.getValue();\n if (d + w > maxTime)\n continue;\n // Go from x -> y\n if (currCost + passingFees[v] < cost[v]) {\n cost[v] = currCost + passingFees[v];\n dist[v] = d + w;\n minHeap.offer(new int[] {cost[v], dist[v], v});\n } else if (d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.offer(new int[] {currCost + passingFees[v], dist[v], v});\n }\n }\n }\n\n return -1;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minCost(int maxTime, vector>& edges,\n vector& passingFees) {\n const int n = passingFees.size();\n vector>> graph(n);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n const int w = edge[2];\n graph[u].emplace_back(v, w);\n graph[v].emplace_back(u, w);\n }\n\n return dijkstra(graph, 0, n - 1, maxTime, passingFees);\n }\n\n private:\n int dijkstra(const vector>>& graph, int src, int dst,\n int maxTime, const vector& passingFees) {\n // cost[i] := the minimum cost to reach the i-th city\n vector cost(graph.size(), INT_MAX);\n // dist[i] := the minimum time to reach the i-th city\n vector dist(graph.size(), maxTime + 1);\n\n cost[src] = passingFees[src];\n dist[src] = 0;\n using T = tuple; // (cost[u], dist[u], u)\n priority_queue, greater<>> minHeap;\n minHeap.emplace(cost[src], dist[src], src);\n\n while (!minHeap.empty()) {\n const auto [currCost, d, u] = minHeap.top();\n minHeap.pop();\n if (u == dst)\n return cost[dst];\n if (d > dist[u] && currCost > cost[u])\n continue;\n for (const auto& [v, w] : graph[u]) {\n if (d + w > maxTime)\n continue;\n // Go from u -> v.\n if (currCost + passingFees[v] < cost[v]) {\n cost[v] = currCost + passingFees[v];\n dist[v] = d + w;\n minHeap.emplace(cost[v], dist[v], v);\n } else if (d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.emplace(currCost + passingFees[v], dist[v], v);\n }\n }\n }\n\n return -1;\n }\n};\n"} +{"task_num": 1938, "task_title": "Maximum Genetic Difference Query", "difficulty": 3, "func_name": "maxGeneticDifference", "description": "There is a rooted tree consisting of `n` nodes numbered `0` to `n - 1`. Each\nnode's number denotes its unique genetic value (i.e. the genetic value of node\n`x` is `x`). The genetic difference between two genetic values is defined as\nthe bitwise-XOR of their values. You are given the integer array `parents`,\nwhere `parents[i]` is the parent for node `i`. If node `x` is the root of the\ntree, then `parents[x] == -1`.\n\nYou are also given the array `queries` where `queries[i] = [nodei, vali]`. For\neach query `i`, find the maximum genetic difference between `vali` and `pi`,\nwhere `pi` is the genetic value of any node that is on the path between\n`nodei` and the root (including `nodei` and the root). More formally, you want\nto maximize `vali XOR pi`.\n\nReturn an array `ans` where `ans[i]` is the answer to the `ith` query.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass TrieNode:\n def __init__(self):\n self.children = [None] * 2\n self.count = 0\n\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n self.kHeight = 17\n\n def update(self, num: int, val: int) -> None:\n node = self.root\n for i in range(self.kHeight, -1, -1):\n bit = (num >> i) & 1\n if not node.children[bit]:\n node.children[bit] = TrieNode()\n node = node.children[bit]\n node.count += val\n\n def query(self, num: int) -> int:\n ans = 0\n node = self.root\n for i in range(self.kHeight, -1, -1):\n bit = (num >> i) & 1\n targetBit = bit ^ 1\n if node.children[targetBit] and node.children[targetBit].count > 0:\n ans += 1 << i\n node = node.children[targetBit]\n else:\n node = node.children[targetBit ^ 1]\n return ans\n\n\nclass Solution:\n def maxGeneticDifference(self, parents: List[int], queries: List[List[int]]) -> List[int]:\n n = len(parents)\n ans = [0] * len(queries)\n rootVal = -1\n tree = [[] for _ in range(n)]\n nodeToQueries = collections.defaultdict(list)\n trie = Trie()\n\n for i, parent in enumerate(parents):\n if parent == -1:\n rootVal = i\n else:\n tree[parent].append(i)\n\n for i, (node, val) in enumerate(queries):\n nodeToQueries[node].append((i, val))\n\n def dfs(node: int) -> None:\n trie.update(node, 1)\n\n for i, val in nodeToQueries[node]:\n ans[i] = trie.query(val)\n\n for child in tree[node]:\n dfs(child)\n\n trie.update(node, -1)\n\n dfs(rootVal)\n return ans\n", "java_solution": "class TrieNode {\n public TrieNode[] children = new TrieNode[2];\n public int count = 0;\n}\n\nclass Trie {\n public void update(int num, int val) {\n TrieNode node = root;\n for (int i = HEIGHT; i >= 0; --i) {\n final int bit = (num >> i) & 1;\n if (node.children[bit] == null)\n node.children[bit] = new TrieNode();\n node = node.children[bit];\n node.count += val;\n }\n }\n\n public int query(int num) {\n int ans = 0;\n TrieNode node = root;\n for (int i = HEIGHT; i >= 0; --i) {\n final int bit = (num >> i) & 1;\n final int targetBit = bit ^ 1;\n if (node.children[targetBit] != null && node.children[targetBit].count > 0) {\n ans += 1 << i;\n node = node.children[targetBit];\n } else {\n node = node.children[targetBit ^ 1];\n }\n }\n return ans;\n }\n\n private static final int HEIGHT = 17;\n TrieNode root = new TrieNode();\n}\n\nclass Solution {\n public int[] maxGeneticDifference(int[] parents, int[][] queries) {\n final int n = parents.length;\n int[] ans = new int[queries.length];\n int rootVal = -1;\n List[] tree = new List[n];\n\n for (int i = 0; i < n; ++i)\n tree[i] = new ArrayList<>();\n\n // {node: (index, val)}\n Map>> nodeToQueries = new HashMap<>();\n Trie trie = new Trie();\n\n for (int i = 0; i < parents.length; ++i)\n if (parents[i] == -1)\n rootVal = i;\n else\n tree[parents[i]].add(i);\n\n for (int i = 0; i < queries.length; ++i) {\n final int node = queries[i][0];\n final int val = queries[i][1];\n nodeToQueries.putIfAbsent(node, new ArrayList<>());\n nodeToQueries.get(node).add(new Pair<>(i, val));\n }\n\n dfs(rootVal, trie, tree, nodeToQueries, ans);\n return ans;\n }\n\n private void dfs(int node, Trie trie, List[] tree,\n Map>> nodeToQueries, int[] ans) {\n trie.update(node, 1);\n\n if (nodeToQueries.containsKey(node))\n for (Pair query : nodeToQueries.get(node)) {\n final int i = query.getKey();\n final int val = query.getValue();\n ans[i] = trie.query(val);\n }\n\n for (final int child : tree[node])\n dfs(child, trie, tree, nodeToQueries, ans);\n\n trie.update(node, -1);\n }\n}\n", "cpp_solution": "struct TrieNode {\n vector> children;\n int count = 0;\n TrieNode() : children(2) {}\n};\n\nclass Trie {\n public:\n void update(int num, int val) {\n shared_ptr node = root;\n for (int i = kHeight; i >= 0; --i) {\n const int bit = (num >> i) & 1;\n if (node->children[bit] == nullptr)\n node->children[bit] = make_shared();\n node = node->children[bit];\n node->count += val;\n }\n }\n\n int query(int num) {\n int ans = 0;\n shared_ptr node = root;\n for (int i = kHeight; i >= 0; --i) {\n const int bit = (num >> i) & 1;\n const int targetBit = bit ^ 1;\n if (node->children[targetBit] && node->children[targetBit]->count) {\n ans += 1 << i;\n node = node->children[targetBit];\n } else {\n node = node->children[targetBit ^ 1];\n }\n }\n return ans;\n }\n\n private:\n static constexpr int kHeight = 17;\n shared_ptr root = make_shared();\n};\n\nclass Solution {\n public:\n vector maxGeneticDifference(vector& parents,\n vector>& queries) {\n const int n = parents.size();\n vector ans(queries.size());\n int rootVal = -1;\n vector> tree(n);\n // {node: (index, val)}\n unordered_map>> nodeToQueries;\n Trie trie;\n\n for (int i = 0; i < parents.size(); ++i)\n if (parents[i] == -1)\n rootVal = i;\n else\n tree[parents[i]].push_back(i);\n\n for (int i = 0; i < queries.size(); ++i) {\n const int node = queries[i][0];\n const int val = queries[i][1];\n nodeToQueries[node].emplace_back(i, val);\n }\n\n dfs(rootVal, trie, tree, nodeToQueries, ans);\n return ans;\n }\n\n private:\n void dfs(int node, Trie& trie, const vector>& tree,\n const unordered_map>>& nodeToQueries,\n vector& ans) {\n trie.update(node, 1);\n\n if (const auto it = nodeToQueries.find(node); it != nodeToQueries.cend())\n for (const auto& [i, val] : it->second)\n ans[i] = trie.query(val);\n\n for (const int child : tree[node])\n dfs(child, trie, tree, nodeToQueries, ans);\n\n trie.update(node, -1);\n }\n};\n"} +{"task_num": 1971, "task_title": "Find if Path Exists in Graph", "difficulty": 1, "func_name": "validPath", "description": "There is a bi-directional graph with `n` vertices, where each vertex is\nlabeled from `0` to `n - 1` (inclusive). The edges in the graph are\nrepresented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]`\ndenotes a bi-directional edge between vertex `ui` and vertex `vi`. Every\nvertex pair is connected by at most one edge, and no vertex has an edge to\nitself.\n\nYou want to determine if there is a valid path that exists from vertex\n`source` to vertex `destination`.\n\nGiven `edges` and the integers `n`, `source`, and `destination`, return `true`\nif there is a valid path from `source` to `destination`, or `false` otherwise.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self.find(u)\n j = self.find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:\n uf = UnionFind(n)\n\n for u, v in edges:\n uf.unionByRank(u, v)\n\n return uf.find(source) == uf.find(destination)\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public void unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n public int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n\n private int[] id;\n private int[] rank;\n}\n\nclass Solution {\n public boolean validPath(int n, int[][] edges, int source, int destination) {\n UnionFind uf = new UnionFind(n);\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n uf.unionByRank(u, v);\n }\n\n return uf.find(source) == uf.find(destination);\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n), rank(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n void unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n\n private:\n vector id;\n vector rank;\n};\n\nclass Solution {\n public:\n bool validPath(int n, vector>& edges, int source,\n int destination) {\n UnionFind uf(n);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n uf.unionByRank(u, v);\n }\n\n return uf.find(source) == uf.find(destination);\n }\n};\n"} +{"task_num": 1976, "task_title": "Number of Ways to Arrive at Destination", "difficulty": 2, "func_name": "countPaths", "description": "You are in a city that consists of `n` intersections numbered from `0` to `n -\n1` with bi-directional roads between some intersections. The inputs are\ngenerated such that you can reach any intersection from any other intersection\nand that there is at most one road between any two intersections.\n\nYou are given an integer `n` and a 2D integer array `roads` where `roads[i] =\n[ui, vi, timei]` means that there is a road between intersections `ui` and\n`vi` that takes `timei` minutes to travel. You want to know in how many ways\nyou can travel from intersection `0` to intersection `n - 1` in the shortest\namount of time.\n\nReturn the number of ways you can arrive at your destination in the shortest\namount of time. Since the answer may be large, return it modulo `109 + 7`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def countPaths(self, n: int, roads: List[List[int]]) -> int:\n graph = [[] for _ in range(n)]\n\n for u, v, w in roads:\n graph[u].append((v, w))\n graph[v].append((u, w))\n\n return self._dijkstra(graph, 0, n - 1)\n\n def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, dst: int) -> int:\n kMod = 10**9 + 7\n ways = [0] * len(graph)\n dist = [math.inf] * len(graph)\n\n ways[src] = 1\n dist[src] = 0\n minHeap = [(dist[src], src)]\n\n while minHeap:\n d, u = heapq.heappop(minHeap)\n if d > dist[u]:\n continue\n for v, w in graph[u]:\n if d + w < dist[v]:\n dist[v] = d + w\n ways[v] = ways[u]\n heapq.heappush(minHeap, (dist[v], v))\n elif d + w == dist[v]:\n ways[v] += ways[u]\n ways[v] %= kMod\n\n return ways[dst]\n", "java_solution": "class Solution {\n public int countPaths(int n, int[][] roads) {\n List>[] graph = new List[n];\n\n for (int i = 0; i < n; i++)\n graph[i] = new ArrayList<>();\n\n for (int[] road : roads) {\n final int u = road[0];\n final int v = road[1];\n final int w = road[2];\n graph[u].add(new Pair<>(v, w));\n graph[v].add(new Pair<>(u, w));\n }\n\n return dijkstra(graph, 0, n - 1);\n }\n\n private int dijkstra(List>[] graph, int src, int dst) {\n final int MOD = 1_000_000_007;\n long[] ways = new long[graph.length];\n Arrays.fill(ways, 0);\n long[] dist = new long[graph.length];\n Arrays.fill(dist, Long.MAX_VALUE);\n\n ways[src] = 1;\n dist[src] = 0;\n Queue> minHeap =\n new PriorityQueue<>(Comparator.comparingLong(Pair::getKey)) {\n { offer(new Pair<>(dist[src], src)); }\n };\n\n while (!minHeap.isEmpty()) {\n final long d = minHeap.peek().getKey();\n final int u = minHeap.poll().getValue();\n if (d > dist[u])\n continue;\n for (Pair pair : graph[u]) {\n final int v = pair.getKey();\n final int w = pair.getValue();\n if (d + w < dist[v]) {\n dist[v] = d + w;\n ways[v] = ways[u];\n minHeap.offer(new Pair<>(dist[v], v));\n } else if (d + w == dist[v]) {\n ways[v] += ways[u];\n ways[v] %= MOD;\n }\n }\n }\n\n return (int) ways[dst];\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int countPaths(int n, vector>& roads) {\n vector>> graph(n);\n\n for (const vector& road : roads) {\n const int u = road[0];\n const int v = road[1];\n const int w = road[2];\n graph[u].emplace_back(v, w);\n graph[v].emplace_back(u, w);\n }\n\n return dijkstra(graph, 0, n - 1);\n }\n\n private:\n // Similar to 1786. Number of Restricted Paths From First to Last Node\n int dijkstra(const vector>>& graph, int src, int dst) {\n constexpr int kMod = 1'000'000'007;\n vector ways(graph.size());\n vector dist(graph.size(), LONG_MAX);\n\n ways[src] = 1;\n dist[src] = 0;\n using P = pair; // (d, u)\n priority_queue, greater<>> minHeap;\n minHeap.emplace(dist[src], src);\n\n while (!minHeap.empty()) {\n const auto [d, u] = minHeap.top();\n minHeap.pop();\n if (d > dist[u])\n continue;\n for (const auto& [v, w] : graph[u])\n if (d + w < dist[v]) {\n dist[v] = d + w;\n ways[v] = ways[u];\n minHeap.emplace(dist[v], v);\n } else if (d + w == dist[v]) {\n ways[v] += ways[u];\n ways[v] %= kMod;\n }\n }\n\n return ways[dst];\n }\n};\n"} +{"task_num": 1977, "task_title": "Number of Ways to Separate Numbers", "difficulty": 3, "func_name": "numberOfCombinations", "description": "You wrote down many positive integers in a string called `num`. However, you\nrealized that you forgot to add commas to seperate the different numbers. You\nremember that the list of integers was non-decreasing and that no integer had\nleading zeros.\n\nReturn the number of possible lists of integers that you could have written\ndown to get the string `num`. Since the answer may be large, return it modulo\n`109 + 7`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def numberOfCombinations(self, num: str) -> int:\n if num[0] == '0':\n return 0\n\n kMod = 1_000_000_007\n n = len(num)\n dp = [[0] * (n + 1) for _ in range(n)]\n lcs = [[0] * (n + 1) for _ in range(n + 1)]\n\n for i in range(n - 1, -1, -1):\n for j in range(i + 1, n):\n if num[i] == num[j]:\n lcs[i][j] = lcs[i + 1][j + 1] + 1\n\n for i in range(n):\n for k in range(1, i + 2):\n dp[i][k] += dp[i][k - 1]\n dp[i][k] %= kMod\n s = i - k + 1\n if num[s] == '0':\n continue\n if s == 0:\n dp[i][k] += 1\n continue\n if s < k:\n dp[i][k] += dp[s - 1][s]\n continue\n l = lcs[s - k][s]\n if l >= k or num[s - k + l] <= num[s + l]:\n dp[i][k] += dp[s - 1][k]\n else:\n dp[i][k] += dp[s - 1][k - 1]\n\n return dp[n - 1][n] % kMod\n", "java_solution": "class Solution {\n public int numberOfCombinations(String num) {\n if (num.charAt(0) == '0')\n return 0;\n\n final int MOD = 1_000_000_007;\n final int n = num.length();\n // dp[i][k] := the number of possible lists of integers ending in num[i] with\n // the length of the last number being 1..k\n long[][] dp = new long[n][n + 1];\n // lcs[i][j] := the number of the same digits in num[i..n) and num[j..n)\n int[][] lcs = new int[n + 1][n + 1];\n\n for (int i = n - 1; i >= 0; --i)\n for (int j = i + 1; j < n; ++j)\n if (num.charAt(i) == num.charAt(j))\n lcs[i][j] = lcs[i + 1][j + 1] + 1;\n\n for (int i = 0; i < n; ++i)\n for (int k = 1; k <= i + 1; ++k) {\n dp[i][k] += dp[i][k - 1];\n dp[i][k] %= MOD;\n // The last number is num[s..i].\n final int s = i - k + 1;\n if (num.charAt(s) == '0')\n // the number of possible lists of integers ending in num[i] with the\n // length of the last number being k\n continue;\n if (s == 0) {\n // the whole string\n dp[i][k] += 1;\n continue;\n }\n if (s < k) {\n // The length k is not enough, so add the number of possible lists of\n // integers in num[0..s - 1].\n dp[i][k] += dp[s - 1][s];\n continue;\n }\n final int l = lcs[s - k][s];\n if (l >= k || num.charAt(s - k + l) <= num.charAt(s + l))\n // Have enough length k and num[s - k..s - 1] <= num[j..i].\n dp[i][k] += dp[s - 1][k];\n else\n // Have enough length k but num[s - k..s - 1] > num[j..i].\n dp[i][k] += dp[s - 1][k - 1];\n }\n\n return (int) dp[n - 1][n] % MOD;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int numberOfCombinations(string num) {\n if (num[0] == '0')\n return 0;\n\n constexpr int kMod = 1'000'000'007;\n const int n = num.size();\n // dp[i][k] := the number of possible lists of integers ending in num[i]\n // with the length of the last number being 1..k\n vector> dp(n, vector(n + 1));\n // lcs[i][j] := the number of the same digits in num[i..n) and num[j..n)\n vector> lcs(n + 1, vector(n + 1));\n\n for (int i = n - 1; i >= 0; --i)\n for (int j = i + 1; j < n; ++j)\n if (num[i] == num[j])\n lcs[i][j] = lcs[i + 1][j + 1] + 1;\n\n for (int i = 0; i < n; ++i)\n for (int k = 1; k <= i + 1; ++k) {\n dp[i][k] += dp[i][k - 1];\n dp[i][k] %= kMod;\n // The last number is num[s..i].\n const int s = i - k + 1;\n if (num[s] == '0')\n // the number of possible lists of integers ending in num[i] with the\n // length of the last number being k\n continue;\n if (s == 0) {\n // the whole string\n dp[i][k] += 1;\n continue;\n }\n if (s < k) {\n // The length k is not enough, so add the number of possible lists of\n // integers in num[0..s - 1].\n dp[i][k] += dp[s - 1][s];\n continue;\n }\n const int l = lcs[s - k][s];\n if (l >= k || num[s - k + l] <= num[s + l])\n // Have enough length k and num[s - k..s - 1] <= num[j..i].\n dp[i][k] += dp[s - 1][k];\n else\n // Have enough length k but num[s - k..s - 1] > num[j..i].\n dp[i][k] += dp[s - 1][k - 1];\n }\n\n return dp[n - 1][n] % kMod;\n }\n};\n"} +{"task_num": 1994, "task_title": "The Number of Good Subsets", "difficulty": 3, "func_name": "numberOfGoodSubsets", "description": "You are given an integer array `nums`. We call a subset of `nums` good if its\nproduct can be represented as a product of one or more distinct prime numbers.\n\n* For example, if `nums = [1, 2, 3, 4]`: \n* `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are good subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3` respectively.\n* `[1, 4]` and `[4]` are not good subsets with products `4 = 2*2` and `4 = 2*2` respectively.\n\nReturn the number of different good subsets in `nums` modulo `109 + 7`.\n\nA subset of `nums` is any array that can be obtained by deleting some\n(possibly none or all) elements from `nums`. Two subsets are different if and\nonly if the chosen indices to delete are different.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def numberOfGoodSubsets(self, nums: List[int]) -> int:\n kMod = 1_000_000_007\n primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n n = 1 << len(primes)\n dp = [1] + [0] * (n - 1)\n count = collections.Counter(nums)\n\n for num, freq in count.items():\n if num == 1:\n continue\n if any(num % squared == 0 for squared in [4, 9, 25]):\n continue\n numPrimesMask = 0\n for i, prime in enumerate(primes):\n if num % prime == 0:\n numPrimesMask += 1 << i\n for primesMask in range(n):\n if primesMask & numPrimesMask > 0:\n continue\n nextPrimesMask = numPrimesMask | primesMask\n dp[nextPrimesMask] += dp[primesMask] * freq\n dp[nextPrimesMask] %= kMod\n\n return (1 << count[1]) * sum(dp[1:]) % kMod\n", "java_solution": "class Solution {\n public int numberOfGoodSubsets(int[] nums) {\n final int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};\n final int n = 1 << primes.length;\n final int maxNum = Arrays.stream(nums).max().getAsInt();\n long[] dp = new long[n];\n int[] count = new int[maxNum + 1];\n\n dp[0] = 1;\n\n for (final int num : nums)\n ++count[num];\n\n for (int num = 2; num <= maxNum; ++num) {\n if (count[num] == 0)\n continue;\n if (num % 4 == 0 || num % 9 == 0 || num % 25 == 0)\n continue;\n final int numPrimesMask = getPrimesMask(num, primes);\n for (int primesMask = 0; primesMask < n; ++primesMask) {\n if ((primesMask & numPrimesMask) > 0)\n continue;\n final int nextPrimesMask = primesMask | numPrimesMask;\n dp[nextPrimesMask] += dp[primesMask] * count[num];\n dp[nextPrimesMask] %= MOD;\n }\n }\n\n return (int) (modPow(2, count[1]) * ((Arrays.stream(dp).sum() - 1) % MOD) % MOD);\n }\n\n private static final int MOD = 1_000_000_007;\n\n private int getPrimesMask(int num, int[] primes) {\n int primesMask = 0;\n for (int i = 0; i < primes.length; ++i)\n if (num % primes[i] == 0)\n primesMask |= 1 << i;\n return primesMask;\n }\n\n private long modPow(long x, long n) {\n if (n == 0)\n return 1;\n if (n % 2 == 1)\n return x * modPow(x, n - 1) % MOD;\n return modPow(x * x % MOD, n / 2);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int numberOfGoodSubsets(vector& nums) {\n const vector primes{2, 3, 5, 7, 11, 13, 17, 19, 23, 29};\n const int n = 1 << primes.size();\n const int maxNum = ranges::max(nums);\n vector dp(n);\n vector count(maxNum + 1);\n\n dp[0] = 1;\n\n for (const int num : nums)\n ++count[num];\n\n for (int num = 2; num <= maxNum; ++num) {\n if (count[num] == 0)\n continue;\n if (num % 4 == 0 || num % 9 == 0 || num % 25 == 0)\n continue;\n const int numPrimesMask = getPrimesMask(num, primes);\n for (int primesMask = 0; primesMask < n; ++primesMask) {\n if ((primesMask & numPrimesMask) > 0)\n continue;\n const int nextPrimesMask = primesMask | numPrimesMask;\n dp[nextPrimesMask] += dp[primesMask] * count[num];\n dp[nextPrimesMask] %= kMod;\n }\n }\n\n return modPow(2, count[1]) *\n (accumulate(dp.begin() + 1, dp.end(), 0L) % kMod) % kMod;\n }\n\n private:\n static constexpr int kMod = 1'000'000'007;\n\n int getPrimesMask(int num, const vector& primes) {\n int primesMask = 0;\n for (int i = 0; i < primes.size(); ++i)\n if (num % primes[i] == 0)\n primesMask |= 1 << i;\n return primesMask;\n }\n\n long modPow(long x, long n) {\n if (n == 0)\n return 1;\n if (n % 2 == 1)\n return x * modPow(x % kMod, (n - 1)) % kMod;\n return modPow(x * x % kMod, (n / 2)) % kMod;\n }\n};\n"} +{"task_num": 1998, "task_title": "GCD Sort of an Array", "difficulty": 3, "func_name": "gcdSort", "description": "You are given an integer array `nums`, and you can perform the following\noperation any number of times on `nums`:\n\n* Swap the positions of two elements `nums[i]` and `nums[j]` if `gcd(nums[i], nums[j]) > 1` where `gcd(nums[i], nums[j])` is the greatest common divisor of `nums[i]` and `nums[j]`.\n\nReturn `true` if it is possible to sort `nums` in non-decreasing order using\nthe above swap method, or `false` otherwise.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self.find(u)\n j = self.find(v)\n if i == j:\n return False\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n return True\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def gcdSort(self, nums: List[int]) -> bool:\n maxNum = max(nums)\n minPrimeFactors = self._sieveEratosthenes(maxNum + 1)\n uf = UnionFind(maxNum + 1)\n\n for num in nums:\n for primeFactor in self._getPrimeFactors(num, minPrimeFactors):\n uf.unionByRank(num, primeFactor)\n\n for a, b in zip(nums, sorted(nums)):\n if uf.find(a) != uf.find(b):\n return False\n\n return True\n\n def _sieveEratosthenes(self, n: int) -> List[int]:\n minPrimeFactors = [i for i in range(n + 1)]\n for i in range(2, int(n**0.5) + 1):\n if minPrimeFactors[i] == i:\n for j in range(i * i, n, i):\n minPrimeFactors[j] = min(minPrimeFactors[j], i)\n return minPrimeFactors\n\n def _getPrimeFactors(self, num: int, minPrimeFactors: List[int]) -> List[int]:\n primeFactors = []\n while num > 1:\n divisor = minPrimeFactors[num]\n primeFactors.append(divisor)\n while num % divisor == 0:\n num //= divisor\n return primeFactors\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public void unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n public int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n\n private int[] id;\n private int[] rank;\n}\n\nclass Solution {\n public boolean gcdSort(int[] nums) {\n final int mx = Arrays.stream(nums).max().getAsInt();\n final int[] minPrimeFactors = sieveEratosthenes(mx + 1);\n UnionFind uf = new UnionFind(mx + 1);\n\n for (final int num : nums)\n for (final int primeFactor : getPrimeFactors(num, minPrimeFactors))\n uf.unionByRank(num, primeFactor);\n\n int[] sortedNums = nums.clone();\n Arrays.sort(sortedNums);\n\n for (int i = 0; i < nums.length; ++i)\n // Can't swap nums[i] with sortedNums[i].\n if (uf.find(nums[i]) != uf.find(sortedNums[i]))\n return false;\n\n return true;\n }\n\n // Gets the minimum prime factor of i, where 1 < i <= n.\n private int[] sieveEratosthenes(int n) {\n int[] minPrimeFactors = new int[n + 1];\n for (int i = 2; i <= n; ++i)\n minPrimeFactors[i] = i;\n for (int i = 2; i * i < n; ++i)\n if (minPrimeFactors[i] == i) // `i` is prime.\n for (int j = i * i; j < n; j += i)\n minPrimeFactors[j] = Math.min(minPrimeFactors[j], i);\n return minPrimeFactors;\n }\n\n private List getPrimeFactors(int num, int[] minPrimeFactors) {\n List primeFactors = new ArrayList<>();\n while (num > 1) {\n final int divisor = minPrimeFactors[num];\n primeFactors.add(divisor);\n while (num % divisor == 0)\n num /= divisor;\n }\n return primeFactors;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n), rank(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n void unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n\n private:\n vector id;\n vector rank;\n};\n\nclass Solution {\n public:\n bool gcdSort(vector& nums) {\n const int mx = ranges::max(nums);\n const vector minPrimeFactors = sieveEratosthenes(mx + 1);\n UnionFind uf(mx + 1);\n\n for (const int num : nums)\n for (const int primeFactor : getPrimeFactors(num, minPrimeFactors))\n uf.unionByRank(num, primeFactor);\n\n vector sortedNums(nums);\n ranges::sort(sortedNums);\n\n for (int i = 0; i < nums.size(); ++i)\n // Can't swap nums[i] with sortedNums[i].\n if (uf.find(nums[i]) != uf.find(sortedNums[i]))\n return false;\n\n return true;\n }\n\n private:\n // Gets the minimum prime factor of i, where 1 < i <= n.\n vector sieveEratosthenes(int n) {\n vector minPrimeFactors(n + 1);\n iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2);\n for (int i = 2; i * i < n; ++i)\n if (minPrimeFactors[i] == i) // `i` is prime.\n for (int j = i * i; j < n; j += i)\n minPrimeFactors[j] = min(minPrimeFactors[j], i);\n return minPrimeFactors;\n }\n\n vector getPrimeFactors(int num, const vector& minPrimeFactors) {\n vector primeFactors;\n while (num > 1) {\n const int divisor = minPrimeFactors[num];\n primeFactors.push_back(divisor);\n while (num % divisor == 0)\n num /= divisor;\n }\n return primeFactors;\n }\n};\n"} +{"task_num": 2019, "task_title": "The Score of Students Solving Math Expression", "difficulty": 3, "func_name": "scoreOfStudents", "description": "You are given a string `s` that contains digits `0-9`, addition symbols `'+'`,\nand multiplication symbols `'*'` only, representing a valid math expression of\nsingle digit numbers (e.g., `3+5*2`). This expression was given to `n`\nelementary school students. The students were instructed to get the answer of\nthe expression by following this order of operations:\n\n1. Compute multiplication, reading from left to right; Then,\n2. Compute addition, reading from left to right.\n\nYou are given an integer array `answers` of length `n`, which are the\nsubmitted answers of the students in no particular order. You are asked to\ngrade the `answers`, by following these rules:\n\n* If an answer equals the correct answer of the expression, this student will be rewarded `5` points;\n* Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic, this student will be rewarded `2` points;\n* Otherwise, this student will be rewarded `0` points.\n\nReturn the sum of the points of the students.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nimport operator\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def scoreOfStudents(self, s: str, answers: List[int]) -> int:\n n = len(s) // 2 + 1\n ans = 0\n func = {'+': operator.add, '*': operator.mul}\n dp = [[set() for j in range(n)] for _ in range(n)]\n\n for i in range(n):\n dp[i][i].add(int(s[i * 2]))\n\n for d in range(1, n):\n for i in range(n - d):\n j = i + d\n for k in range(i, j):\n op = s[k * 2 + 1]\n for a in dp[i][k]:\n for b in dp[k + 1][j]:\n res = func[op](a, b)\n if res <= 1000:\n dp[i][j].add(res)\n\n correctAnswer = eval(s)\n\n for answer, freq in collections.Counter(answers).items():\n if answer == correctAnswer:\n ans += 5 * freq\n elif answer in dp[0][n - 1]:\n ans += 2 * freq\n\n return ans\n", "java_solution": "class Solution {\n public int scoreOfStudents(String s, int[] answers) {\n final int n = s.length() / 2 + 1;\n int ans = 0;\n Set[][] dp = new Set[n][n];\n Map count = new HashMap<>();\n\n for (int i = 0; i < n; ++i)\n for (int j = i; j < n; ++j)\n dp[i][j] = new HashSet<>();\n\n for (int i = 0; i < n; ++i)\n dp[i][i].add(s.charAt(i * 2) - '0');\n\n for (int d = 1; d < n; ++d)\n for (int i = 0; i + d < n; ++i) {\n final int j = i + d;\n for (int k = i; k < j; ++k) {\n final char op = s.charAt(k * 2 + 1);\n for (final int a : dp[i][k])\n for (final int b : dp[k + 1][j]) {\n final int res = func(op, a, b);\n if (res <= 1000)\n dp[i][j].add(res);\n }\n }\n }\n\n final int correctAnswer = eval(s);\n\n for (final int answer : answers)\n count.merge(answer, 1, Integer::sum);\n\n for (final int answer : count.keySet())\n if (answer == correctAnswer)\n ans += 5 * count.get(answer);\n else if (dp[0][n - 1].contains(answer))\n ans += 2 * count.get(answer);\n\n return ans;\n }\n\n private int eval(final String s) {\n int ans = 0;\n int currNum = 0;\n int prevNum = 0;\n char op = '+';\n\n for (int i = 0; i < s.length(); ++i) {\n final char c = s.charAt(i);\n if (Character.isDigit(c))\n currNum = currNum * 10 + (c - '0');\n if (!Character.isDigit(c) || i == s.length() - 1) {\n if (op == '+') {\n ans += prevNum;\n prevNum = currNum;\n } else if (op == '*') {\n prevNum = prevNum * currNum;\n }\n op = c;\n currNum = 0;\n }\n }\n\n return ans + prevNum;\n }\n\n private int func(char op, int a, int b) {\n if (op == '+')\n return a + b;\n return a * b;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int scoreOfStudents(string s, vector& answers) {\n const int n = s.length() / 2 + 1;\n const unordered_map> func{\n {'+', plus()}, {'*', multiplies()}};\n int ans = 0;\n vector>> dp(n, vector>(n));\n unordered_map count;\n\n for (int i = 0; i < n; ++i)\n dp[i][i].insert(s[i * 2] - '0');\n\n for (int d = 1; d < n; ++d)\n for (int i = 0; i + d < n; ++i) {\n const int j = i + d;\n for (int k = i; k < j; ++k) {\n const char op = s[k * 2 + 1];\n for (const int a : dp[i][k])\n for (const int b : dp[k + 1][j]) {\n const int res = func.at(op)(a, b);\n if (res <= 1000)\n dp[i][j].insert(res);\n }\n }\n }\n\n const int correctAnswer = eval(s);\n\n for (const int answer : answers)\n ++count[answer];\n\n for (const auto& [answer, freq] : count)\n if (answer == correctAnswer)\n ans += 5 * freq;\n else if (dp[0][n - 1].contains(answer))\n ans += 2 * freq;\n\n return ans;\n }\n\n private:\n int eval(const string& s) {\n int ans = 0;\n int prevNum = 0;\n int currNum = 0;\n char op = '+';\n\n for (int i = 0; i < s.length(); ++i) {\n const char c = s[i];\n if (isdigit(c))\n currNum = currNum * 10 + (c - '0');\n if (!isdigit(c) || i == s.length() - 1) {\n if (op == '+') {\n ans += prevNum;\n prevNum = currNum;\n } else if (op == '*') {\n prevNum = prevNum * currNum;\n }\n op = c;\n currNum = 0;\n }\n }\n\n return ans + prevNum;\n }\n};\n"} +{"task_num": 2030, "task_title": "Smallest K-Length Subsequence With Occurrences of a Letter", "difficulty": 3, "func_name": "smallestSubsequence", "description": "You are given a string `s`, an integer `k`, a letter `letter`, and an integer\n`repetition`.\n\nReturn the lexicographically smallest subsequence of `s` of length `k` that\nhas the letter `letter` appear at least `repetition` times. The test cases are\ngenerated so that the `letter` appears in `s` at least `repetition` times.\n\nA subsequence is a string that can be derived from another string by deleting\nsome or no characters without changing the order of the remaining characters.\n\nA string `a` is lexicographically smaller than a string `b` if in the first\nposition where `a` and `b` differ, string `a` has a letter that appears\nearlier in the alphabet than the corresponding letter in `b`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:\n stack = []\n required = repetition\n nLetters = s.count(letter)\n\n for i, c in enumerate(s):\n while stack and stack[-1] > c and len(stack) + len(s) - i - 1 >= k and (stack[-1] != letter or nLetters > required):\n if stack.pop() == letter:\n required += 1\n if len(stack) < k:\n if c == letter:\n stack.append(c)\n required -= 1\n elif k - len(stack) > required:\n stack.append(c)\n if c == letter:\n nLetters -= 1\n\n return ''.join(stack)\n", "java_solution": "class Solution {\n public String smallestSubsequence(String s, int k, char letter, int repetition) {\n StringBuilder sb = new StringBuilder();\n Deque stack = new ArrayDeque<>();\n int required = repetition;\n int nLetters = (int) s.chars().filter(c -> c == letter).count();\n\n for (int i = 0; i < s.length(); ++i) {\n final char c = s.charAt(i);\n while (!stack.isEmpty() && stack.peek() > c && stack.size() + s.length() - i - 1 >= k &&\n (stack.peek() != letter || nLetters > required))\n if (stack.pop() == letter)\n ++required;\n if (stack.size() < k)\n if (c == letter) {\n stack.push(c);\n --required;\n } else if (k - stack.size() > required) {\n stack.push(c);\n }\n if (c == letter)\n --nLetters;\n }\n\n for (final char c : stack)\n sb.append(c);\n\n return sb.reverse().toString();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n string smallestSubsequence(string s, int k, char letter, int repetition) {\n string ans;\n vector stack;\n int required = repetition;\n int nLetters = ranges::count(s, letter);\n\n for (int i = 0; i < s.length(); ++i) {\n const char c = s[i];\n while (!stack.empty() && stack.back() > c &&\n stack.size() + s.length() - i - 1 >= k &&\n (stack.back() != letter || nLetters > required)) {\n const char popped = stack.back();\n stack.pop_back();\n if (popped == letter)\n ++required;\n }\n if (stack.size() < k)\n if (c == letter) {\n stack.push_back(c);\n --required;\n } else if (k > stack.size() + required) {\n stack.push_back(c);\n }\n if (c == letter)\n --nLetters;\n }\n\n for (const char c : stack)\n ans += c;\n\n return ans;\n }\n};\n"} +{"task_num": 2040, "task_title": "Kth Smallest Product of Two Sorted Arrays", "difficulty": 3, "func_name": "kthSmallestProduct", "description": "Given two sorted 0-indexed integer arrays `nums1` and `nums2` as well as an\ninteger `k`, return the `kth` (1-based) smallest product of `nums1[i] *\nnums2[j]` where `0 <= i < nums1.length` and `0 <= j < nums2.length`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int:\n A1 = [-num for num in nums1 if num < 0][::-1]\n A2 = [num for num in nums1 if num >= 0]\n B1 = [-num for num in nums2 if num < 0][::-1]\n B2 = [num for num in nums2 if num >= 0]\n\n negCount = len(A1) * len(B2) + len(A2) * len(B1)\n\n if k > negCount:\n k -= negCount\n sign = 1\n else:\n k = negCount - k + 1\n sign = -1\n B1, B2 = B2, B1\n\n def numProductNoGreaterThan(A: List[int], B: List[int], m: int) -> int:\n ans = 0\n j = len(B) - 1\n for i in range(len(A)):\n while j >= 0 and A[i] * B[j] > m:\n j -= 1\n ans += j + 1\n return ans\n\n l = 0\n r = 10**10\n\n while l < r:\n m = (l + r) // 2\n if numProductNoGreaterThan(A1, B1, m) + numProductNoGreaterThan(A2, B2, m) >= k:\n r = m\n else:\n l = m + 1\n\n return sign * l\n", "java_solution": "class Solution {\n public long kthSmallestProduct(int[] nums1, int[] nums2, long k) {\n List A1 = new ArrayList<>();\n List A2 = new ArrayList<>();\n List B1 = new ArrayList<>();\n List B2 = new ArrayList<>();\n\n seperate(nums1, A1, A2);\n seperate(nums2, B1, B2);\n\n final long negCount = A1.size() * B2.size() + A2.size() * B1.size();\n int sign = 1;\n\n if (k > negCount) {\n k -= negCount; // Find the (k - negCount)-th positive.\n } else {\n k = negCount - k + 1; // Find the (negCount - k + 1)-th abs(negative).\n sign = -1;\n List temp = B1;\n B1 = B2;\n B2 = temp;\n }\n\n long l = 0;\n long r = (long) 1e10;\n\n while (l < r) {\n final long m = (l + r) / 2;\n if (numProductNoGreaterThan(A1, B1, m) + numProductNoGreaterThan(A2, B2, m) >= k)\n r = m;\n else\n l = m + 1;\n }\n\n return sign * l;\n }\n\n private void seperate(int[] arr, List A1, List A2) {\n for (final int a : arr)\n if (a < 0)\n A1.add(-a);\n else\n A2.add(a);\n Collections.reverse(A1); // Reverse to sort ascending\n }\n\n private long numProductNoGreaterThan(List A, List B, long m) {\n long count = 0;\n int j = B.size() - 1;\n // For each a, find the first index j s.t. a * B[j] <= m\n // So numProductNoGreaterThan m for this row will be j + 1\n for (final long a : A) {\n while (j >= 0 && a * B.get(j) > m)\n --j;\n count += j + 1;\n }\n return count;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n long long kthSmallestProduct(vector& nums1, vector& nums2,\n long long k) {\n vector A1;\n vector A2;\n vector B1;\n vector B2;\n\n seperate(nums1, A1, A2);\n seperate(nums2, B1, B2);\n\n const long negCount = A1.size() * B2.size() + A2.size() * B1.size();\n int sign = 1;\n\n if (k > negCount) {\n k -= negCount; // Find the (k - negCount)-th positive.\n } else {\n k = negCount - k + 1; // Find the (negCount - k + 1)-th abs(negative).\n sign = -1;\n swap(B1, B2);\n }\n\n long l = 0;\n long r = 1e10;\n\n while (l < r) {\n const long m = (l + r) / 2;\n if (numProductNoGreaterThan(A1, B1, m) +\n numProductNoGreaterThan(A2, B2, m) >=\n k)\n r = m;\n else\n l = m + 1;\n }\n\n return sign * l;\n }\n\n private:\n void seperate(const vector& arr, vector& A1, vector& A2) {\n for (const int a : arr)\n if (a < 0)\n A1.push_back(-a);\n else\n A2.push_back(a);\n ranges::reverse(A1); // Reverse to sort ascending\n }\n\n long numProductNoGreaterThan(const vector& A, const vector& B,\n long m) {\n long count = 0;\n int j = B.size() - 1;\n // For each a, find the first index j s.t. a * B[j] <= m\n // So numProductNoGreaterThan m for this row will be j + 1\n for (const long a : A) {\n while (j >= 0 && a * B[j] > m)\n --j;\n count += j + 1;\n }\n return count;\n }\n};\n"} +{"task_num": 2045, "task_title": "Second Minimum Time to Reach Destination", "difficulty": 3, "func_name": "secondMinimum", "description": "A city is represented as a bi-directional connected graph with `n` vertices\nwhere each vertex is labeled from `1` to `n` (inclusive). The edges in the\ngraph are represented as a 2D integer array `edges`, where each `edges[i] =\n[ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`.\nEvery vertex pair is connected by at most one edge, and no vertex has an edge\nto itself. The time taken to traverse any edge is `time` minutes.\n\nEach vertex has a traffic signal which changes its color from green to red and\nvice versa every `change` minutes. All signals change at the same time. You\ncan enter a vertex at any time, but can leave a vertex only when the signal is\ngreen. You cannot wait at a vertex if the signal is green.\n\nThe second minimum value is defined as the smallest value strictly larger than\nthe minimum value.\n\n* For example the second minimum value of `[2, 3, 4]` is `3`, and the second minimum value of `[2, 2, 4]` is `4`.\n\nGiven `n`, `edges`, `time`, and `change`, return the second minimum time it\nwill take to go from vertex `1` to vertex `n`.\n\nNotes:\n\n* You can go through any vertex any number of times, including `1` and `n`.\n* You can assume that when the journey starts, all signals have just turned green.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:\n graph = [[] for _ in range(n + 1)]\n q = collections.deque([(1, 0)])\n minTime = [[math.inf] * 2 for _ in range(n + 1)]\n minTime[1][0] = 0\n\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n\n while q:\n i, prevTime = q.popleft()\n\n numChangeSignal = prevTime // change\n waitTime = change - (prevTime % change) if numChangeSignal & 1 else 0\n newTime = prevTime + waitTime + time\n for j in graph[i]:\n if newTime < minTime[j][0]:\n minTime[j][0] = newTime\n q.append((j, newTime))\n elif minTime[j][0] < newTime < minTime[j][1]:\n if j == n:\n return newTime\n minTime[j][1] = newTime\n q.append((j, newTime))\n", "java_solution": "class Solution {\n public int secondMinimum(int n, int[][] edges, int time, int change) {\n List[] graph = new List[n + 1];\n // (index, time)\n Queue> q = new ArrayDeque<>(List.of(new Pair<>(1, 0)));\n // minTime[u][0] := the first minimum time to reach the node u\n // minTime[u][1] := the second minimum time to reach the node u\n int[][] minTime = new int[n + 1][2];\n Arrays.stream(minTime).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));\n minTime[1][0] = 0;\n\n for (int i = 1; i <= n; ++i)\n graph[i] = new ArrayList<>();\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n graph[u].add(v);\n graph[v].add(u);\n }\n\n while (!q.isEmpty()) {\n final int u = q.peek().getKey();\n final int prevTime = q.poll().getValue();\n // Start from green.\n // If `numChangeSignal` is odd, now red.\n // If `numChangeSignal` is even, now green.\n final int numChangeSignal = prevTime / change;\n final int waitTime = numChangeSignal % 2 == 0 ? 0 : change - prevTime % change;\n final int newTime = prevTime + waitTime + time;\n for (final int v : graph[u])\n if (newTime < minTime[v][0]) {\n minTime[v][0] = newTime;\n q.offer(new Pair<>(v, newTime));\n } else if (minTime[v][0] < newTime && newTime < minTime[v][1]) {\n if (v == n)\n return newTime;\n minTime[v][1] = newTime;\n q.offer(new Pair<>(v, newTime));\n }\n }\n\n throw new IllegalArgumentException();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int secondMinimum(int n, vector>& edges, int time, int change) {\n vector> graph(n + 1);\n queue> q{{{1, 0}}};\n // minTime[u][0] := the first minimum time to reach the node u\n // minTime[u][1] := the second minimum time to reach the node u\n vector> minTime(n + 1, vector(2, INT_MAX));\n minTime[1][0] = 0;\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n graph[u].push_back(v);\n graph[v].push_back(u);\n }\n\n while (!q.empty()) {\n const auto [u, prevTime] = q.front();\n q.pop();\n // Start from green.\n // If `numChangeSignal` is odd, now red.\n // If `numChangeSignal` is even, now green.\n const int numChangeSignal = prevTime / change;\n const int waitTime =\n numChangeSignal % 2 == 0 ? 0 : change - prevTime % change;\n const int newTime = prevTime + waitTime + time;\n for (const int v : graph[u])\n if (newTime < minTime[v][0]) {\n minTime[v][0] = newTime;\n q.emplace(v, newTime);\n } else if (minTime[v][0] < newTime && newTime < minTime[v][1]) {\n if (v == n)\n return newTime;\n minTime[v][1] = newTime;\n q.emplace(v, newTime);\n }\n }\n\n throw;\n }\n};\n"} +{"task_num": 2059, "task_title": "Minimum Operations to Convert Number", "difficulty": 2, "func_name": "minimumOperations", "description": "You are given a 0-indexed integer array `nums` containing distinct numbers, an\ninteger `start`, and an integer `goal`. There is an integer `x` that is\ninitially set to `start`, and you want to perform operations on `x` such that\nit is converted to `goal`. You can perform the following operation repeatedly\non the number `x`:\n\nIf `0 <= x <= 1000`, then for any index `i` in the array (`0 <= i <\nnums.length`), you can set `x` to any of the following:\n\n* `x + nums[i]`\n* `x - nums[i]`\n* `x ^ nums[i]` (bitwise-XOR)\n\nNote that you can use each `nums[i]` any number of times in any order.\nOperations that set `x` to be out of the range `0 <= x <= 1000` are valid, but\nno more operations can be done afterward.\n\nReturn the minimum number of operations needed to convert `x = start` into\n`goal`, and `-1` if it is not possible.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumOperations(self, nums: List[int], start: int, goal: int) -> int:\n ans = 0\n q = collections.deque([start])\n seen = {start}\n\n while q:\n ans += 1\n for _ in range(len(q)):\n x = q.popleft()\n for num in nums:\n for res in (x + num, x - num, x ^ num):\n if res == goal:\n return ans\n if res < 0 or res > 1000 or res in seen:\n continue\n seen.add(res)\n q.append(res)\n\n return -1\n", "java_solution": "class Solution {\n public int minimumOperations(int[] nums, int start, int goal) {\n Queue q = new ArrayDeque<>(List.of(start));\n boolean[] seen = new boolean[1001];\n seen[start] = true;\n\n for (int step = 1; !q.isEmpty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n final int x = q.poll();\n for (final int num : nums) {\n for (final int res : new int[] {x + num, x - num, x ^ num}) {\n if (res == goal)\n return step;\n if (res < 0 || res > 1000 || seen[res])\n continue;\n seen[res] = true;\n q.offer(res);\n }\n }\n }\n\n return -1;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minimumOperations(vector& nums, int start, int goal) {\n queue q{{start}};\n vector seen(1001);\n seen[start] = true;\n\n for (int step = 1; !q.empty(); ++step)\n for (int sz = q.size(); sz > 0; --sz) {\n const int x = q.front();\n q.pop();\n for (const int num : nums) {\n for (const int res : {x + num, x - num, x ^ num}) {\n if (res == goal)\n return step;\n if (res < 0 || res > 1000 || seen[res])\n continue;\n seen[res] = true;\n q.push(res);\n }\n }\n }\n\n return -1;\n }\n};\n"} +{"task_num": 2076, "task_title": "Process Restricted Friend Requests", "difficulty": 3, "func_name": "friendRequests", "description": "You are given an integer `n` indicating the number of people in a network.\nEach person is labeled from `0` to `n - 1`.\n\nYou are also given a 0-indexed 2D integer array `restrictions`, where\n`restrictions[i] = [xi, yi]` means that person `xi` and person `yi` cannot\nbecome friends, either directly or indirectly through other people.\n\nInitially, no one is friends with each other. You are given a list of friend\nrequests as a 0-indexed 2D integer array `requests`, where `requests[j] = [uj,\nvj]` is a friend request between person `uj` and person `vj`.\n\nA friend request is successful if `uj` and `vj` can be friends. Each friend\nrequest is processed in the given order (i.e., `requests[j]` occurs before\n`requests[j + 1]`), and upon a successful request, `uj` and `vj` become direct\nfriends for all future friend requests.\n\nReturn a boolean array `result`, where each `result[j]` is `true` if the `jth`\nfriend request is successful or `false` if it is not.\n\nNote: If `uj` and `vj` are already direct friends, the request is still\nsuccessful.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self.find(u)\n j = self.find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def friendRequests(self, n: int, restrictions: List[List[int]], requests: List[List[int]]) -> List[bool]:\n ans = []\n uf = UnionFind(n)\n\n for u, v in requests:\n pu = uf.find(u)\n pv = uf.find(v)\n isValid = True\n if pu != pv:\n for x, y in restrictions:\n px = uf.find(x)\n py = uf.find(y)\n if (pu, pv) in [(px, py), (py, px)]:\n isValid = False\n break\n ans.append(isValid)\n if isValid:\n uf.unionByRank(pu, pv)\n\n return ans\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public void unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n public int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n\n private int[] id;\n private int[] rank;\n}\n\nclass Solution {\n public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) {\n boolean[] ans = new boolean[requests.length];\n UnionFind uf = new UnionFind(n);\n\n for (int i = 0; i < requests.length; ++i) {\n final int pu = uf.find(requests[i][0]);\n final int pv = uf.find(requests[i][1]);\n boolean isValid = true;\n if (pu != pv)\n for (int[] restriction : restrictions) {\n final int px = uf.find(restriction[0]);\n final int py = uf.find(restriction[1]);\n if (pu == px && pv == py || pu == py && pv == px) {\n isValid = false;\n break;\n }\n }\n ans[i] = isValid;\n if (isValid)\n uf.unionByRank(pu, pv);\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n), rank(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n void unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n\n private:\n vector id;\n vector rank;\n};\n\nclass Solution {\n public:\n vector friendRequests(int n, vector>& restrictions,\n vector>& requests) {\n vector ans;\n UnionFind uf(n);\n\n for (const vector& request : requests) {\n const int i = uf.find(request[0]);\n const int j = uf.find(request[1]);\n bool isValid = true;\n if (i != j)\n for (const vector& restriction : restrictions) {\n const int x = uf.find(restriction[0]);\n const int y = uf.find(restriction[1]);\n if (i == x && j == y || i == y && j == x) {\n isValid = false;\n break;\n }\n }\n ans.push_back(isValid);\n if (isValid)\n uf.unionByRank(i, j);\n }\n\n return ans;\n }\n};\n"} +{"task_num": 2086, "task_title": "Minimum Number of Buckets Required to Collect Rainwater from Houses", "difficulty": 2, "func_name": "minimumBuckets", "description": "You are given a 0-indexed string `hamsters` where `hamsters[i]` is either:\n\n* `'H'` indicating that there is a hamster at index `i`, or\n* `'.'` indicating that index `i` is empty.\n\nYou will add some number of food buckets at the empty indices in order to feed\nthe hamsters. A hamster can be fed if there is at least one food bucket to its\nleft or to its right. More formally, a hamster at index `i` can be fed if you\nplace a food bucket at index `i - 1` and/or at index `i + 1`.\n\nReturn the minimum number of food buckets you should place at empty indices to\nfeed all the hamsters or `-1` if it is impossible to feed all of them.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumBuckets(self, street: str) -> int:\n A = list(street)\n\n for i, c in enumerate(A):\n if c == 'H':\n if i > 0 and A[i - 1] == 'B':\n continue\n if i + 1 < len(A) and A[i + 1] == '.':\n A[i + 1] = 'B'\n elif i > 0 and A[i - 1] == '.':\n A[i - 1] = 'B'\n else:\n return -1\n\n return A.count('B')\n", "java_solution": "class Solution {\n public int minimumBuckets(String street) {\n final char[] A = street.toCharArray();\n\n for (int i = 0; i < A.length; ++i)\n if (A[i] == 'H') {\n if (i > 0 && A[i - 1] == 'B')\n continue;\n if (i + 1 < A.length && A[i + 1] == '.')\n // Always prefer place a bucket in (i + 1) because it enhances the\n // possibility to collect the upcoming houses.\n A[i + 1] = 'B';\n else if (i > 0 && A[i - 1] == '.')\n A[i - 1] = 'B';\n else\n return -1;\n }\n\n return (int) new String(A).chars().filter(a -> a == 'B').count();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minimumBuckets(string street) {\n for (int i = 0; i < street.length(); ++i)\n if (street[i] == 'H') {\n if (i > 0 && street[i - 1] == 'B')\n continue;\n if (i + 1 < street.length() && street[i + 1] == '.')\n // Always prefer place a bucket in (i + 1) because it enhances the\n // possibility to collect the upcoming houses.\n street[i + 1] = 'B';\n else if (i > 0 && street[i - 1] == '.')\n street[i - 1] = 'B';\n else\n return -1;\n }\n\n return ranges::count(street, 'B');\n }\n};\n"} +{"task_num": 2092, "task_title": "Find All People With Secret", "difficulty": 3, "func_name": "findAllPeople", "description": "You are given an integer `n` indicating there are `n` people numbered from `0`\nto `n - 1`. You are also given a 0-indexed 2D integer array `meetings` where\n`meetings[i] = [xi, yi, timei]` indicates that person `xi` and person `yi`\nhave a meeting at `timei`. A person may attend multiple meetings at the same\ntime. Finally, you are given an integer `firstPerson`.\n\nPerson `0` has a secret and initially shares the secret with a person\n`firstPerson` at time `0`. This secret is then shared every time a meeting\ntakes place with a person that has the secret. More formally, for every\nmeeting, if a person `xi` has the secret at `timei`, then they will share the\nsecret with person `yi`, and vice versa.\n\nThe secrets are shared instantaneously. That is, a person may receive the\nsecret and share it with people in other meetings within the same time frame.\n\nReturn a list of all the people that have the secret after all the meetings\nhave taken place. You may return the answer in any order.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n\n def connected(self, u: int, v: int) -> bool:\n return self._find(self.id[u]) == self._find(self.id[v])\n\n def reset(self, u: int) -> None:\n self.id[u] = u\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n uf = UnionFind(n)\n timeToPairs = collections.defaultdict(list)\n\n uf.unionByRank(0, firstPerson)\n\n for x, y, time in meetings:\n timeToPairs[time].append((x, y))\n\n for _, pairs in sorted(timeToPairs.items(), key=lambda x: x[0]):\n peopleUnioned = set()\n for x, y in pairs:\n uf.unionByRank(x, y)\n peopleUnioned.add(x)\n peopleUnioned.add(y)\n for person in peopleUnioned:\n if not uf.connected(person, 0):\n uf.reset(person)\n\n res=[]\n for i in range(n):\n if uf.connected(i, 0):\n res.append(i)\n return res\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n }\n\n public void unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n public boolean connected(int u, int v) {\n return find(u) == find(v);\n }\n\n public void reset(int u) {\n id[u] = u;\n }\n\n private int[] id;\n private int[] rank;\n\n private int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n}\n\nclass Solution {\n public List findAllPeople(int n, int[][] meetings, int firstPerson) {\n List ans = new ArrayList<>();\n UnionFind uf = new UnionFind(n);\n TreeMap>> timeToPairs = new TreeMap<>();\n\n uf.unionByRank(0, firstPerson);\n\n for (int[] meeting : meetings) {\n final int x = meeting[0];\n final int y = meeting[1];\n final int time = meeting[2];\n timeToPairs.putIfAbsent(time, new ArrayList<>());\n timeToPairs.get(time).add(new Pair<>(x, y));\n }\n\n for (List> pairs : timeToPairs.values()) {\n Set peopleUnioned = new HashSet<>();\n for (Pair pair : pairs) {\n final int x = pair.getKey();\n final int y = pair.getValue();\n uf.unionByRank(x, y);\n peopleUnioned.add(x);\n peopleUnioned.add(y);\n }\n for (final int person : peopleUnioned)\n if (!uf.connected(person, 0))\n uf.reset(person);\n }\n\n for (int i = 0; i < n; ++i)\n if (uf.connected(i, 0))\n ans.add(i);\n\n return ans;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n), rank(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n void unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n bool connected(int u, int v) {\n return find(u) == find(v);\n }\n\n void reset(int u) {\n id[u] = u;\n }\n\n private:\n vector id;\n vector rank;\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n};\n\nclass Solution {\n public:\n vector findAllPeople(int n, vector>& meetings,\n int firstPerson) {\n vector ans;\n UnionFind uf(n);\n map>> timeToPairs;\n\n uf.unionByRank(0, firstPerson);\n\n for (const vector& meeting : meetings) {\n const int x = meeting[0];\n const int y = meeting[1];\n const int time = meeting[2];\n timeToPairs[time].push_back({x, y});\n }\n\n for (const auto& [_, pairs] : timeToPairs) {\n unordered_set peopleUnioned;\n for (const auto& [x, y] : pairs) {\n uf.unionByRank(x, y);\n peopleUnioned.insert(x);\n peopleUnioned.insert(y);\n }\n for (const int person : peopleUnioned)\n if (!uf.connected(person, 0))\n uf.reset(person);\n }\n\n for (int i = 0; i < n; ++i)\n if (uf.connected(i, 0))\n ans.push_back(i);\n\n return ans;\n }\n};\n"} +{"task_num": 2115, "task_title": "Find All Possible Recipes from Given Supplies", "difficulty": 2, "func_name": "findAllRecipes", "description": "You have information about `n` different recipes. You are given a string array\n`recipes` and a 2D string array `ingredients`. The `ith` recipe has the name\n`recipes[i]`, and you can create it if you have all the needed ingredients\nfrom `ingredients[i]`. Ingredients to a recipe may need to be created from\nother recipes, i.e., `ingredients[i]` may contain a string that is in\n`recipes`.\n\nYou are also given a string array `supplies` containing all the ingredients\nthat you initially have, and you have an infinite supply of all of them.\n\nReturn a list of all the recipes that you can create. You may return the\nanswer in any order.\n\nNote that two recipes may contain each other in their ingredients.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n ans = []\n supplies = set(supplies)\n graph = collections.defaultdict(list)\n inDegrees = collections.Counter()\n q = collections.deque()\n\n for i, recipe in enumerate(recipes):\n for ingredient in ingredients[i]:\n if ingredient not in supplies:\n graph[ingredient].append(recipe)\n inDegrees[recipe] += 1\n\n for recipe in recipes:\n if inDegrees[recipe] == 0:\n q.append(recipe)\n\n while q:\n u = q.popleft()\n ans.append(u)\n for v in graph[u]:\n inDegrees[v] -= 1\n if inDegrees[v] == 0:\n q.append(v)\n\n return ans\n", "java_solution": "class Solution {\n public List findAllRecipes(String[] recipes, List> ingredients,\n String[] supplies) {\n List ans = new ArrayList<>();\n Set suppliesSet = new HashSet<>();\n for (final String supply : supplies)\n suppliesSet.add(supply);\n Map> graph = new HashMap<>();\n Map inDegrees = new HashMap<>();\n\n // Build the graph.\n for (int i = 0; i < recipes.length; ++i)\n for (final String ingredient : ingredients.get(i))\n if (!suppliesSet.contains(ingredient)) {\n graph.putIfAbsent(ingredient, new ArrayList<>());\n graph.get(ingredient).add(recipes[i]);\n inDegrees.merge(recipes[i], 1, Integer::sum);\n }\n\n // Perform topological sorting.\n Queue q = Arrays.stream(recipes)\n .filter(recipe -> inDegrees.getOrDefault(recipe, 0) == 0)\n .collect(Collectors.toCollection(ArrayDeque::new));\n\n while (!q.isEmpty()) {\n final String u = q.poll();\n ans.add(u);\n if (!graph.containsKey(u))\n continue;\n for (final String v : graph.get(u)) {\n inDegrees.merge(v, -1, Integer::sum);\n if (inDegrees.get(v) == 0)\n q.offer(v);\n }\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector findAllRecipes(vector& recipes,\n vector>& ingredients,\n vector& supplies) {\n vector ans;\n unordered_set suppliesSet(supplies.begin(), supplies.end());\n unordered_map> graph;\n unordered_map inDegrees;\n queue q;\n\n // Build the graph.\n for (int i = 0; i < recipes.size(); ++i)\n for (const string& ingredient : ingredients[i])\n if (!suppliesSet.contains(ingredient)) {\n graph[ingredient].push_back(recipes[i]);\n ++inDegrees[recipes[i]];\n }\n\n // Perform topological sorting.\n for (const string& recipe : recipes)\n if (!inDegrees.contains(recipe))\n q.push(recipe);\n\n while (!q.empty()) {\n const string u = q.front();\n q.pop();\n ans.push_back(u);\n if (!graph.contains(u))\n continue;\n for (const string& v : graph[u])\n if (--inDegrees[v] == 0)\n q.push(v);\n }\n\n return ans;\n }\n};\n"} +{"task_num": 2127, "task_title": "Maximum Employees to Be Invited to a Meeting", "difficulty": 3, "func_name": "maximumInvitations", "description": "A company is organizing a meeting and has a list of `n` employees, waiting to\nbe invited. They have arranged for a large circular table, capable of seating\nany number of employees.\n\nThe employees are numbered from `0` to `n - 1`. Each employee has a favorite\nperson and they will attend the meeting only if they can sit next to their\nfavorite person at the table. The favorite person of an employee is not\nthemself.\n\nGiven a 0-indexed integer array `favorite`, where `favorite[i]` denotes the\nfavorite person of the `ith` employee, return the maximum number of employees\nthat can be invited to the meeting.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nfrom enum import Enum\n\n\nclass State(Enum):\n kInit = 0\n kVisiting = 1\n kVisited = 2\n\n\nclass Solution:\n def maximumInvitations(self, favorite: List[int]) -> int:\n n = len(favorite)\n sumComponentsLength = 0\n graph = [[] for _ in range(n)]\n inDegrees = [0] * n\n maxChainLength = [1] * n\n\n for i, f in enumerate(favorite):\n graph[i].append(f)\n inDegrees[f] += 1\n\n q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0])\n\n while q:\n u = q.popleft()\n for v in graph[u]:\n inDegrees[v] -= 1\n if inDegrees[v] == 0:\n q.append(v)\n maxChainLength[v] = max(maxChainLength[v], 1 + maxChainLength[u])\n\n for i in range(n):\n if favorite[favorite[i]] == i:\n sumComponentsLength += maxChainLength[i] + maxChainLength[favorite[i]]\n\n maxCycleLength = 0\n parent = [-1] * n\n seen = set()\n states = [State.kInit] * n\n\n def findCycle(u: int) -> None:\n nonlocal maxCycleLength\n seen.add(u)\n states[u] = State.kVisiting\n for v in graph[u]:\n if v not in seen:\n parent[v] = u\n findCycle(v)\n elif states[v] == State.kVisiting:\n curr = u\n cycleLength = 1\n while curr != v:\n curr = parent[curr]\n cycleLength += 1\n maxCycleLength = max(maxCycleLength, cycleLength)\n states[u] = State.kVisited\n\n for i in range(n):\n if i not in seen:\n findCycle(i)\n\n return max(sumComponentsLength // 2, maxCycleLength)\n", "java_solution": "enum State { INIT, VISITING, VISITED }\n\nclass Solution {\n public int maximumInvitations(int[] favorite) {\n final int n = favorite.length;\n int sumComponentsLength = 0; // the component: a -> b -> c <-> x <- y\n List[] graph = new List[n];\n int[] inDegrees = new int[n];\n int[] maxChainLength = new int[n];\n Arrays.fill(maxChainLength, 1);\n Arrays.setAll(graph, i -> new ArrayList<>());\n\n // Build the graph.\n for (int i = 0; i < n; ++i) {\n graph[i].add(favorite[i]);\n ++inDegrees[favorite[i]];\n }\n\n // Perform topological sorting.\n Queue q = IntStream.range(0, n)\n .filter(i -> inDegrees[i] == 0)\n .boxed()\n .collect(Collectors.toCollection(ArrayDeque::new));\n\n while (!q.isEmpty()) {\n final int u = q.poll();\n for (final int v : graph[u]) {\n if (--inDegrees[v] == 0)\n q.offer(v);\n maxChainLength[v] = Math.max(maxChainLength[v], 1 + maxChainLength[u]);\n }\n }\n\n for (int i = 0; i < n; ++i)\n if (favorite[favorite[i]] == i)\n // i <-> favorite[i] (the cycle's length = 2)\n sumComponentsLength += maxChainLength[i] + maxChainLength[favorite[i]];\n\n int[] parent = new int[n];\n Arrays.fill(parent, -1);\n boolean[] seen = new boolean[n];\n State[] states = new State[n];\n\n for (int i = 0; i < n; ++i)\n if (!seen[i])\n findCycle(graph, i, parent, seen, states);\n\n return Math.max(sumComponentsLength / 2, maxCycleLength);\n }\n\n private int maxCycleLength = 0; // the cycle : a -> b -> c -> a\n\n private void findCycle(List[] graph, int u, int[] parent, boolean[] seen,\n State[] states) {\n seen[u] = true;\n states[u] = State.VISITING;\n\n for (final int v : graph[u]) {\n if (!seen[v]) {\n parent[v] = u;\n findCycle(graph, v, parent, seen, states);\n } else if (states[v] == State.VISITING) {\n // Find the cycle's length.\n int curr = u;\n int cycleLength = 1;\n while (curr != v) {\n curr = parent[curr];\n ++cycleLength;\n }\n maxCycleLength = Math.max(maxCycleLength, cycleLength);\n }\n }\n\n states[u] = State.VISITED;\n }\n}\n", "cpp_solution": "enum class State { kInit, kVisiting, kVisited };\n\nclass Solution {\n public:\n int maximumInvitations(vector& favorite) {\n const int n = favorite.size();\n int sumComponentsLength = 0; // the component: a -> b -> c <-> x <- y\n vector> graph(n);\n vector inDegrees(n);\n vector maxChainLength(n, 1);\n queue q;\n\n // Build the graph.\n for (int i = 0; i < n; ++i) {\n graph[i].push_back(favorite[i]);\n ++inDegrees[favorite[i]];\n }\n\n // Perform topological sorting.\n for (int i = 0; i < n; ++i)\n if (inDegrees[i] == 0)\n q.push(i);\n\n while (!q.empty()) {\n const int u = q.front();\n q.pop();\n for (const int v : graph[u]) {\n if (--inDegrees[v] == 0)\n q.push(v);\n maxChainLength[v] = max(maxChainLength[v], 1 + maxChainLength[u]);\n }\n }\n\n for (int i = 0; i < n; ++i)\n if (favorite[favorite[i]] == i)\n // i <-> favorite[i] (the cycle's length = 2)\n sumComponentsLength += maxChainLength[i] + maxChainLength[favorite[i]];\n\n int maxCycleLength = 0; // the cycle : a -> b -> c -> a\n vector parent(n, -1);\n vector seen(n);\n vector states(n);\n\n for (int i = 0; i < n; ++i)\n if (!seen[i])\n findCycle(graph, i, parent, seen, states, maxCycleLength);\n\n return max(sumComponentsLength / 2, maxCycleLength);\n }\n\n private:\n void findCycle(const vector>& graph, int u, vector& parent,\n vector& seen, vector& states,\n int& maxCycleLength) {\n seen[u] = true;\n states[u] = State::kVisiting;\n\n for (const int v : graph[u]) {\n if (!seen[v]) {\n parent[v] = u;\n findCycle(graph, v, parent, seen, states, maxCycleLength);\n } else if (states[v] == State::kVisiting) {\n // Find the cycle's length.\n int curr = u;\n int cycleLength = 1;\n while (curr != v) {\n curr = parent[curr];\n ++cycleLength;\n }\n maxCycleLength = max(maxCycleLength, cycleLength);\n }\n }\n\n states[u] = State::kVisited;\n }\n};\n"} +{"task_num": 2132, "task_title": "Stamping the Grid", "difficulty": 3, "func_name": "possibleToStamp", "description": "You are given an `m x n` binary matrix `grid` where each cell is either `0`\n(empty) or `1` (occupied).\n\nYou are then given stamps of size `stampHeight x stampWidth`. We want to fit\nthe stamps such that they follow the given restrictions and requirements:\n\n1. Cover all the empty cells.\n2. Do not cover any of the occupied cells.\n3. We can put as many stamps as we want.\n4. Stamps can overlap with each other.\n5. Stamps are not allowed to be rotated.\n6. Stamps must stay completely inside the grid.\n\nReturn `true` if it is possible to fit the stamps while following the given\nrestrictions and requirements. Otherwise, return `false`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def possibleToStamp(self, grid: List[List[int]], stampHeight: int, stampWidth: int) -> bool:\n m = len(grid)\n n = len(grid[0])\n A = [[0] * (n + 1) for _ in range(m + 1)]\n B = [[0] * (n + 1) for _ in range(m + 1)]\n fit = [[False] * n for _ in range(m)]\n\n for i in range(m):\n for j in range(n):\n A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + grid[i][j]\n if i + 1 >= stampHeight and j + 1 >= stampWidth:\n x = i - stampHeight + 1\n y = j - stampWidth + 1\n if A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == 0:\n fit[i][j] = True\n\n for i in range(m):\n for j in range(n):\n B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + fit[i][j]\n\n for i in range(m):\n for j in range(n):\n if not grid[i][j]:\n x = min(i + stampHeight, m)\n y = min(j + stampWidth, n)\n if B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0:\n return False\n\n return True\n", "java_solution": "class Solution {\n public boolean possibleToStamp(int[][] grid, int stampHeight, int stampWidth) {\n final int m = grid.length;\n final int n = grid[0].length;\n // A[i][j] := the number of 1s in grid[0..i)[0..j)\n int[][] A = new int[m + 1][n + 1];\n // B[i][j] := the number of ways to stamp the submatrix in [0..i)[0..j)\n int[][] B = new int[m + 1][n + 1];\n // fit[i][j] := 1 if the stamps can fit with the right-bottom at (i, j)\n int[][] fit = new int[m][n];\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j) {\n A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + grid[i][j];\n if (i + 1 >= stampHeight && j + 1 >= stampWidth) {\n final int x = i - stampHeight + 1;\n final int y = j - stampWidth + 1;\n if (A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == 0)\n fit[i][j] = 1;\n }\n }\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + fit[i][j];\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 0) {\n final int x = Math.min(i + stampHeight, m);\n final int y = Math.min(j + stampWidth, n);\n if (B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0)\n return false;\n }\n\n return true;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool possibleToStamp(vector>& grid, int stampHeight,\n int stampWidth) {\n const int m = grid.size();\n const int n = grid[0].size();\n // A[i][j] := the number of 1s in grid[0..i)[0..j)\n vector> A(m + 1, vector(n + 1));\n // B[i][j] := the number of ways to stamp the submatrix in [0..i)[0..j)\n vector> B(m + 1, vector(n + 1));\n // fit[i][j] := true if the stamps can fit with the right-bottom at (i, j)\n vector> fit(m, vector(n));\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j) {\n A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + grid[i][j];\n if (i + 1 >= stampHeight && j + 1 >= stampWidth) {\n const int x = i - stampHeight + 1;\n const int y = j - stampWidth + 1;\n if (A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == 0)\n fit[i][j] = true;\n }\n }\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + fit[i][j];\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (!grid[i][j]) {\n const int x = min(i + stampHeight, m);\n const int y = min(j + stampWidth, n);\n if (B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0)\n return false;\n }\n\n return true;\n }\n};\n"} +{"task_num": 2146, "task_title": "K Highest Ranked Items Within a Price Range", "difficulty": 2, "func_name": "highestRankedKItems", "description": "You are given a 0-indexed 2D integer array `grid` of size `m x n` that\nrepresents a map of the items in a shop. The integers in the grid represent\nthe following:\n\n* `0` represents a wall that you cannot pass through.\n* `1` represents an empty cell that you can freely move to and from.\n* All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells.\n\nIt takes `1` step to travel between adjacent grid cells.\n\nYou are also given integer arrays `pricing` and `start` where `pricing = [low,\nhigh]` and `start = [row, col]` indicates that you start at the position\n`(row, col)` and are interested only in items with a price in the range of\n`[low, high]` (inclusive). You are further given an integer `k`.\n\nYou are interested in the positions of the `k` highest-ranked items whose\nprices are within the given price range. The rank is determined by the first\nof these criteria that is different:\n\n1. Distance, defined as the length of the shortest path from the `start` (shorter distance has a higher rank).\n2. Price (lower price has a higher rank, but it must be in the price range).\n3. The row number (smaller row number has a higher rank).\n4. The column number (smaller column number has a higher rank).\n\nReturn the `k` highest-ranked items within the price range sorted by their\nrank (highest to lowest). If there are fewer than `k` reachable items within\nthe price range, return all of them.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]:\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(grid)\n n = len(grid[0])\n low, high = pricing\n row, col = start\n ans = []\n\n if low <= grid[row][col] <= high:\n ans.append([row, col])\n if k == 1:\n return ans\n\n q = collections.deque([(row, col)])\n seen = {(row, col)}\n\n while q:\n neighbors = []\n for _ in range(len(q)):\n i, j = q.popleft()\n for t in range(4):\n x = i + dirs[t][0]\n y = j + dirs[t][1]\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if not grid[x][y] or (x, y) in seen:\n continue\n if low <= grid[x][y] <= high:\n neighbors.append([x, y])\n q.append((x, y))\n seen.add((x, y))\n neighbors.sort(key=lambda x: (grid[x[0]][x[1]], x[0], x[1]))\n for neighbor in neighbors:\n if len(ans) < k:\n ans.append(neighbor)\n if len(ans) == k:\n return ans\n\n return ans\n", "java_solution": "class Solution {\n public List> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) {\n final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n final int m = grid.length;\n final int n = grid[0].length;\n final int low = pricing[0];\n final int high = pricing[1];\n final int row = start[0];\n final int col = start[1];\n List> ans = new ArrayList<>();\n\n if (low <= grid[row][col] && grid[row][col] <= high) {\n ans.add(Arrays.asList(row, col));\n if (k == 1)\n return ans;\n }\n\n Queue> q = new ArrayDeque<>(List.of(new Pair<>(row, col)));\n boolean[][] seen = new boolean[m][n];\n seen[row][col] = true; // Mark as visited.\n\n while (!q.isEmpty()) {\n List> neighbors = new ArrayList<>();\n for (int sz = q.size(); sz > 0; --sz) {\n final int i = q.peek().getKey();\n final int j = q.poll().getValue();\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (grid[x][y] == 0 || seen[x][y])\n continue;\n if (low <= grid[x][y] && grid[x][y] <= high)\n neighbors.add(Arrays.asList(x, y));\n q.offer(new Pair<>(x, y));\n seen[x][y] = true;\n }\n }\n Collections.sort(neighbors, new Comparator>() {\n @Override\n public int compare(List a, List b) {\n final int x1 = a.get(0);\n final int y1 = a.get(1);\n final int x2 = b.get(0);\n final int y2 = b.get(1);\n if (grid[x1][y1] != grid[x2][y2])\n return grid[x1][y1] - grid[x2][y2];\n return x1 == x2 ? y1 - y2 : x1 - x2;\n }\n });\n for (List neighbor : neighbors) {\n if (ans.size() < k)\n ans.add(neighbor);\n if (ans.size() == k)\n return ans;\n }\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector> highestRankedKItems(vector>& grid,\n vector& pricing,\n vector& start, int k) {\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n const int m = grid.size();\n const int n = grid[0].size();\n const int low = pricing[0];\n const int high = pricing[1];\n const int row = start[0];\n const int col = start[1];\n vector> ans;\n\n if (low <= grid[row][col] && grid[row][col] <= high) {\n ans.push_back({row, col});\n if (k == 1)\n return ans;\n }\n\n queue> q{{{row, col}}};\n vector> seen(m, vector(n));\n seen[row][col] = true; // Mark as visited.\n\n while (!q.empty()) {\n vector> neighbors;\n for (int sz = q.size(); sz > 0; --sz) {\n const auto [i, j] = q.front();\n q.pop();\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (!grid[x][y] || seen[x][y])\n continue;\n if (low <= grid[x][y] && grid[x][y] <= high)\n neighbors.push_back({x, y});\n q.emplace(x, y);\n seen[x][y] = true;\n }\n }\n ranges::sort(neighbors, [&](const vector& a, const vector& b) {\n const int x1 = a[0];\n const int y1 = a[1];\n const int x2 = b[0];\n const int y2 = b[1];\n if (grid[x1][y1] != grid[x2][y2])\n return grid[x1][y1] < grid[x2][y2];\n return x1 == x2 ? y1 < y2 : x1 < x2;\n });\n for (const vector& neighbor : neighbors) {\n if (ans.size() < k)\n ans.push_back(neighbor);\n if (ans.size() == k)\n return ans;\n }\n }\n\n return ans;\n }\n};\n"} +{"task_num": 2157, "task_title": "Groups of Strings", "difficulty": 3, "func_name": "groupStrings", "description": "You are given a 0-indexed array of strings `words`. Each string consists of\nlowercase English letters only. No letter occurs more than once in any string\nof `words`.\n\nTwo strings `s1` and `s2` are said to be connected if the set of letters of\n`s2` can be obtained from the set of letters of `s1` by any one of the\nfollowing operations:\n\n* Adding exactly one letter to the set of the letters of `s1`.\n* Deleting exactly one letter from the set of the letters of `s1`.\n* Replacing exactly one letter from the set of the letters of `s1` with any letter, including itself.\n\nThe array `words` can be divided into one or more non-intersecting groups. A\nstring belongs to a group if any one of the following is true:\n\n* It is connected to at least one other string of the group.\n* It is the only string present in the group.\n\nNote that the strings in `words` should be grouped in such a manner that a\nstring belonging to a group cannot be connected to a string present in any\nother group. It can be proved that such an arrangement is always unique.\n\nReturn an array `ans` of size `2` where:\n\n* `ans[0]` is the maximum number of groups `words` can be divided into, and\n* `ans[1]` is the size of the largest group.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.count = n\n self.id = list(range(n))\n self.sz = [1] * n\n\n def unionBySize(self, u: int, v: int) -> None:\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return\n if self.sz[i] < self.sz[j]:\n self.sz[j] += self.sz[i]\n self.id[i] = j\n else:\n self.sz[i] += self.sz[j]\n self.id[j] = i\n self.count -= 1\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def groupStrings(self, words: List[str]) -> List[int]:\n uf = UnionFind(len(words))\n\n def getMask(s: str) -> int:\n mask = 0\n for c in s:\n mask |= 1 << ord(c) - ord('a')\n return mask\n\n def getAddedMasks(mask: int):\n for i in range(26):\n if not (mask >> i & 1):\n yield mask | 1 << i\n\n def getDeletedMasks(mask: int):\n for i in range(26):\n if mask >> i & 1:\n yield mask ^ 1 << i\n\n maskToIndex = {getMask(word): i for i, word in enumerate(words)}\n deletedMaskToIndex = {}\n\n for i, word in enumerate(words):\n mask = getMask(word)\n for m in getAddedMasks(mask):\n if m in maskToIndex:\n uf.unionBySize(i, maskToIndex[m])\n for m in getDeletedMasks(mask):\n if m in maskToIndex:\n uf.unionBySize(i, maskToIndex[m])\n if m in deletedMaskToIndex:\n uf.unionBySize(i, deletedMaskToIndex[m])\n else:\n deletedMaskToIndex[m] = i\n\n return [uf.count, max(uf.sz)]\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n count = n;\n id = new int[n];\n sz = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n for (int i = 0; i < n; ++i)\n sz[i] = 1;\n }\n\n public void unionBySize(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return;\n if (sz[i] < sz[j]) {\n sz[j] += sz[i];\n id[i] = j;\n } else {\n sz[i] += sz[j];\n id[j] = i;\n }\n --count;\n }\n\n public int getCount() {\n return count;\n }\n\n public int getMaxSize() {\n return Arrays.stream(sz).max().getAsInt();\n }\n\n private int count;\n private int[] id;\n private int[] sz;\n\n private int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n}\n\nclass Solution {\n public int[] groupStrings(String[] words) {\n UnionFind uf = new UnionFind(words.length);\n Map maskToIndex = new HashMap<>();\n Map deletedMaskToIndex = new HashMap<>();\n\n for (int i = 0; i < words.length; ++i) {\n final int mask = getMask(words[i]);\n for (int j = 0; j < 26; ++j)\n if ((mask >> j & 1) == 1) {\n // Going to delete this bit.\n final int m = mask ^ 1 << j;\n if (maskToIndex.containsKey(m))\n uf.unionBySize(i, maskToIndex.get(m));\n if (deletedMaskToIndex.containsKey(m))\n uf.unionBySize(i, deletedMaskToIndex.get(m));\n else\n deletedMaskToIndex.put(m, i);\n } else {\n // Going to add this bit.\n final int m = mask | 1 << j;\n if (maskToIndex.containsKey(m))\n uf.unionBySize(i, maskToIndex.get(m));\n }\n maskToIndex.put(mask, i);\n }\n\n return new int[] {uf.getCount(), uf.getMaxSize()};\n }\n\n private int getMask(final String s) {\n int mask = 0;\n for (final char c : s.toCharArray())\n mask |= 1 << c - 'a';\n return mask;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : count(n), id(n), sz(n, 1) {\n iota(id.begin(), id.end(), 0);\n }\n\n void unionBySize(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return;\n if (sz[i] < sz[j]) {\n sz[j] += sz[i];\n id[i] = j;\n } else {\n sz[i] += sz[j];\n id[j] = i;\n }\n --count;\n }\n\n int getCount() const {\n return count;\n }\n\n int getMaxSize() const {\n return ranges::max(sz);\n }\n\n private:\n int count;\n vector id;\n vector sz;\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n};\n\nclass Solution {\n public:\n vector groupStrings(vector& words) {\n UnionFind uf(words.size());\n unordered_map maskToIndex;\n unordered_map deletedMaskToIndex;\n\n for (int i = 0; i < words.size(); ++i) {\n const int mask = getMask(words[i]);\n for (int j = 0; j < 26; ++j)\n if (mask >> j & 1) {\n // Going to delete this bit.\n const int m = mask ^ 1 << j;\n if (const auto it = maskToIndex.find(m); it != maskToIndex.cend())\n uf.unionBySize(i, it->second);\n if (const auto it = deletedMaskToIndex.find(m);\n it != deletedMaskToIndex.cend())\n uf.unionBySize(i, it->second);\n else\n deletedMaskToIndex[m] = i;\n } else {\n // Going to add this bit.\n const int m = mask | 1 << j;\n if (const auto it = maskToIndex.find(m); it != maskToIndex.cend())\n uf.unionBySize(i, it->second);\n }\n maskToIndex[mask] = i;\n }\n\n return {uf.getCount(), uf.getMaxSize()};\n }\n\n private:\n int getMask(const string& s) {\n int mask = 0;\n for (const char c : s)\n mask |= 1 << c - 'a';\n return mask;\n }\n};\n"} +{"task_num": 2182, "task_title": "Construct String With Repeat Limit", "difficulty": 2, "func_name": "repeatLimitedString", "description": "You are given a string `s` and an integer `repeatLimit`. Construct a new\nstring `repeatLimitedString` using the characters of `s` such that no letter\nappears more than `repeatLimit` times in a row. You do not have to use all\ncharacters from `s`.\n\nReturn the lexicographically largest `repeatLimitedString` possible.\n\nA string `a` is lexicographically larger than a string `b` if in the first\nposition where `a` and `b` differ, string `a` has a letter that appears later\nin the alphabet than the corresponding letter in `b`. If the first\n`min(a.length, b.length)` characters do not differ, then the longer string is\nthe lexicographically larger one.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def repeatLimitedString(self, s: str, repeatLimit: int) -> str:\n ans = ''\n count = collections.Counter(s)\n\n while True:\n addOne = ans and self._shouldAddOne(ans, count)\n c = self._getLargestChar(ans, count)\n if c == ' ':\n break\n repeats = 1 if addOne else min(count[c], repeatLimit)\n ans += c * repeats\n count[c] -= repeats\n\n return ans\n\n def _shouldAddOne(self, ans: str, count: collections.Counter) -> bool:\n for c in reversed(string.ascii_lowercase):\n if count[c]:\n return ans[-1] == c\n return False\n\n def _getLargestChar(self, ans: str, count: collections.Counter) -> int:\n for c in reversed(string.ascii_lowercase):\n if count[c] and (not ans or ans[-1] != c):\n return c\n return ' '\n", "java_solution": "class Solution {\n public String repeatLimitedString(String s, int repeatLimit) {\n StringBuilder sb = new StringBuilder();\n int[] count = new int[26];\n\n for (final char c : s.toCharArray())\n ++count[c - 'a'];\n\n while (true) {\n final boolean addOne = !sb.isEmpty() && shouldAddOne(sb, count);\n final int i = getLargestChar(sb, count);\n if (i == -1)\n break;\n final int repeats = addOne ? 1 : Math.min(count[i], repeatLimit);\n sb.append(String.valueOf((char) ('a' + i)).repeat(repeats));\n count[i] -= repeats;\n }\n\n return sb.toString();\n }\n\n private boolean shouldAddOne(StringBuilder sb, int[] count) {\n for (int i = 25; i >= 0; --i)\n if (count[i] > 0)\n return sb.charAt(sb.length() - 1) == 'a' + i;\n return false;\n }\n\n private int getLargestChar(StringBuilder sb, int[] count) {\n for (int i = 25; i >= 0; --i)\n if (count[i] > 0 && (sb.isEmpty() || sb.charAt(sb.length() - 1) != 'a' + i))\n return i;\n return -1;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n string repeatLimitedString(string s, int repeatLimit) {\n string ans;\n vector count(26);\n\n for (const char c : s)\n ++count[c - 'a'];\n\n while (true) {\n const bool addOne = !ans.empty() && shouldAddOne(ans, count);\n const int i = getLargestChar(ans, count);\n if (i == -1)\n break;\n const int repeats = addOne ? 1 : min(count[i], repeatLimit);\n ans += string(repeats, 'a' + i);\n count[i] -= repeats;\n }\n\n return ans;\n }\n\n private:\n bool shouldAddOne(const string& ans, const vector& count) {\n for (int i = 25; i >= 0; --i)\n if (count[i])\n return ans.back() == 'a' + i;\n return false;\n }\n\n int getLargestChar(const string& ans, const vector& count) {\n for (int i = 25; i >= 0; --i)\n if (count[i] && (ans.empty() || ans.back() != 'a' + i))\n return i;\n return -1;\n }\n};\n"} +{"task_num": 2203, "task_title": "Minimum Weighted Subgraph With the Required Paths", "difficulty": 3, "func_name": "minimumWeight", "description": "You are given an integer `n` denoting the number of nodes of a weighted\ndirected graph. The nodes are numbered from `0` to `n - 1`.\n\nYou are also given a 2D integer array `edges` where `edges[i] = [fromi, toi,\nweighti]` denotes that there exists a directed edge from `fromi` to `toi` with\nweight `weighti`.\n\nLastly, you are given three distinct integers `src1`, `src2`, and `dest`\ndenoting three distinct nodes of the graph.\n\nReturn the minimum weight of a subgraph of the graph such that it is possible\nto reach `dest` from both `src1` and `src2` via a set of edges of this\nsubgraph. In case such a subgraph does not exist, return `-1`.\n\nA subgraph is a graph whose vertices and edges are subsets of the original\ngraph. The weight of a subgraph is the sum of weights of its constituent\nedges.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int:\n graph = [[] for _ in range(n)]\n reversedGraph = [[] for _ in range(n)]\n\n for u, v, w in edges:\n graph[u].append((v, w))\n reversedGraph[v].append((u, w))\n\n fromSrc1 = self._dijkstra(graph, src1)\n fromSrc2 = self._dijkstra(graph, src2)\n fromDest = self._dijkstra(reversedGraph, dest)\n minWeight = min(a + b + c for a, b, c in zip(fromSrc1, fromSrc2, fromDest))\n if minWeight == math.inf:\n return -1\n else:\n return minWeight\n\n def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int) -> List[int]:\n dist = [math.inf] * len(graph)\n\n dist[src] = 0\n minHeap = [(dist[src], src)]\n\n while minHeap:\n d, u = heapq.heappop(minHeap)\n if d > dist[u]:\n continue\n for v, w in graph[u]:\n if d + w < dist[v]:\n dist[v] = d + w\n heapq.heappush(minHeap, (dist[v], v))\n\n return dist\n", "java_solution": "class Solution {\n public long minimumWeight(int n, int[][] edges, int src1, int src2, int dest) {\n List>[] graph = new List[n];\n List>[] reversedGraph = new List[n];\n\n for (int i = 0; i < n; ++i) {\n graph[i] = new ArrayList<>();\n reversedGraph[i] = new ArrayList<>();\n }\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n final int w = edge[2];\n graph[u].add(new Pair<>(v, w));\n reversedGraph[v].add(new Pair<>(u, w));\n }\n\n long[] fromSrc1 = dijkstra(graph, src1);\n long[] fromSrc2 = dijkstra(graph, src2);\n long[] fromDest = dijkstra(reversedGraph, dest);\n long ans = MAX;\n\n for (int i = 0; i < n; ++i) {\n if (fromSrc1[i] == MAX || fromSrc2[i] == MAX || fromDest[i] == MAX)\n continue;\n ans = Math.min(ans, fromSrc1[i] + fromSrc2[i] + fromDest[i]);\n }\n\n return ans == MAX ? -1 : ans;\n }\n\n private static long MAX = (long) 1e10;\n\n private long[] dijkstra(List>[] graph, int src) {\n long[] dist = new long[graph.length];\n Arrays.fill(dist, MAX);\n\n dist[src] = 0;\n Queue> minHeap =\n new PriorityQueue<>(Comparator.comparingLong(Pair::getKey)) {\n {\n offer(new Pair<>(dist[src], src)); // (d, u)\n }\n };\n\n while (!minHeap.isEmpty()) {\n final long d = minHeap.peek().getKey();\n final int u = minHeap.poll().getValue();\n if (d > dist[u])\n continue;\n for (Pair pair : graph[u]) {\n final int v = pair.getKey();\n final int w = pair.getValue();\n if (d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.offer(new Pair<>(dist[v], v));\n }\n }\n }\n\n return dist;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n long long minimumWeight(int n, vector>& edges, int src1, int src2,\n int dest) {\n vector>> graph(n);\n vector>> reversedGraph(n);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n const int w = edge[2];\n graph[u].emplace_back(v, w);\n reversedGraph[v].emplace_back(u, w);\n }\n\n const vector fromSrc1 = dijkstra(graph, src1);\n const vector fromSrc2 = dijkstra(graph, src2);\n const vector fromDest = dijkstra(reversedGraph, dest);\n long ans = kMax;\n\n for (int i = 0; i < n; ++i) {\n if (fromSrc1[i] == kMax || fromSrc2[i] == kMax || fromDest[i] == kMax)\n continue;\n ans = min(ans, fromSrc1[i] + fromSrc2[i] + fromDest[i]);\n }\n\n return ans == kMax ? -1 : ans;\n }\n\n private:\n static constexpr long kMax = 10'000'000'000;\n\n vector dijkstra(const vector>>& graph, int src) {\n vector dist(graph.size(), kMax);\n\n dist[src] = 0;\n using P = pair; // (d, u)\n priority_queue, greater<>> minHeap;\n minHeap.emplace(dist[src], src);\n\n while (!minHeap.empty()) {\n const auto [d, u] = minHeap.top();\n minHeap.pop();\n if (d > dist[u])\n continue;\n for (const auto& [v, w] : graph[u])\n if (d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.emplace(dist[v], v);\n }\n }\n\n return dist;\n }\n};\n"} +{"task_num": 2242, "task_title": "Maximum Score of a Node Sequence", "difficulty": 3, "func_name": "maximumScore", "description": "There is an undirected graph with `n` nodes, numbered from `0` to `n - 1`.\n\nYou are given a 0-indexed integer array `scores` of length `n` where\n`scores[i]` denotes the score of node `i`. You are also given a 2D integer\narray `edges` where `edges[i] = [ai, bi]` denotes that there exists an\nundirected edge connecting nodes `ai` and `bi`.\n\nA node sequence is valid if it meets the following conditions:\n\n* There is an edge connecting every pair of adjacent nodes in the sequence.\n* No node appears more than once in the sequence.\n\nThe score of a node sequence is defined as the sum of the scores of the nodes\nin the sequence.\n\nReturn the maximum score of a valid node sequence with a length of `4`. If no\nsuch sequence exists, return `-1`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int:\n n = len(scores)\n ans = -1\n graph = [[] for _ in range(n)]\n\n for u, v in edges:\n graph[u].append((scores[v], v))\n graph[v].append((scores[u], u))\n\n for i in range(n):\n graph[i] = heapq.nlargest(3, graph[i])\n\n for u, v in edges:\n for scoreA, a in graph[u]:\n for scoreB, b in graph[v]:\n if a != b and a != v and b != u:\n ans = max(ans, scoreA + scores[u] + scores[v] + scoreB)\n\n return ans\n", "java_solution": "class Solution {\n public int maximumScore(int[] scores, int[][] edges) {\n final int n = scores.length;\n int ans = -1;\n Queue[] graph = new Queue[n];\n\n for (int i = 0; i < n; ++i)\n graph[i] = new PriorityQueue<>(Comparator.comparingInt(a -> scores[a]));\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n graph[u].offer(v);\n graph[v].offer(u);\n if (graph[u].size() > 3)\n graph[u].poll();\n if (graph[v].size() > 3)\n graph[v].poll();\n }\n\n // To find the target sequence: a - u - v - b, enumerate each edge (u, v),\n // and find a (u's child) and b (v's child). That's why we find the 3\n // children that have the highest scores because one of the 3 children is\n // guaranteed to be valid.\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n for (final int a : graph[u])\n for (final int b : graph[v])\n if (a != b && a != v && b != u)\n ans = Math.max(ans, scores[a] + scores[u] + scores[v] + scores[b]);\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int maximumScore(vector& scores, vector>& edges) {\n int ans = -1;\n vector>> graph(scores.size()); // {(score, node)}\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n graph[u].emplace(scores[v], v);\n graph[v].emplace(scores[u], u);\n if (graph[u].size() > 3)\n graph[u].erase(graph[u].begin());\n if (graph[v].size() > 3)\n graph[v].erase(graph[v].begin());\n }\n\n // To find the target sequence: a - u - v - b, enumerate each edge (u, v),\n // and find a (u's child) and b (v's child). That's why we find the 3\n // children that have the highest scores because one of the 3 children is\n // guaranteed to be valid.\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n for (const auto& [scoreA, a] : graph[u])\n for (const auto& [scoreB, b] : graph[v])\n if (a != b && a != v && b != u)\n ans = max(ans, scoreA + scores[u] + scores[v] + scoreB);\n }\n\n return ans;\n }\n};\n"} +{"task_num": 2245, "task_title": "Maximum Trailing Zeros in a Cornered Path", "difficulty": 2, "func_name": "maxTrailingZeros", "description": "You are given a 2D integer array `grid` of size `m x n`, where each cell\ncontains a positive integer.\n\nA cornered path is defined as a set of adjacent cells with at most one turn.\nMore specifically, the path should exclusively move either horizontally or\nvertically up to the turn (if there is one), without returning to a previously\nvisited cell. After the turn, the path will then move exclusively in the\nalternate direction: move vertically if it moved horizontally, and vice versa,\nalso without returning to a previously visited cell.\n\nThe product of a path is defined as the product of all the values in the path.\n\nReturn the maximum number of trailing zeros in the product of a cornered path\nfound in `grid`.\n\nNote:\n\n* Horizontal movement means moving in either the left or right direction.\n* Vertical movement means moving in either the up or down direction.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n leftPrefix2 = [[0] * n for _ in range(m)]\n leftPrefix5 = [[0] * n for _ in range(m)]\n topPrefix2 = [[0] * n for _ in range(m)]\n topPrefix5 = [[0] * n for _ in range(m)]\n\n def getCount(num: int, factor: int) -> int:\n count = 0\n while num % factor == 0:\n num //= factor\n count += 1\n return count\n\n for i in range(m):\n for j in range(n):\n leftPrefix2[i][j] = getCount(grid[i][j], 2)\n leftPrefix5[i][j] = getCount(grid[i][j], 5)\n if j:\n leftPrefix2[i][j] += leftPrefix2[i][j - 1]\n leftPrefix5[i][j] += leftPrefix5[i][j - 1]\n\n for j in range(n):\n for i in range(m):\n topPrefix2[i][j] = getCount(grid[i][j], 2)\n topPrefix5[i][j] = getCount(grid[i][j], 5)\n if i:\n topPrefix2[i][j] += topPrefix2[i - 1][j]\n topPrefix5[i][j] += topPrefix5[i - 1][j]\n\n ans = 0\n for i in range(m):\n for j in range(n):\n curr2 = getCount(grid[i][j], 2)\n curr5 = getCount(grid[i][j], 5)\n l2 = leftPrefix2[i][j]\n l5 = leftPrefix5[i][j]\n r2 = leftPrefix2[i][n - 1] - (0 if j == 0 else leftPrefix2[i][j - 1])\n r5 = leftPrefix5[i][n - 1] - (0 if j == 0 else leftPrefix5[i][j - 1])\n t2 = topPrefix2[i][j]\n t5 = topPrefix5[i][j]\n d2 = topPrefix2[m - 1][j] - (0 if i == 0 else topPrefix2[i - 1][j])\n d5 = topPrefix5[m - 1][j] - (0 if i == 0 else topPrefix5[i - 1][j])\n ans = max(ans, min(l2 + t2 - curr2, l5 + t5 - curr5), min(r2 + t2 - curr2, r5 + t5 - curr5), min(l2 + d2 - curr2, l5 + d5 - curr5), min(r2 + d2 - curr2, r5 + d5 - curr5))\n\n return ans\n", "java_solution": "class Solution {\n public int maxTrailingZeros(int[][] grid) {\n final int m = grid.length;\n final int n = grid[0].length;\n // leftPrefix2[i][j] := the number of 2 in grid[i][0..j]\n // leftPrefix5[i][j] := the number of 5 in grid[i][0..j]\n // topPrefix2[i][j] := the number of 2 in grid[0..i][j]\n // topPrefix5[i][j] := the number of 5 in grid[0..i][j]\n int[][] leftPrefix2 = new int[m][n];\n int[][] leftPrefix5 = new int[m][n];\n int[][] topPrefix2 = new int[m][n];\n int[][] topPrefix5 = new int[m][n];\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j) {\n leftPrefix2[i][j] = getCount(grid[i][j], 2);\n leftPrefix5[i][j] = getCount(grid[i][j], 5);\n if (j > 0) {\n leftPrefix2[i][j] += leftPrefix2[i][j - 1];\n leftPrefix5[i][j] += leftPrefix5[i][j - 1];\n }\n }\n\n for (int j = 0; j < n; ++j)\n for (int i = 0; i < m; ++i) {\n topPrefix2[i][j] = getCount(grid[i][j], 2);\n topPrefix5[i][j] = getCount(grid[i][j], 5);\n if (i > 0) {\n topPrefix2[i][j] += topPrefix2[i - 1][j];\n topPrefix5[i][j] += topPrefix5[i - 1][j];\n }\n }\n\n int ans = 0;\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j) {\n final int curr2 = getCount(grid[i][j], 2);\n final int curr5 = getCount(grid[i][j], 5);\n final int l2 = leftPrefix2[i][j];\n final int l5 = leftPrefix5[i][j];\n final int r2 = leftPrefix2[i][n - 1] - (j > 0 ? leftPrefix2[i][j - 1] : 0);\n final int r5 = leftPrefix5[i][n - 1] - (j > 0 ? leftPrefix5[i][j - 1] : 0);\n final int t2 = topPrefix2[i][j];\n final int t5 = topPrefix5[i][j];\n final int d2 = topPrefix2[m - 1][j] - (i > 0 ? topPrefix2[i - 1][j] : 0);\n final int d5 = topPrefix5[m - 1][j] - (i > 0 ? topPrefix5[i - 1][j] : 0);\n ans = Math.max(ans, Math.max(Math.max(Math.min(l2 + t2 - curr2, l5 + t5 - curr5),\n Math.min(r2 + t2 - curr2, r5 + t5 - curr5)),\n Math.max(Math.min(l2 + d2 - curr2, l5 + d5 - curr5),\n Math.min(r2 + d2 - curr2, r5 + d5 - curr5))));\n }\n\n return ans;\n }\n\n private int getCount(int num, int factor) {\n int count = 0;\n while (num % factor == 0) {\n num /= factor;\n ++count;\n }\n return count;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int maxTrailingZeros(vector>& grid) {\n const int m = grid.size();\n const int n = grid[0].size();\n // leftPrefix2[i][j] := the number of 2 in grid[i][0..j]\n // leftPrefix5[i][j] := the number of 5 in grid[i][0..j]\n // topPrefix2[i][j] := the number of 2 in grid[0..i][j]\n // topPrefix5[i][j] := the number of 5 in grid[0..i][j]\n vector> leftPrefix2(m, vector(n));\n vector> leftPrefix5(m, vector(n));\n vector> topPrefix2(m, vector(n));\n vector> topPrefix5(m, vector(n));\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j) {\n leftPrefix2[i][j] = getCount(grid[i][j], 2);\n leftPrefix5[i][j] = getCount(grid[i][j], 5);\n if (j > 0) {\n leftPrefix2[i][j] += leftPrefix2[i][j - 1];\n leftPrefix5[i][j] += leftPrefix5[i][j - 1];\n }\n }\n\n for (int j = 0; j < n; ++j)\n for (int i = 0; i < m; ++i) {\n topPrefix2[i][j] = getCount(grid[i][j], 2);\n topPrefix5[i][j] = getCount(grid[i][j], 5);\n if (i > 0) {\n topPrefix2[i][j] += topPrefix2[i - 1][j];\n topPrefix5[i][j] += topPrefix5[i - 1][j];\n }\n }\n\n int ans = 0;\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j) {\n const int curr2 = getCount(grid[i][j], 2);\n const int curr5 = getCount(grid[i][j], 5);\n const int l2 = leftPrefix2[i][j];\n const int l5 = leftPrefix5[i][j];\n const int r2 = leftPrefix2[i][n - 1] - (j ? leftPrefix2[i][j - 1] : 0);\n const int r5 = leftPrefix5[i][n - 1] - (j ? leftPrefix5[i][j - 1] : 0);\n const int t2 = topPrefix2[i][j];\n const int t5 = topPrefix5[i][j];\n const int d2 = topPrefix2[m - 1][j] - (i ? topPrefix2[i - 1][j] : 0);\n const int d5 = topPrefix5[m - 1][j] - (i ? topPrefix5[i - 1][j] : 0);\n ans = max({ans, min(l2 + t2 - curr2, l5 + t5 - curr5),\n min(r2 + t2 - curr2, r5 + t5 - curr5),\n min(l2 + d2 - curr2, l5 + d5 - curr5),\n min(r2 + d2 - curr2, r5 + d5 - curr5)});\n }\n\n return ans;\n }\n\n private:\n int getCount(int num, int factor) {\n int count = 0;\n while (num % factor == 0) {\n num /= factor;\n ++count;\n }\n return count;\n }\n};\n"} +{"task_num": 2257, "task_title": "Count Unguarded Cells in the Grid", "difficulty": 2, "func_name": "countUnguarded", "description": "You are given two integers `m` and `n` representing a 0-indexed `m x n` grid.\nYou are also given two 2D integer arrays `guards` and `walls` where `guards[i]\n= [rowi, coli]` and `walls[j] = [rowj, colj]` represent the positions of the\n`ith` guard and `jth` wall respectively.\n\nA guard can see every cell in the four cardinal directions (north, east,\nsouth, or west) starting from their position unless obstructed by a wall or\nanother guard. A cell is guarded if there is at least one guard that can see\nit.\n\nReturn the number of unoccupied cells that are not guarded.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:\n ans = 0\n grid = [[0] * n for _ in range(m)]\n left = [[0] * n for _ in range(m)]\n right = [[0] * n for _ in range(m)]\n up = [[0] * n for _ in range(m)]\n down = [[0] * n for _ in range(m)]\n\n for row, col in guards:\n grid[row][col] = 'G'\n\n for row, col in walls:\n grid[row][col] = 'W'\n\n for i in range(m):\n lastCell = 0\n for j in range(n):\n if grid[i][j] == 'G' or grid[i][j] == 'W':\n lastCell = grid[i][j]\n else:\n left[i][j] = lastCell\n lastCell = 0\n for j in range(n - 1, -1, -1):\n if grid[i][j] == 'G' or grid[i][j] == 'W':\n lastCell = grid[i][j]\n else:\n right[i][j] = lastCell\n\n for j in range(n):\n lastCell = 0\n for i in range(m):\n if grid[i][j] == 'G' or grid[i][j] == 'W':\n lastCell = grid[i][j]\n else:\n up[i][j] = lastCell\n lastCell = 0\n for i in range(m - 1, -1, -1):\n if grid[i][j] == 'G' or grid[i][j] == 'W':\n lastCell = grid[i][j]\n else:\n down[i][j] = lastCell\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0 and left[i][j] != 'G' and right[i][j] != 'G' and up[i][j] != 'G' and down[i][j] != 'G':\n ans += 1\n\n return ans\n", "java_solution": "class Solution {\n public int countUnguarded(int m, int n, int[][] guards, int[][] walls) {\n int ans = 0;\n char[][] grid = new char[m][n];\n char[][] left = new char[m][n];\n char[][] right = new char[m][n];\n char[][] up = new char[m][n];\n char[][] down = new char[m][n];\n\n for (int[] guard : guards)\n grid[guard[0]][guard[1]] = 'G';\n\n for (int[] wall : walls)\n grid[wall[0]][wall[1]] = 'W';\n\n for (int i = 0; i < m; ++i) {\n char lastCell = 0;\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 'G' || grid[i][j] == 'W')\n lastCell = grid[i][j];\n else\n left[i][j] = lastCell;\n lastCell = 0;\n for (int j = n - 1; j >= 0; --j)\n if (grid[i][j] == 'G' || grid[i][j] == 'W')\n lastCell = grid[i][j];\n else\n right[i][j] = lastCell;\n }\n\n for (int j = 0; j < n; ++j) {\n char lastCell = 0;\n for (int i = 0; i < m; ++i)\n if (grid[i][j] == 'G' || grid[i][j] == 'W')\n lastCell = grid[i][j];\n else\n up[i][j] = lastCell;\n lastCell = 0;\n for (int i = m - 1; i >= 0; --i)\n if (grid[i][j] == 'G' || grid[i][j] == 'W')\n lastCell = grid[i][j];\n else\n down[i][j] = lastCell;\n }\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 0 && left[i][j] != 'G' && right[i][j] != 'G' && up[i][j] != 'G' &&\n down[i][j] != 'G')\n ++ans;\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int countUnguarded(int m, int n, vector>& guards,\n vector>& walls) {\n int ans = 0;\n vector> grid(m, vector(n));\n vector> left(m, vector(n));\n vector> right(m, vector(n));\n vector> up(m, vector(n));\n vector> down(m, vector(n));\n\n for (const vector& guard : guards)\n grid[guard[0]][guard[1]] = 'G';\n\n for (const vector& wall : walls)\n grid[wall[0]][wall[1]] = 'W';\n\n for (int i = 0; i < m; ++i) {\n char lastCell = 0;\n for (int j = 0; j < n; ++j)\n recordOrFill(grid[i][j], lastCell, left[i][j]);\n lastCell = 0;\n for (int j = n - 1; j >= 0; --j)\n recordOrFill(grid[i][j], lastCell, right[i][j]);\n }\n\n for (int j = 0; j < n; ++j) {\n char lastCell = 0;\n for (int i = 0; i < m; ++i)\n recordOrFill(grid[i][j], lastCell, up[i][j]);\n lastCell = 0;\n for (int i = m - 1; i >= 0; --i)\n recordOrFill(grid[i][j], lastCell, down[i][j]);\n }\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 0 && left[i][j] != 'G' && right[i][j] != 'G' &&\n up[i][j] != 'G' && down[i][j] != 'G')\n ++ans;\n\n return ans;\n }\n\n private:\n void recordOrFill(char currCell, char& lastCell, char& infoCell) {\n if (currCell == 'G' || currCell == 'W')\n lastCell = currCell;\n else\n infoCell = lastCell;\n }\n};\n"} +{"task_num": 2258, "task_title": "Escape the Spreading Fire", "difficulty": 3, "func_name": "maximumMinutes", "description": "You are given a 0-indexed 2D integer array `grid` of size `m x n` which\nrepresents a field. Each cell has one of three values:\n\n* `0` represents grass,\n* `1` represents fire,\n* `2` represents a wall that you and fire cannot pass through.\n\nYou are situated in the top-left cell, `(0, 0)`, and you want to travel to the\nsafehouse at the bottom-right cell, `(m - 1, n - 1)`. Every minute, you may\nmove to an adjacent grass cell. After your move, every fire cell will spread\nto all adjacent cells that are not walls.\n\nReturn the maximum number of minutes that you can stay in your initial\nposition before moving while still safely reaching the safehouse. If this is\nimpossible, return `-1`. If you can always reach the safehouse regardless of\nthe minutes stayed, return `109`.\n\nNote that even if the fire spreads to the safehouse immediately after you have\nreached it, it will be counted as safely reaching the safehouse.\n\nA cell is adjacent to another cell if the former is directly north, east,\nsouth, or west of the latter (i.e., their sides are touching).\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def maximumMinutes(self, grid: List[List[int]]) -> int:\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n kMax = len(grid) * len(grid[0])\n fireGrid = [[-1] * len(grid[0]) for _ in range(len(grid))]\n self._buildFireGrid(grid, fireGrid, dirs)\n\n ans = -1\n l = 0\n r = kMax\n\n while l <= r:\n m = (l + r) // 2\n if self._canStayFor(grid, fireGrid, m, dirs):\n ans = m\n l = m + 1\n else:\n r = m - 1\n\n return int(1e9) if ans == kMax else ans\n\n def _buildFireGrid(self, grid: List[List[int]], fireMinute: List[List[int]], dirs: List[int]) -> None:\n minuteFromFire = 0\n q = collections.deque()\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n q.append((i, j))\n fireMinute[i][j] = 0\n while q:\n minuteFromFire += 1\n for _ in range(len(q)):\n i, j = q.popleft()\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == len(grid) or y < 0 or y == len(grid[0]):\n continue\n if grid[x][y] == 2:\n continue\n if fireMinute[x][y] != -1:\n continue\n fireMinute[x][y] = minuteFromFire\n q.append((x, y))\n\n def _canStayFor(self, grid: List[List[int]], fireMinute: List[List[int]], minute: int, dirs: List[int]) -> bool:\n q = collections.deque([(0, 0)])\n seen = {(0, 0)}\n\n while q:\n minute += 1\n for _ in range(len(q)):\n i, j = q.popleft()\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == len(grid) or y < 0 or y == len(grid[0]):\n continue\n if grid[x][y] == 2:\n continue\n if x == len(grid) - 1 and y == len(grid[0]) - 1:\n if fireMinute[x][y] != -1 and fireMinute[x][y] < minute:\n continue\n return True\n if fireMinute[x][y] != -1 and fireMinute[x][y] <= minute:\n continue\n if (x, y) in seen:\n continue\n q.append((x, y))\n seen.add((x, y))\n\n return False\n", "java_solution": "class Solution {\n public int maximumMinutes(int[][] grid) {\n final int MAX = grid.length * grid[0].length;\n int[][] fireMinute = new int[grid.length][grid[0].length];\n Arrays.stream(fireMinute).forEach(A -> Arrays.fill(A, -1));\n buildFireGrid(grid, fireMinute);\n\n int ans = -1;\n int l = 0;\n int r = MAX;\n\n while (l <= r) {\n final int m = (l + r) / 2;\n if (canStayFor(grid, fireMinute, m)) {\n ans = m;\n l = m + 1;\n } else {\n r = m - 1;\n }\n }\n\n return ans == MAX ? 1_000_000_000 : ans;\n }\n\n private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n private void buildFireGrid(int[][] grid, int[][] fireMinute) {\n Queue> q = new ArrayDeque<>();\n\n for (int i = 0; i < grid.length; ++i)\n for (int j = 0; j < grid[0].length; ++j)\n if (grid[i][j] == 1) { // the fire\n q.offer(new Pair<>(i, j));\n fireMinute[i][j] = 0;\n }\n\n for (int minuteFromFire = 1; !q.isEmpty(); ++minuteFromFire)\n for (int sz = q.size(); sz > 0; --sz) {\n final int i = q.peek().getKey();\n final int j = q.poll().getValue();\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == grid.length || y < 0 || y == grid[0].length)\n continue;\n if (grid[x][y] == 2) // the wall\n continue;\n if (fireMinute[x][y] != -1)\n continue;\n fireMinute[x][y] = minuteFromFire;\n q.offer(new Pair<>(x, y));\n }\n }\n }\n\n boolean canStayFor(int[][] grid, int[][] fireMinute, int minute) {\n Queue> q =\n new ArrayDeque<>(List.of(new Pair<>(0, 0))); // the start position\n boolean[][] seen = new boolean[grid.length][grid[0].length];\n seen[0][0] = true;\n\n while (!q.isEmpty()) {\n ++minute;\n for (int sz = q.size(); sz > 0; --sz) {\n final int i = q.peek().getKey();\n final int j = q.poll().getValue();\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == grid.length || y < 0 || y == grid[0].length)\n continue;\n if (grid[x][y] == 2) // the wall\n continue;\n if (x == grid.length - 1 && y == grid[0].length - 1) {\n if (fireMinute[x][y] != -1 && fireMinute[x][y] < minute)\n continue;\n return true;\n }\n if (fireMinute[x][y] != -1 && fireMinute[x][y] <= minute)\n continue;\n if (seen[x][y])\n continue;\n q.offer(new Pair<>(x, y));\n seen[x][y] = true;\n }\n }\n }\n\n return false;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int maximumMinutes(vector>& grid) {\n const int kMax = grid.size() * grid[0].size();\n vector> fireMinute(grid.size(),\n vector(grid[0].size(), -1));\n buildFireGrid(grid, fireMinute);\n\n int ans = -1;\n int l = 0;\n int r = kMax;\n\n while (l <= r) {\n const int m = (l + r) / 2;\n if (canStayFor(grid, fireMinute, m)) {\n ans = m;\n l = m + 1;\n } else {\n r = m - 1;\n }\n }\n\n return ans == kMax ? 1'000'000'000 : ans;\n }\n\n private:\n static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n void buildFireGrid(const vector>& grid,\n vector>& fireMinute) {\n queue> q;\n\n for (int i = 0; i < grid.size(); ++i)\n for (int j = 0; j < grid[0].size(); ++j)\n if (grid[i][j] == 1) { // the fire\n q.emplace(i, j);\n fireMinute[i][j] = 0;\n }\n\n for (int minuteFromFire = 1; !q.empty(); ++minuteFromFire)\n for (int sz = q.size(); sz > 0; --sz) {\n const auto [i, j] = q.front();\n q.pop();\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size())\n continue;\n if (grid[x][y] == 2) // the wall\n continue;\n if (fireMinute[x][y] != -1)\n continue;\n fireMinute[x][y] = minuteFromFire;\n q.emplace(x, y);\n }\n }\n }\n\n bool canStayFor(const vector>& grid,\n const vector>& fireMinute, int minute) {\n queue> q{{{0, 0}}}; // the start position\n vector> seen(grid.size(), vector(grid[0].size()));\n seen[0][0] = true;\n\n while (!q.empty()) {\n ++minute;\n for (int sz = q.size(); sz > 0; --sz) {\n const auto [i, j] = q.front();\n q.pop();\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size())\n continue;\n if (grid[x][y] == 2) // the wall\n continue;\n if (x == grid.size() - 1 && y == grid[0].size() - 1) {\n if (fireMinute[x][y] != -1 && fireMinute[x][y] < minute)\n continue;\n return true;\n }\n if (fireMinute[x][y] != -1 && fireMinute[x][y] <= minute)\n continue;\n if (seen[x][y])\n continue;\n q.emplace(x, y);\n seen[x][y] = true;\n }\n }\n }\n\n return false;\n }\n};\n"} +{"task_num": 2290, "task_title": "Minimum Obstacle Removal to Reach Corner", "difficulty": 3, "func_name": "minimumObstacles", "description": "You are given a 0-indexed 2D integer array `grid` of size `m x n`. Each cell\nhas one of two values:\n\n* `0` represents an empty cell,\n* `1` represents an obstacle that may be removed.\n\nYou can move up, down, left, or right from and to an empty cell.\n\nReturn the minimum number of obstacles to remove so you can move from the\nupper left corner `(0, 0)` to the lower right corner `(m - 1, n - 1)`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumObstacles(self, grid: List[List[int]]) -> int:\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(grid)\n n = len(grid[0])\n minHeap = [(grid[0][0], 0, 0)] # (d, i, j)\n dist = [[math.inf] * n for _ in range(m)]\n dist[0][0] = grid[0][0]\n\n while minHeap:\n d, i, j = heapq.heappop(minHeap)\n if i == m - 1 and j == n - 1:\n return d\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n newDist = d + grid[i][j]\n if newDist < dist[x][y]:\n dist[x][y] = newDist\n heapq.heappush(minHeap, (newDist, x, y))\n\n return dist[m - 1][n - 1]\n", "java_solution": "class Solution {\n public int minimumObstacles(int[][] grid) {\n final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n final int m = grid.length;\n final int n = grid[0].length;\n Queue minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) {\n { offer(new int[] {grid[0][0], 0, 0}); } // (d, i, j)\n };\n int[][] dist = new int[m][n];\n Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));\n dist[0][0] = grid[0][0];\n\n while (!minHeap.isEmpty()) {\n final int d = minHeap.peek()[0];\n final int i = minHeap.peek()[1];\n final int j = minHeap.poll()[2];\n if (i == m - 1 && j == n - 1)\n return d;\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n final int newDist = d + grid[i][j];\n if (newDist < dist[x][y]) {\n dist[x][y] = newDist;\n minHeap.offer(new int[] {newDist, x, y});\n }\n }\n }\n\n return dist[m - 1][n - 1];\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minimumObstacles(vector>& grid) {\n const int m = grid.size();\n const int n = grid[0].size();\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n using T = tuple; // (d, i, j)\n priority_queue, greater<>> minHeap;\n vector> dist(m, vector(n, INT_MAX));\n\n minHeap.emplace(grid[0][0], 0, 0);\n dist[0][0] = grid[0][0];\n\n while (!minHeap.empty()) {\n const auto [d, i, j] = minHeap.top();\n minHeap.pop();\n if (i == m - 1 && j == n - 1)\n return d;\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n const int newDist = d + grid[i][j];\n if (newDist < dist[x][y]) {\n dist[x][y] = newDist;\n minHeap.emplace(newDist, x, y);\n }\n }\n }\n\n return dist[m - 1][n - 1];\n }\n};\n"} +{"task_num": 2299, "task_title": "Strong Password Checker II", "difficulty": 1, "func_name": "strongPasswordCheckerII", "description": "A password is said to be strong if it satisfies all the following criteria:\n\n* It has at least `8` characters.\n* It contains at least one lowercase letter.\n* It contains at least one uppercase letter.\n* It contains at least one digit.\n* It contains at least one special character. The special characters are the characters in the following string: `\"!@#$%^&*()-+\"`.\n* It does not contain `2` of the same character in adjacent positions (i.e., `\"aab\"` violates this condition, but `\"aba\"` does not).\n\nGiven a string `password`, return `true` if it is a strong password.\nOtherwise, return `false`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def strongPasswordCheckerII(self, password: str) -> bool:\n if len(password) < 8:\n return False\n if not any(c.islower() for c in password):\n return False\n if not any(c.isupper() for c in password):\n return False\n if not any(c.isdigit() for c in password):\n return False\n if not any(\"!@#$%^&*()-+\".find(c) != -1 for c in password):\n return False\n return all(a != b for a, b in zip(password, password[1:]))\n", "java_solution": "class Solution {\n public boolean strongPasswordCheckerII(String password) {\n if (password.length() < 8)\n return false;\n\n final boolean hasLowerCase = password.chars().anyMatch(c -> Character.isLowerCase(c));\n if (!hasLowerCase)\n return false;\n\n final boolean hasUpperCase = password.chars().anyMatch(c -> Character.isUpperCase(c));\n if (!hasUpperCase)\n return false;\n\n final boolean hasDigit = password.chars().anyMatch(c -> Character.isDigit(c));\n if (!hasDigit)\n return false;\n\n final boolean hasSpecial = password.chars().anyMatch(c -> \"!@#$%^&*()-+\".indexOf(c) != -1);\n if (!hasSpecial)\n return false;\n\n for (int i = 1; i < password.length(); ++i)\n if (password.charAt(i) == password.charAt(i - 1))\n return false;\n return true;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool strongPasswordCheckerII(string password) {\n if (password.length() < 8)\n return false;\n\n const bool hasLowerCase =\n ranges::any_of(password, [](const char c) { return islower(c); });\n if (!hasLowerCase)\n return false;\n\n const bool hasUpperCase =\n ranges::any_of(password, [](const char c) { return isupper(c); });\n if (!hasUpperCase)\n return false;\n\n const bool hasDigit =\n ranges::any_of(password, [](const char c) { return isdigit(c); });\n if (!hasDigit)\n return false;\n\n const bool hasSpecial = ranges::any_of(password, [](const char c) {\n return string(\"!@#$%^&*()-+\").find(c) != string::npos;\n });\n if (!hasSpecial)\n return false;\n\n for (int i = 1; i < password.length(); ++i)\n if (password[i] == password[i - 1])\n return false;\n return true;\n }\n};\n"} +{"task_num": 2301, "task_title": "Match Substring After Replacement", "difficulty": 3, "func_name": "matchReplacement", "description": "You are given two strings `s` and `sub`. You are also given a 2D character\narray `mappings` where `mappings[i] = [oldi, newi]` indicates that you may\nperform the following operation any number of times:\n\n* Replace a character `oldi` of `sub` with `newi`.\n\nEach character in `sub` cannot be replaced more than once.\n\nReturn `true` if it is possible to make `sub` a substring of `s` by replacing\nzero or more characters according to `mappings`. Otherwise, return `false`.\n\nA substring is a contiguous non-empty sequence of characters within a string.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool:\n isMapped = [[False] * 128 for _ in range(128)]\n\n for old, new in mappings:\n isMapped[ord(old)][ord(new)] = True\n\n for i in range(len(s)):\n if self._canTransform(s, i, sub, isMapped):\n return True\n\n return False\n\n def _canTransform(self, s: str, start: int, sub: str, isMapped: List[List[bool]]) -> bool:\n if start + len(sub) > len(s):\n return False\n\n for i in range(len(sub)):\n a = sub[i]\n b = s[start + i]\n if a != b and not isMapped[ord(a)][ord(b)]:\n return False\n\n return True\n", "java_solution": "class Solution {\n public boolean matchReplacement(String s, String sub, char[][] mappings) {\n boolean[][] isMapped = new boolean[128][128];\n\n for (char[] m : mappings) {\n final char old = m[0];\n final char _new = m[1];\n isMapped[old][_new] = true;\n }\n\n for (int i = 0; i < s.length(); ++i)\n if (canTransform(s, i, sub, isMapped))\n return true;\n\n return false;\n }\n\n private boolean canTransform(final String s, int start, final String sub, boolean[][] isMapped) {\n if (start + sub.length() > s.length())\n return false;\n\n for (int i = 0; i < sub.length(); ++i) {\n final char a = sub.charAt(i);\n final char b = s.charAt(start + i);\n if (a != b && !isMapped[a][b])\n return false;\n }\n\n return true;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool matchReplacement(string s, string sub, vector>& mappings) {\n vector> isMapped(128, vector(128));\n\n for (const vector& m : mappings) {\n const char old = m[0];\n const char _new = m[1];\n isMapped[old][_new] = true;\n }\n\n for (int i = 0; i < s.length(); ++i)\n if (canTransform(s, i, sub, isMapped))\n return true;\n\n return false;\n }\n\n private:\n bool canTransform(const string& s, int start, const string& sub,\n const vector>& isMapped) {\n if (start + sub.length() > s.length())\n return false;\n\n for (int i = 0; i < sub.length(); ++i) {\n const char a = sub[i];\n const char b = s[start + i];\n if (a != b && !isMapped[a][b])\n return false;\n }\n\n return true;\n }\n};\n"} +{"task_num": 2322, "task_title": "Minimum Score After Removals on a Tree", "difficulty": 3, "func_name": "minimumScore", "description": "There is an undirected connected tree with `n` nodes labeled from `0` to `n -\n1` and `n - 1` edges.\n\nYou are given a 0-indexed integer array `nums` of length `n` where `nums[i]`\nrepresents the value of the `ith` node. You are also given a 2D integer array\n`edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is\nan edge between nodes `ai` and `bi` in the tree.\n\nRemove two distinct edges of the tree to form three connected components. For\na pair of removed edges, the following steps are defined:\n\n1. Get the XOR of all the values of the nodes for each of the three components respectively.\n2. The difference between the largest XOR value and the smallest XOR value is the score of the pair.\n\n* For example, say the three components have the node values: `[4,5,7]`, `[1,9]`, and `[3,3,3]`. The three XOR values are `4 ^ 5 ^ 7 = 6`, `1 ^ 9 = 8`, and `3 ^ 3 ^ 3 = 3`. The largest XOR value is `8` and the smallest XOR value is `3`. The score is then `8 - 3 = 5`.\n\nReturn the minimum score of any possible pair of edge removals on the given\ntree.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator, Set\n\nclass Solution:\n def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:\n n = len(nums)\n xors = functools.reduce(lambda x, y: x ^ y, nums)\n subXors = nums[:]\n tree = [[] for _ in range(n)]\n children = [{i} for i in range(n)]\n\n for u, v in edges:\n tree[u].append(v)\n tree[v].append(u)\n\n def dfs(u: int, parent: int) -> Tuple[int, Set[int]]:\n for v in tree[u]:\n if v == parent:\n continue\n vXor, vChildren = dfs(v, u)\n subXors[u] ^= vXor\n children[u] |= vChildren\n return subXors[u], children[u]\n\n dfs(0, -1)\n\n ans = math.inf\n for i in range(len(edges)):\n a, b = edges[i]\n if b in children[a]:\n a, b = b, a\n for j in range(i):\n c, d = edges[j]\n if d in children[c]:\n c, d = d, c\n\n if c in children[a] and a != c:\n cands = [subXors[c], subXors[a] ^ subXors[c], xors ^ subXors[a]]\n elif a in children[c] and a != c:\n cands = [subXors[a], subXors[c] ^ subXors[a], xors ^ subXors[c]]\n else:\n cands = [subXors[a], subXors[c], xors ^ subXors[a] ^ subXors[c]]\n ans = min(ans, max(cands) - min(cands))\n\n return ans\n", "java_solution": "class Solution {\n public int minimumScore(int[] nums, int[][] edges) {\n final int n = nums.length;\n final int xors = getXors(nums);\n int[] subXors = nums.clone();\n List[] tree = new List[n];\n Set[] children = new Set[n];\n\n for (int i = 0; i < n; ++i)\n tree[i] = new ArrayList<>();\n\n for (int i = 0; i < n; ++i)\n children[i] = new HashSet<>(Arrays.asList(i));\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n tree[u].add(v);\n tree[v].add(u);\n }\n\n dfs(tree, 0, -1, subXors, children);\n\n int ans = Integer.MAX_VALUE;\n\n for (int i = 0; i < edges.length; ++i) {\n int a = edges[i][0];\n int b = edges[i][1];\n if (children[a].contains(b)) {\n final int temp = a;\n a = b;\n b = a;\n }\n for (int j = 0; j < i; ++j) {\n int c = edges[j][0];\n int d = edges[j][1];\n if (children[c].contains(d)) {\n final int temp = c;\n c = d;\n d = temp;\n }\n int[] cands;\n if (a != c && children[a].contains(c))\n cands = new int[] {subXors[c], subXors[a] ^ subXors[c], xors ^ subXors[a]};\n else if (a != c && children[c].contains(a))\n cands = new int[] {subXors[a], subXors[c] ^ subXors[a], xors ^ subXors[c]};\n else\n cands = new int[] {subXors[a], subXors[c], xors ^ subXors[a] ^ subXors[c]};\n ans = Math.min(ans, Arrays.stream(cands).max().getAsInt() -\n Arrays.stream(cands).min().getAsInt());\n }\n }\n\n return ans;\n }\n\n private Pair> dfs(List[] tree, int u, int prev, int[] subXors,\n Set[] children) {\n for (final int v : tree[u]) {\n if (v == prev)\n continue;\n final Pair> pair = dfs(tree, v, u, subXors, children);\n final int vXor = pair.getKey();\n final Set vChildren = pair.getValue();\n subXors[u] ^= vXor;\n for (final int child : vChildren)\n children[u].add(child);\n }\n return new Pair<>(subXors[u], children[u]);\n }\n\n private int getXors(int[] nums) {\n int xors = 0;\n for (final int num : nums)\n xors ^= num;\n return xors;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minimumScore(vector& nums, vector>& edges) {\n const int n = nums.size();\n const int xors = reduce(nums.begin(), nums.end(), 0, bit_xor());\n vector subXors(nums);\n vector> tree(n);\n vector> children(n);\n\n for (int i = 0; i < n; ++i)\n children[i].insert(i);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n tree[u].push_back(v);\n tree[v].push_back(u);\n }\n\n dfs(tree, 0, -1, subXors, children);\n\n int ans = INT_MAX;\n\n for (int i = 0; i < edges.size(); ++i) {\n int a = edges[i][0];\n int b = edges[i][1];\n if (children[a].contains(b))\n swap(a, b);\n for (int j = 0; j < i; ++j) {\n int c = edges[j][0];\n int d = edges[j][1];\n if (children[c].contains(d))\n swap(c, d);\n vector cands;\n if (a != c && children[a].contains(c))\n cands = {subXors[c], subXors[a] ^ subXors[c], xors ^ subXors[a]};\n else if (a != c && children[c].contains(a))\n cands = {subXors[a], subXors[c] ^ subXors[a], xors ^ subXors[c]};\n else\n cands = {subXors[a], subXors[c], xors ^ subXors[a] ^ subXors[c]};\n ans = min(ans, ranges::max(cands) - ranges::min(cands));\n }\n }\n\n return ans;\n }\n\n private:\n pair> dfs(const vector>& tree, int u,\n int prev, vector& subXors,\n vector>& children) {\n for (const int v : tree[u]) {\n if (v == prev)\n continue;\n const auto& [vXor, vChildren] = dfs(tree, v, u, subXors, children);\n subXors[u] ^= vXor;\n children[u].insert(vChildren.begin(), vChildren.end());\n }\n return {subXors[u], children[u]};\n }\n};\n"} +{"task_num": 2332, "task_title": "The Latest Time to Catch a Bus", "difficulty": 2, "func_name": "latestTimeCatchTheBus", "description": "You are given a 0-indexed integer array `buses` of length `n`, where\n`buses[i]` represents the departure time of the `ith` bus. You are also given\na 0-indexed integer array `passengers` of length `m`, where `passengers[j]`\nrepresents the arrival time of the `jth` passenger. All bus departure times\nare unique. All passenger arrival times are unique.\n\nYou are given an integer `capacity`, which represents the maximum number of\npassengers that can get on each bus.\n\nWhen a passenger arrives, they will wait in line for the next available bus.\nYou can get on a bus that departs at `x` minutes if you arrive at `y` minutes\nwhere `y <= x`, and the bus is not full. Passengers with the earliest arrival\ntimes get on the bus first.\n\nMore formally when a bus arrives, either:\n\n* If `capacity` or fewer passengers are waiting for a bus, they will all get on the bus, or\n* The `capacity` passengers with the earliest arrival times will get on the bus.\n\nReturn the latest time you may arrive at the bus station to catch a bus. You\ncannot arrive at the same time as another passenger.\n\nNote: The arrays `buses` and `passengers` are not necessarily sorted.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int:\n buses.sort()\n passengers.sort()\n\n if passengers[0] > buses[-1]:\n return buses[-1]\n\n ans = passengers[0] - 1\n i = 0\n j = 0\n while i < len(buses):\n arrived = 0\n while arrived < capacity and j < len(passengers) and passengers[j] <= buses[i]:\n if j > 0 and passengers[j] != passengers[j - 1] + 1:\n ans = passengers[j] - 1\n j += 1\n arrived += 1\n\n if arrived < capacity and j > 0 and passengers[j - 1] != buses[i]:\n ans = buses[i]\n i += 1\n\n return ans\n", "java_solution": "class Solution {\n public int latestTimeCatchTheBus(int[] buses, int[] passengers, int capacity) {\n Arrays.sort(buses);\n Arrays.sort(passengers);\n\n if (passengers[0] > buses[buses.length - 1])\n return buses[buses.length - 1];\n\n int ans = passengers[0] - 1;\n int i = 0; // buses' index\n int j = 0; // passengers' index\n\n while (i < buses.length) {\n // Greedily make passengers catch `buses[i]`.\n int arrived = 0;\n while (arrived < capacity && j < passengers.length && passengers[j] <= buses[i]) {\n if (j > 0 && passengers[j] != passengers[j - 1] + 1)\n ans = passengers[j] - 1;\n ++j;\n ++arrived;\n }\n // There's room for `buses[i]` to carry a passenger arriving at the\n // `buses[i]`.\n if (arrived < capacity && j > 0 && passengers[j - 1] != buses[i])\n ans = buses[i];\n ++i;\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int latestTimeCatchTheBus(vector& buses, vector& passengers,\n int capacity) {\n ranges::sort(buses);\n ranges::sort(passengers);\n\n if (passengers.front() > buses.back())\n return buses.back();\n\n int ans = passengers[0] - 1;\n int i = 0; // buses' index\n int j = 0; // passengers' index\n\n while (i < buses.size()) {\n // Greedily make passengers catch `buses[i]`.\n int arrived = 0;\n while (arrived < capacity && j < passengers.size() &&\n passengers[j] <= buses[i]) {\n if (j > 0 && passengers[j] != passengers[j - 1] + 1)\n ans = passengers[j] - 1;\n ++j;\n ++arrived;\n }\n // There's room for `buses[i]` to carry a passenger arriving at\n // `buses[i]`.\n if (arrived < capacity && j > 0 && passengers[j - 1] != buses[i])\n ans = buses[i];\n ++i;\n }\n\n return ans;\n }\n};\n"} +{"task_num": 2337, "task_title": "Move Pieces to Obtain a String", "difficulty": 2, "func_name": "canChange", "description": "You are given two strings `start` and `target`, both of length `n`. Each\nstring consists only of the characters `'L'`, `'R'`, and `'_'` where:\n\n* The characters `'L'` and `'R'` represent pieces, where a piece `'L'` can move to the left only if there is a blank space directly to its left, and a piece `'R'` can move to the right only if there is a blank space directly to its right.\n* The character `'_'` represents a blank space that can be occupied by any of the `'L'` or `'R'` pieces.\n\nReturn `true` if it is possible to obtain the string `target` by moving the\npieces of the string `start` any number of times. Otherwise, return `false`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def canChange(self, start: str, target: str) -> bool:\n n = len(start)\n i = 0\n j = 0\n\n while i <= n and j <= n:\n while i < n and start[i] == '_':\n i += 1\n while j < n and target[j] == '_':\n j += 1\n if i == n or j == n:\n return i == n and j == n\n if start[i] != target[j]:\n return False\n if start[i] == 'R' and i > j:\n return False\n if start[i] == 'L' and i < j:\n return False\n i += 1\n j += 1\n\n return True\n", "java_solution": "class Solution {\n public boolean canChange(String start, String target) {\n final int n = start.length();\n int i = 0; // start's index\n int j = 0; // target's index\n\n while (i <= n && j <= n) {\n while (i < n && start.charAt(i) == '_')\n ++i;\n while (j < n && target.charAt(j) == '_')\n ++j;\n if (i == n || j == n)\n return i == n && j == n;\n if (start.charAt(i) != target.charAt(j))\n return false;\n if (start.charAt(i) == 'R' && i > j)\n return false;\n if (start.charAt(i) == 'L' && i < j)\n return false;\n ++i;\n ++j;\n }\n\n return true;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool canChange(string start, string target) {\n const int n = start.length();\n int i = 0; // start's index\n int j = 0; // target's index\n\n while (i <= n && j <= n) {\n while (i < n && start[i] == '_')\n ++i;\n while (j < n && target[j] == '_')\n ++j;\n if (i == n || j == n)\n return i == n && j == n;\n if (start[i] != target[j])\n return false;\n if (start[i] == 'R' && i > j)\n return false;\n if (start[i] == 'L' && i < j)\n return false;\n ++i;\n ++j;\n }\n\n return true;\n }\n};\n"} +{"task_num": 2392, "task_title": "Build a Matrix With Conditions", "difficulty": 3, "func_name": "buildMatrix", "description": "You are given a positive integer `k`. You are also given:\n\n* a 2D integer array `rowConditions` of size `n` where `rowConditions[i] = [abovei, belowi]`, and\n* a 2D integer array `colConditions` of size `m` where `colConditions[i] = [lefti, righti]`.\n\nThe two arrays contain integers from `1` to `k`.\n\nYou have to build a `k x k` matrix that contains each of the numbers from `1`\nto `k` exactly once. The remaining cells should have the value `0`.\n\nThe matrix should also satisfy the following conditions:\n\n* The number `abovei` should appear in a row that is strictly above the row at which the number `belowi` appears for all `i` from `0` to `n - 1`.\n* The number `lefti` should appear in a column that is strictly left of the column at which the number `righti` appears for all `i` from `0` to `m - 1`.\n\nReturn any matrix that satisfies the conditions. If no answer exists, return\nan empty matrix.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]:\n rowOrder = self._topologicalSort(rowConditions, k)\n if not rowOrder:\n return []\n\n colOrder = self._topologicalSort(colConditions, k)\n if not colOrder:\n return []\n\n ans = [[0] * k for _ in range(k)]\n nodeToRowIndex = [0] * (k + 1)\n\n for i, node in enumerate(rowOrder):\n nodeToRowIndex[node] = i\n\n for j, node in enumerate(colOrder):\n i = nodeToRowIndex[node]\n ans[i][j] = node\n\n return ans\n\n def _topologicalSort(self, conditions: List[List[int]], n: int) -> List[int]:\n order = []\n graph = [[] for _ in range(n + 1)]\n inDegrees = [0] * (n + 1)\n\n for u, v in conditions:\n graph[u].append(v)\n inDegrees[v] += 1\n\n q = collections.deque([i for i in range(1, n + 1) if inDegrees[i] == 0])\n\n while q:\n u = q.popleft()\n order.append(u)\n for v in graph[u]:\n inDegrees[v] -= 1\n if inDegrees[v] == 0:\n q.append(v)\n\n if len(order) == n:\n return order\n else:\n return []\n", "java_solution": "class Solution {\n public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n List rowOrder = topologicalSort(rowConditions, k);\n if (rowOrder.isEmpty())\n return new int[][] {};\n\n List colOrder = topologicalSort(colConditions, k);\n if (colOrder.isEmpty())\n return new int[][] {};\n\n int[][] ans = new int[k][k];\n int[] nodeToRowIndex = new int[k + 1];\n\n for (int i = 0; i < k; ++i)\n nodeToRowIndex[rowOrder.get(i)] = i;\n\n for (int j = 0; j < k; ++j) {\n final int node = colOrder.get(j);\n final int i = nodeToRowIndex[node];\n ans[i][j] = node;\n }\n\n return ans;\n }\n\n private List topologicalSort(int[][] conditions, int n) {\n List order = new ArrayList<>();\n List[] graph = new List[n + 1];\n int[] inDegrees = new int[n + 1];\n Queue q = new ArrayDeque<>();\n\n for (int i = 1; i <= n; ++i)\n graph[i] = new ArrayList<>();\n\n // Build the graph.\n for (int[] condition : conditions) {\n final int u = condition[0];\n final int v = condition[1];\n graph[u].add(v);\n ++inDegrees[v];\n }\n\n // Perform topological sorting.\n for (int i = 1; i <= n; ++i)\n if (inDegrees[i] == 0)\n q.offer(i);\n\n while (!q.isEmpty()) {\n final int u = q.poll();\n order.add(u);\n for (final int v : graph[u])\n if (--inDegrees[v] == 0)\n q.offer(v);\n }\n\n return order.size() == n ? order : new ArrayList<>();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector> buildMatrix(int k, vector>& rowConditions,\n vector>& colConditions) {\n const vector rowOrder = topologicalSort(rowConditions, k);\n if (rowOrder.empty())\n return {};\n\n const vector colOrder = topologicalSort(colConditions, k);\n if (colOrder.empty())\n return {};\n\n vector> ans(k, vector(k));\n vector nodeToRowIndex(k + 1);\n\n for (int i = 0; i < k; ++i)\n nodeToRowIndex[rowOrder[i]] = i;\n\n for (int j = 0; j < k; ++j) {\n const int node = colOrder[j];\n const int i = nodeToRowIndex[node];\n ans[i][j] = node;\n }\n\n return ans;\n }\n\n private:\n vector topologicalSort(const vector>& conditions, int n) {\n vector order;\n vector> graph(n + 1);\n vector inDegrees(n + 1);\n queue q;\n\n // Build the graph.\n for (const vector& condition : conditions) {\n const int u = condition[0];\n const int v = condition[1];\n graph[u].push_back(v);\n ++inDegrees[v];\n }\n\n // Perform topological sorting.\n for (int i = 1; i <= n; ++i)\n if (inDegrees[i] == 0)\n q.push(i);\n\n while (!q.empty()) {\n const int u = q.front();\n q.pop();\n order.push_back(u);\n for (const int v : graph[u])\n if (--inDegrees[v] == 0)\n q.push(v);\n }\n\n return order.size() == n ? order : vector();\n }\n};\n"} +{"task_num": 2437, "task_title": "Number of Valid Clock Times", "difficulty": 1, "func_name": "countTime", "description": "You are given a string of length `5` called `time`, representing the current\ntime on a digital clock in the format `\"hh:mm\"`. The earliest possible time is\n`\"00:00\"` and the latest possible time is `\"23:59\"`.\n\nIn the string `time`, the digits represented by the `?` symbol are unknown,\nand must be replaced with a digit from `0` to `9`.\n\nReturn an integer `answer`, the number of valid clock times that can be\ncreated by replacing every `?` with a digit from `0` to `9`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def countTime(self, time: str) -> int:\n ans = 1\n if time[3] == '?':\n ans *= 6\n if time[4] == '?':\n ans *= 10\n\n if time[0] == '?' and time[1] == '?':\n return ans * 24\n if time[0] == '?':\n if time[1] < '4':\n return ans * 3\n else:\n return ans * 2\n if time[1] == '?':\n if time[0] == '2':\n return ans * 4\n else:\n return ans * 10\n return ans\n", "java_solution": "class Solution {\n public int countTime(String time) {\n int ans = 1;\n if (time.charAt(3) == '?')\n ans *= 6;\n if (time.charAt(4) == '?')\n ans *= 10;\n\n if (time.charAt(0) == '?' && time.charAt(1) == '?')\n return ans * 24;\n if (time.charAt(0) == '?')\n return time.charAt(1) < '4' ? ans * 3 : ans * 2;\n if (time.charAt(1) == '?')\n return time.charAt(0) == '2' ? ans * 4 : ans * 10;\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int countTime(string time) {\n int ans = 1;\n if (time[3] == '?')\n ans *= 6;\n if (time[4] == '?')\n ans *= 10;\n\n if (time[0] == '?' && time[1] == '?')\n return ans * 24;\n if (time[0] == '?')\n return time[1] < '4' ? ans * 3 : ans * 2;\n if (time[1] == '?')\n return time[0] == '2' ? ans * 4 : ans * 10;\n return ans;\n }\n};\n"} +{"task_num": 2456, "task_title": "Most Popular Video Creator", "difficulty": 2, "func_name": "mostPopularCreator", "description": "You are given two string arrays `creators` and `ids`, and an integer array\n`views`, all of length `n`. The `ith` video on a platform was created by\n`creator[i]`, has an id of `ids[i]`, and has `views[i]` views.\n\nThe popularity of a creator is the sum of the number of views on all of the\ncreator's videos. Find the creator with the highest popularity and the id of\ntheir most viewed video.\n\n* If multiple creators have the highest popularity, find all of them.\n* If multiple videos have the highest view count for a creator, find the lexicographically smallest id.\n\nReturn a 2D array of strings `answer` where `answer[i] = [creatori, idi]`\nmeans that `creatori` has the highest popularity and `idi` is the id of their\nmost popular video. The answer can be returned in any order.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Creator:\n def __init__(self, popularity: int, videoId: str, maxView: int):\n self.popularity = popularity\n self.videoId = videoId\n self.maxView = maxView\n\n\nclass Solution:\n def mostPopularCreator(self, creators: List[str], ids: List[str], views: List[int]) -> List[List[str]]:\n ans = []\n maxPopularity = 0\n nameToCreator = {}\n\n for name, id, view in zip(creators, ids, views):\n if name not in nameToCreator:\n nameToCreator[name] = Creator(view, id, view)\n maxPopularity = max(maxPopularity, view)\n continue\n creator = nameToCreator[name]\n creator.popularity += view\n maxPopularity = max(maxPopularity, creator.popularity)\n if creator.maxView < view or creator.maxView == view and creator.videoId > id:\n creator.videoId = id\n creator.maxView = view\n\n for name, creator in nameToCreator.items():\n if creator.popularity == maxPopularity:\n ans.append([name, creator.videoId])\n\n return ans\n", "java_solution": "class Creator {\n public long popularity; // the popularity sum\n public String videoId; // the video id that has the maximum view\n public int maxView; // the maximum view of the creator\n public Creator(long popularity, String videoId, int maxView) {\n this.popularity = popularity;\n this.videoId = videoId;\n this.maxView = maxView;\n }\n}\n\nclass Solution {\n public List> mostPopularCreator(String[] creators, String[] ids, int[] views) {\n List> ans = new ArrayList<>();\n Map nameToCreator = new HashMap<>();\n long maxPopularity = 0;\n\n for (int i = 0; i < creators.length; ++i) {\n if (!nameToCreator.containsKey(creators[i])) {\n nameToCreator.put(creators[i], new Creator(views[i], ids[i], views[i]));\n maxPopularity = Math.max(maxPopularity, (long) views[i]);\n continue;\n }\n Creator creator = nameToCreator.get(creators[i]);\n creator.popularity += views[i];\n maxPopularity = Math.max(maxPopularity, (long) creator.popularity);\n if (creator.maxView < views[i] ||\n creator.maxView == views[i] && creator.videoId.compareTo(ids[i]) > 0) {\n creator.videoId = ids[i];\n creator.maxView = views[i];\n }\n }\n\n for (Map.Entry entry : nameToCreator.entrySet())\n if (entry.getValue().popularity == maxPopularity)\n ans.add(Arrays.asList(entry.getKey(), entry.getValue().videoId));\n\n return ans;\n }\n}\n", "cpp_solution": "struct Creator {\n long popularity; // the popularity sum\n string videoId; // the video id that has the maximum view\n int maxView; // the maximum view of the creator\n};\n\nclass Solution {\n public:\n vector> mostPopularCreator(vector& creators,\n vector& ids,\n vector& views) {\n vector> ans;\n unordered_map nameToCreator;\n long maxPopularity = 0;\n\n for (int i = 0; i < creators.size(); ++i) {\n if (!nameToCreator.contains(creators[i])) {\n nameToCreator[creators[i]] = Creator{\n .popularity = views[i],\n .videoId = ids[i],\n .maxView = views[i],\n };\n maxPopularity = max(maxPopularity, static_cast(views[i]));\n continue;\n }\n Creator& creator = nameToCreator[creators[i]];\n creator.popularity += views[i];\n maxPopularity = max(maxPopularity, static_cast(creator.popularity));\n if (creator.maxView < views[i] ||\n creator.maxView == views[i] && creator.videoId > ids[i]) {\n creator.videoId = ids[i];\n creator.maxView = views[i];\n }\n }\n\n for (const auto& [name, creator] : nameToCreator)\n if (creator.popularity == maxPopularity)\n ans.push_back({name, creator.videoId});\n\n return ans;\n }\n};\n"} +{"task_num": 2462, "task_title": "Total Cost to Hire K Workers", "difficulty": 2, "func_name": "totalCost", "description": "You are given a 0-indexed integer array `costs` where `costs[i]` is the cost\nof hiring the `ith` worker.\n\nYou are also given two integers `k` and `candidates`. We want to hire exactly\n`k` workers according to the following rules:\n\n* You will run `k` sessions and hire exactly one worker in each session.\n* In each hiring session, choose the worker with the lowest cost from either the first `candidates` workers or the last `candidates` workers. Break the tie by the smallest index. \n* For example, if `costs = [3,2,7,7,1,2]` and `candidates = 2`, then in the first hiring session, we will choose the `4th` worker because they have the lowest cost `[3,2,7,7,1,2]`.\n* In the second hiring session, we will choose `1st` worker because they have the same lowest cost as `4th` worker but they have the smallest index `[3,2,7,7,2]`. Please note that the indexing may be changed in the process.\n* If there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index.\n* A worker can only be chosen once.\n\nReturn the total cost to hire exactly `k` workers.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def totalCost(self, costs: List[int], k: int, candidates: int) -> int:\n ans = 0\n i = 0\n j = len(costs) - 1\n minHeapL = []\n minHeapR = []\n\n for _ in range(k):\n while len(minHeapL) < candidates and i <= j:\n heapq.heappush(minHeapL, costs[i])\n i += 1\n while len(minHeapR) < candidates and i <= j:\n heapq.heappush(minHeapR, costs[j])\n j -= 1\n if not minHeapL:\n ans += heapq.heappop(minHeapR)\n elif not minHeapR:\n ans += heapq.heappop(minHeapL)\n elif minHeapL[0] <= minHeapR[0]:\n ans += heapq.heappop(minHeapL)\n else:\n ans += heapq.heappop(minHeapR)\n\n return ans\n", "java_solution": "class Solution {\n public long totalCost(int[] costs, int k, int candidates) {\n long ans = 0;\n int i = 0;\n int j = costs.length - 1;\n Queue minHeapL = new PriorityQueue<>();\n Queue minHeapR = new PriorityQueue<>();\n\n for (int hired = 0; hired < k; ++hired) {\n while (minHeapL.size() < candidates && i <= j)\n minHeapL.offer(costs[i++]);\n while (minHeapR.size() < candidates && i <= j)\n minHeapR.offer(costs[j--]);\n if (minHeapL.isEmpty())\n ans += minHeapR.poll();\n else if (minHeapR.isEmpty())\n ans += minHeapL.poll();\n // Both `minHeapL` and `minHeapR` are not empty.\n else if (minHeapL.peek() <= minHeapR.peek())\n ans += minHeapL.poll();\n else\n ans += minHeapR.poll();\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n long long totalCost(vector& costs, int k, int candidates) {\n long ans = 0;\n int i = 0;\n int j = costs.size() - 1;\n priority_queue, greater<>> minHeapL;\n priority_queue, greater<>> minHeapR;\n\n for (int hired = 0; hired < k; ++hired) {\n while (minHeapL.size() < candidates && i <= j)\n minHeapL.push(costs[i++]);\n while (minHeapR.size() < candidates && i <= j)\n minHeapR.push(costs[j--]);\n if (minHeapL.empty())\n ans += minHeapR.top(), minHeapR.pop();\n else if (minHeapR.empty())\n ans += minHeapL.top(), minHeapL.pop();\n // Both `minHeapL` and `minHeapR` are not empty.\n else if (minHeapL.top() <= minHeapR.top())\n ans += minHeapL.top(), minHeapL.pop();\n else\n ans += minHeapR.top(), minHeapR.pop();\n }\n\n return ans;\n }\n};\n"} +{"task_num": 2467, "task_title": "Most Profitable Path in a Tree", "difficulty": 2, "func_name": "mostProfitablePath", "description": "There is an undirected tree with `n` nodes labeled from `0` to `n - 1`, rooted\nat node `0`. You are given a 2D integer array `edges` of length `n - 1` where\n`edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and\n`bi` in the tree.\n\nAt every node `i`, there is a gate. You are also given an array of even\nintegers `amount`, where `amount[i]` represents:\n\n* the price needed to open the gate at node `i`, if `amount[i]` is negative, or,\n* the cash reward obtained on opening the gate at node `i`, otherwise.\n\nThe game goes on as follows:\n\n* Initially, Alice is at node `0` and Bob is at node `bob`.\n* At every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf node, while Bob moves towards node `0`.\n* For every node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that: \n* If the gate is already open, no price will be required, nor will there be any cash reward.\n* If Alice and Bob reach the node simultaneously, they share the price/reward for opening the gate there. In other words, if the price to open the gate is `c`, then both Alice and Bob pay `c / 2` each. Similarly, if the reward at the gate is `c`, both of them receive `c / 2` each.\n* If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node `0`, he stops moving. Note that these events are independent of each other.\n\nReturn the maximum net income Alice can have if she travels towards the\noptimal leaf node.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int:\n n = len(amount)\n tree = [[] for _ in range(n)]\n parent = [0] * n\n aliceDist = [-1] * n\n\n for u, v in edges:\n tree[u].append(v)\n tree[v].append(u)\n\n def dfs(u: int, prev: int, d: int) -> None:\n parent[u] = prev\n aliceDist[u] = d\n for v in tree[u]:\n if aliceDist[v] == -1:\n dfs(v, u, d + 1)\n\n dfs(0, -1, 0)\n\n u = bob\n bobDist = 0\n while u != 0:\n if bobDist < aliceDist[u]:\n amount[u] = 0\n elif bobDist == aliceDist[u]:\n amount[u] //= 2\n u = parent[u]\n bobDist += 1\n\n return self._getMoney(tree, 0, -1, amount)\n\n def _getMoney(self, tree: List[List[int]], u: int, prev: int, amount: List[int]) -> int:\n if len(tree[u]) == 1 and tree[u][0] == prev:\n return amount[u]\n\n maxPath = -math.inf\n for v in tree[u]:\n if v != prev:\n maxPath = max(maxPath, self._getMoney(tree, v, u, amount))\n\n return amount[u] + maxPath\n", "java_solution": "class Solution {\n public int mostProfitablePath(int[][] edges, int bob, int[] amount) {\n final int n = amount.length;\n List[] tree = new List[n];\n int[] parent = new int[n];\n int[] aliceDist = new int[n];\n Arrays.fill(aliceDist, -1);\n\n for (int i = 0; i < n; ++i)\n tree[i] = new ArrayList<>();\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n tree[u].add(v);\n tree[v].add(u);\n }\n\n dfs(tree, 0, -1, 0, parent, aliceDist);\n\n // Modify the amount along the path from node Bob to node 0.\n // For each node,\n // 1. If Bob reaches earlier than Alice does, change the amount to 0.\n // 2. If Bob and Alice reach simultaneously, devide the amount by 2.\n for (int u = bob, bobDist = 0; u != 0; u = parent[u], ++bobDist)\n if (bobDist < aliceDist[u])\n amount[u] = 0;\n else if (bobDist == aliceDist[u])\n amount[u] /= 2;\n\n return getMoney(tree, 0, -1, amount);\n }\n\n // Fills `parent` and `dist`.\n private void dfs(List[] tree, int u, int prev, int d, int[] parent, int[] dist) {\n parent[u] = prev;\n dist[u] = d;\n for (final int v : tree[u]) {\n if (dist[v] == -1)\n dfs(tree, v, u, d + 1, parent, dist);\n }\n }\n\n private int getMoney(List[] tree, int u, int prev, int[] amount) {\n // a leaf node\n if (tree[u].size() == 1 && tree[u].get(0) == prev)\n return amount[u];\n\n int maxPath = Integer.MIN_VALUE;\n for (final int v : tree[u])\n if (v != prev)\n maxPath = Math.max(maxPath, getMoney(tree, v, u, amount));\n\n return amount[u] + maxPath;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int mostProfitablePath(vector>& edges, int bob,\n vector& amount) {\n const int n = amount.size();\n vector> tree(n);\n vector parent(n);\n vector aliceDist(n, -1);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n tree[u].push_back(v);\n tree[v].push_back(u);\n }\n\n dfs(tree, 0, -1, 0, parent, aliceDist);\n\n // Modify the amount along the path from node Bob to node 0.\n // For each node,\n // 1. If Bob reaches earlier than Alice does, change the amount to 0.\n // 2. If Bob and Alice reach simultaneously, devide the amount by 2.\n for (int u = bob, bobDist = 0; u != 0; u = parent[u], ++bobDist)\n if (bobDist < aliceDist[u])\n amount[u] = 0;\n else if (bobDist == aliceDist[u])\n amount[u] /= 2;\n\n return getMoney(tree, 0, -1, amount);\n }\n\n private:\n // Fills `parent` and `dist`.\n void dfs(const vector>& tree, int u, int prev, int d,\n vector& parent, vector& dist) {\n parent[u] = prev;\n dist[u] = d;\n for (const int v : tree[u]) {\n if (dist[v] == -1)\n dfs(tree, v, u, d + 1, parent, dist);\n }\n }\n\n int getMoney(const vector>& tree, int u, int prev,\n const vector& amount) {\n // a leaf node\n if (tree[u].size() == 1 && tree[u][0] == prev)\n return amount[u];\n\n int maxPath = INT_MIN;\n for (const int v : tree[u])\n if (v != prev)\n maxPath = max(maxPath, getMoney(tree, v, u, amount));\n\n return amount[u] + maxPath;\n }\n};\n"} +{"task_num": 2499, "task_title": "Minimum Total Cost to Make Arrays Unequal", "difficulty": 3, "func_name": "minimumTotalCost", "description": "You are given two 0-indexed integer arrays `nums1` and `nums2`, of equal\nlength `n`.\n\nIn one operation, you can swap the values of any two indices of `nums1`. The\ncost of this operation is the sum of the indices.\n\nFind the minimum total cost of performing the given operation any number of\ntimes such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after\nperforming all the operations.\n\nReturn the minimum total cost such that `nums1` and `nums2` satisfy the above\ncondition. In case it is not possible, return `-1`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n n = len(nums1)\n ans = 0\n maxFreq = 0\n maxFreqNum = 0\n shouldBeSwapped = 0\n conflictedNumCount = [0] * (n + 1)\n\n for i, (num1, num2) in enumerate(zip(nums1, nums2)):\n if num1 == num2:\n conflictedNum = num1\n conflictedNumCount[conflictedNum] += 1\n if conflictedNumCount[conflictedNum] > maxFreq:\n maxFreq = conflictedNumCount[conflictedNum]\n maxFreqNum = conflictedNum\n shouldBeSwapped += 1\n ans += i\n\n for i, (num1, num2) in enumerate(zip(nums1, nums2)):\n if maxFreq * 2 <= shouldBeSwapped:\n break\n if num1 == num2:\n continue\n\n if num1 == maxFreqNum or num2 == maxFreqNum:\n continue\n shouldBeSwapped += 1\n ans += i\n\n if maxFreq * 2 > shouldBeSwapped:\n return -1\n else:\n return ans\n", "java_solution": "class Solution {\n public long minimumTotalCost(int[] nums1, int[] nums2) {\n final int n = nums1.length;\n long ans = 0;\n int maxFreq = 0;\n int maxFreqNum = 0;\n int shouldBeSwapped = 0;\n int[] conflictedNumCount = new int[n + 1];\n\n // Collect the indices i s.t. nums1[i] == nums2[i] and record their `maxFreq`\n // and `maxFreqNum`.\n for (int i = 0; i < n; ++i)\n if (nums1[i] == nums2[i]) {\n final int conflictedNum = nums1[i];\n if (++conflictedNumCount[conflictedNum] > maxFreq) {\n maxFreq = conflictedNumCount[conflictedNum];\n maxFreqNum = conflictedNum;\n }\n ++shouldBeSwapped;\n ans += i;\n }\n\n // Collect the indices with nums1[i] != nums2[i] that contribute less cost.\n // This can be greedily achieved by iterating from 0 to n - 1.\n for (int i = 0; i < n; ++i) {\n // Since we have over `maxFreq * 2` spaces, `maxFreqNum` can be\n // successfully distributed, so no need to collectextra spaces.\n if (maxFreq * 2 <= shouldBeSwapped)\n break;\n if (nums1[i] == nums2[i])\n continue;\n // The numbers == `maxFreqNum` worsen the result since they increase the\n // `maxFreq`.\n if (nums1[i] == maxFreqNum || nums2[i] == maxFreqNum)\n continue;\n ++shouldBeSwapped;\n ans += i;\n }\n\n return maxFreq * 2 > shouldBeSwapped ? -1 : ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n long long minimumTotalCost(vector& nums1, vector& nums2) {\n const int n = nums1.size();\n long ans = 0;\n int maxFreq = 0;\n int maxFreqNum = 0;\n int shouldBeSwapped = 0;\n vector conflictedNumCount(n + 1);\n\n // Collect the indices i s.t. nums1[i] == nums2[i] and record their\n // `maxFreq` and `maxFreqNum`.\n for (int i = 0; i < n; ++i)\n if (nums1[i] == nums2[i]) {\n const int conflictedNum = nums1[i];\n if (++conflictedNumCount[conflictedNum] > maxFreq) {\n maxFreq = conflictedNumCount[conflictedNum];\n maxFreqNum = conflictedNum;\n }\n ++shouldBeSwapped;\n ans += i;\n }\n\n // Collect the indices with nums1[i] != nums2[i] that contribute less cost.\n // This can be greedily achieved by iterating from 0 to n - 1.\n for (int i = 0; i < n; ++i) {\n // Since we have over `maxFreq * 2` spaces, `maxFreqNum` can be\n // successfully distributed, so no need to collectextra spaces.\n if (maxFreq * 2 <= shouldBeSwapped)\n break;\n if (nums1[i] == nums2[i])\n continue;\n // The numbers == `maxFreqNum` worsen the result since they increase the\n // `maxFreq`.\n if (nums1[i] == maxFreqNum || nums2[i] == maxFreqNum)\n continue;\n ++shouldBeSwapped;\n ans += i;\n }\n\n return maxFreq * 2 > shouldBeSwapped ? -1 : ans;\n }\n};\n"} +{"task_num": 2503, "task_title": "Maximum Number of Points From Grid Queries", "difficulty": 3, "func_name": "maxPoints", "description": "You are given an `m x n` integer matrix `grid` and an array `queries` of size\n`k`.\n\nFind an array `answer` of size `k` such that for each integer `queries[i]` you\nstart in the top left cell of the matrix and repeat the following process:\n\n* If `queries[i]` is strictly greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any adjacent cell in all `4` directions: up, down, left, and right.\n* Otherwise, you do not get any points, and you end this process.\n\nAfter the process, `answer[i]` is the maximum number of points you can get.\nNote that for each query you are allowed to visit the same cell multiple\ntimes.\n\nReturn the resulting array `answer`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass IndexedQuery:\n def __init__(self, queryIndex: int, query: int):\n self.queryIndex = queryIndex\n self.query = query\n\n def __iter__(self):\n yield self.queryIndex\n yield self.query\n\n\nclass Solution:\n def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(grid)\n n = len(grid[0])\n ans = [0] * len(queries)\n minHeap = [(grid[0][0], 0, 0)]\n seen = {(0, 0)}\n accumulate = 0\n\n for queryIndex, query in sorted([IndexedQuery(i, query) for i, query in enumerate(queries)], key=lambda iq: iq.query):\n while minHeap:\n val, i, j = heapq.heappop(minHeap)\n if val >= query:\n heapq.heappush(minHeap, (val, i, j))\n break\n accumulate += 1\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if (x, y) in seen:\n continue\n heapq.heappush(minHeap, (grid[x][y], x, y))\n seen.add((x, y))\n ans[queryIndex] = accumulate\n\n return ans\n", "java_solution": "class Solution {\n public int[] maxPoints(int[][] grid, int[] queries) {\n record T(int i, int j, int val) {}\n final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n final int m = grid.length;\n final int n = grid[0].length;\n int[] ans = new int[queries.length];\n Queue minHeap = new PriorityQueue<>(Comparator.comparingInt(T::val));\n boolean[][] seen = new boolean[m][n];\n\n minHeap.offer(new T(0, 0, grid[0][0]));\n seen[0][0] = true;\n int accumulate = 0;\n\n for (IndexedQuery indexedQuery : getIndexedQueries(queries)) {\n final int queryIndex = indexedQuery.queryIndex;\n final int query = indexedQuery.query;\n while (!minHeap.isEmpty()) {\n final int i = minHeap.peek().i;\n final int j = minHeap.peek().j;\n final int val = minHeap.poll().val;\n if (val >= query) {\n // The smallest neighbor is still larger than `query`, so no need to\n // keep exploring. Re-push (i, j, grid[i][j]) back to the `minHeap`.\n minHeap.offer(new T(i, j, val));\n break;\n }\n ++accumulate;\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n minHeap.offer(new T(x, y, grid[x][y]));\n seen[x][y] = true;\n }\n }\n ans[queryIndex] = accumulate;\n }\n\n return ans;\n }\n\n private record IndexedQuery(int queryIndex, int query) {}\n\n private IndexedQuery[] getIndexedQueries(int[] queries) {\n IndexedQuery[] indexedQueries = new IndexedQuery[queries.length];\n for (int i = 0; i < queries.length; ++i)\n indexedQueries[i] = new IndexedQuery(i, queries[i]);\n Arrays.sort(indexedQueries, Comparator.comparingInt(IndexedQuery::query));\n return indexedQueries;\n }\n}\n", "cpp_solution": "struct IndexedQuery {\n int queryIndex;\n int query;\n};\n\nstruct T {\n int i;\n int j;\n int val; // grid[i][j]\n};\n\nclass Solution {\n public:\n vector maxPoints(vector>& grid, vector& queries) {\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n const int m = grid.size();\n const int n = grid[0].size();\n vector ans(queries.size());\n auto compare = [](const T& a, const T& b) { return a.val > b.val; };\n priority_queue, decltype(compare)> minHeap(compare);\n vector> seen(m, vector(n));\n\n minHeap.emplace(0, 0, grid[0][0]);\n seen[0][0] = true;\n int accumulate = 0;\n\n for (const auto& [queryIndex, query] : getIndexedQueries(queries)) {\n while (!minHeap.empty()) {\n const auto [i, j, val] = minHeap.top();\n minHeap.pop();\n if (val >= query) {\n // The smallest neighbor is still larger than `query`, so no need to\n // keep exploring. Re-push (i, j, grid[i][j]) back to the `minHeap`.\n minHeap.emplace(i, j, val);\n break;\n }\n ++accumulate;\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n minHeap.emplace(x, y, grid[x][y]);\n seen[x][y] = true;\n }\n }\n ans[queryIndex] = accumulate;\n }\n\n return ans;\n }\n\n private:\n vector getIndexedQueries(const vector& queries) {\n vector indexedQueries;\n for (int i = 0; i < queries.size(); ++i)\n indexedQueries.push_back({i, queries[i]});\n ranges::sort(\n indexedQueries, ranges::less{},\n [](const IndexedQuery& indexedQuery) { return indexedQuery.query; });\n return indexedQueries;\n }\n};\n"} +{"task_num": 2508, "task_title": "Add Edges to Make Degrees of All Nodes Even", "difficulty": 3, "func_name": "isPossible", "description": "There is an undirected graph consisting of `n` nodes numbered from `1` to `n`.\nYou are given the integer `n` and a 2D array `edges` where `edges[i] = [ai,\nbi]` indicates that there is an edge between nodes `ai` and `bi`. The graph\ncan be disconnected.\n\nYou can add at most two additional edges (possibly none) to this graph so that\nthere are no repeated edges and no self-loops.\n\nReturn `true` if it is possible to make the degree of each node in the graph\neven, otherwise return `false`.\n\nThe degree of a node is the number of edges connected to it.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def isPossible(self, n: int, edges: List[List[int]]) -> bool:\n graph = [set() for _ in range(n)]\n\n for u, v in edges:\n graph[u - 1].add(v - 1)\n graph[v - 1].add(u - 1)\n\n oddNodes = [i for i, neighbor in enumerate(graph) if len(neighbor) & 1]\n if not oddNodes:\n return True\n if len(oddNodes) == 2:\n a, b = oddNodes\n return any(a not in graph[i] and b not in graph[i] for i in range(n))\n if len(oddNodes) == 4:\n a, b, c, d = oddNodes\n return (b not in graph[a] and d not in graph[c]) or (c not in graph[a] and d not in graph[b]) or (d not in graph[a] and c not in graph[b])\n return False\n", "java_solution": "class Solution {\n public boolean isPossible(int n, List> edges) {\n Set[] graph = new Set[n];\n\n for (int i = 0; i < n; ++i)\n graph[i] = new HashSet<>();\n\n for (List edge : edges) {\n final int u = edge.get(0) - 1;\n final int v = edge.get(1) - 1;\n graph[u].add(v);\n graph[v].add(u);\n }\n\n List oddNodes = getOddNodes(graph);\n if (oddNodes.isEmpty())\n return true;\n if (oddNodes.size() == 2) {\n final int a = oddNodes.get(0);\n final int b = oddNodes.get(1);\n for (int i = 0; i < n; ++i)\n // Can connect i with a and i with b.\n if (!graph[i].contains(a) && !graph[i].contains(b))\n return true;\n }\n if (oddNodes.size() == 4) {\n final int a = oddNodes.get(0);\n final int b = oddNodes.get(1);\n final int c = oddNodes.get(2);\n final int d = oddNodes.get(3);\n return (!graph[a].contains(b) && !graph[c].contains(d)) ||\n (!graph[a].contains(c) && !graph[b].contains(d)) ||\n (!graph[a].contains(d) && !graph[b].contains(c));\n }\n return false;\n }\n\n private List getOddNodes(Set[] graph) {\n List oddNodes = new ArrayList<>();\n for (int i = 0; i < graph.length; ++i)\n if (graph[i].size() % 2 == 1)\n oddNodes.add(i);\n return oddNodes;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool isPossible(int n, vector>& edges) {\n vector> graph(n);\n\n for (const vector& edge : edges) {\n const int u = edge[0] - 1;\n const int v = edge[1] - 1;\n graph[u].insert(v);\n graph[v].insert(u);\n }\n\n const vector oddNodes = getOddNodes(graph);\n if (oddNodes.empty())\n return true;\n if (oddNodes.size() == 2) {\n const int a = oddNodes[0];\n const int b = oddNodes[1];\n for (int i = 0; i < n; ++i)\n // Can connect i with a and i with b.\n if (!graph[i].contains(a) && !graph[i].contains(b))\n return true;\n }\n if (oddNodes.size() == 4) {\n const int a = oddNodes[0];\n const int b = oddNodes[1];\n const int c = oddNodes[2];\n const int d = oddNodes[3];\n return (!graph[a].contains(b) && !graph[c].contains(d)) ||\n (!graph[a].contains(c) && !graph[b].contains(d)) ||\n (!graph[a].contains(d) && !graph[b].contains(c));\n }\n return false;\n }\n\n private:\n vector getOddNodes(const vector>& graph) {\n vector oddNodes;\n for (int i = 0; i < graph.size(); ++i)\n if (graph[i].size() % 2 == 1)\n oddNodes.push_back(i);\n return oddNodes;\n }\n};\n"} +{"task_num": 2523, "task_title": "Closest Prime Numbers in Range", "difficulty": 2, "func_name": "closestPrimes", "description": "Given two positive integers `left` and `right`, find the two integers `num1`\nand `num2` such that:\n\n* `left <= num1 < num2 <= right `.\n* `num1` and `num2` are both prime numbers.\n* `num2 - num1` is the minimum amongst all other pairs satisfying the above conditions.\n\nReturn the positive integer array `ans = [num1, num2]`. If there are multiple\npairs satisfying these conditions, return the one with the minimum `num1`\nvalue or `[-1, -1]` if such numbers do not exist.\n\nA number greater than `1` is called prime if it is only divisible by `1` and\nitself.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def closestPrimes(self, left: int, right: int) -> List[int]:\n isPrime = self._sieveEratosthenes(right + 1)\n primes=[]\n for i in range(left, right+1):\n if isPrime[i]:\n primes.append(i)\n\n if len(primes) < 2:\n return [-1, -1]\n\n minDiff = math.inf\n num1 = -1\n num2 = -1\n\n for a, b in zip(primes, primes[1:]):\n diff = b - a\n if diff < minDiff:\n minDiff = diff\n num1 = a\n num2 = b\n\n return [num1, num2]\n\n def _sieveEratosthenes(self, n: int) -> List[bool]:\n isPrime = [True] * n\n isPrime[0] = False\n isPrime[1] = False\n for i in range(2, int(n**0.5) + 1):\n if isPrime[i]:\n for j in range(i * i, n, i):\n isPrime[j] = False\n return isPrime\n", "java_solution": "class Solution {\n public int[] closestPrimes(int left, int right) {\n final boolean[] isPrime = sieveEratosthenes(right + 1);\n List primes = new ArrayList<>();\n\n for (int i = left; i <= right; ++i)\n if (isPrime[i])\n primes.add(i);\n\n if (primes.size() < 2)\n return new int[] {-1, -1};\n\n int minDiff = Integer.MAX_VALUE;\n int num1 = -1;\n int num2 = -1;\n\n for (int i = 1; i < primes.size(); ++i) {\n final int diff = primes.get(i) - primes.get(i - 1);\n if (diff < minDiff) {\n minDiff = diff;\n num1 = primes.get(i - 1);\n num2 = primes.get(i);\n }\n }\n\n return new int[] {num1, num2};\n }\n\n private boolean[] sieveEratosthenes(int n) {\n boolean[] isPrime = new boolean[n];\n Arrays.fill(isPrime, true);\n isPrime[0] = false;\n isPrime[1] = false;\n for (int i = 2; i * i < n; ++i)\n if (isPrime[i])\n for (int j = i * i; j < n; j += i)\n isPrime[j] = false;\n return isPrime;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector closestPrimes(int left, int right) {\n const vector isPrime = sieveEratosthenes(right + 1);\n vector primes;\n\n for (int i = left; i <= right; ++i)\n if (isPrime[i])\n primes.push_back(i);\n\n if (primes.size() < 2)\n return {-1, -1};\n\n int minDiff = INT_MAX;\n int num1 = -1;\n int num2 = -1;\n\n for (int i = 1; i < primes.size(); ++i) {\n const int diff = primes[i] - primes[i - 1];\n if (diff < minDiff) {\n minDiff = diff;\n num1 = primes[i - 1];\n num2 = primes[i];\n }\n }\n\n return {num1, num2};\n }\n\n private:\n vector sieveEratosthenes(int n) {\n vector isPrime(n, true);\n isPrime[0] = false;\n isPrime[1] = false;\n for (int i = 2; i * i < n; ++i)\n if (isPrime[i])\n for (int j = i * i; j < n; j += i)\n isPrime[j] = false;\n return isPrime;\n }\n};\n"} +{"task_num": 2532, "task_title": "Time to Cross a Bridge", "difficulty": 3, "func_name": "findCrossingTime", "description": "There are `k` workers who want to move `n` boxes from an old warehouse to a\nnew one. You are given the two integers `n` and `k`, and a 2D integer array\n`time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti,\nputNewi]`.\n\nThe warehouses are separated by a river and connected by a bridge. The old\nwarehouse is on the right bank of the river, and the new warehouse is on the\nleft bank of the river. Initially, all `k` workers are waiting on the left\nside of the bridge. To move the boxes, the `ith` worker (0-indexed) can :\n\n* Cross the bridge from the left bank (new warehouse) to the right bank (old warehouse) in `leftToRighti` minutes.\n* Pick a box from the old warehouse and return to the bridge in `pickOldi` minutes. Different workers can pick up their boxes simultaneously.\n* Cross the bridge from the right bank (old warehouse) to the left bank (new warehouse) in `rightToLefti` minutes.\n* Put the box in the new warehouse and return to the bridge in `putNewi` minutes. Different workers can put their boxes simultaneously.\n\nA worker `i` is less efficient than a worker `j` if either condition is met:\n\n* `leftToRighti + rightToLefti > leftToRightj + rightToLeftj`\n* `leftToRighti + rightToLefti == leftToRightj + rightToLeftj` and `i > j`\n\nThe following rules regulate the movement of the workers through the bridge :\n\n* If a worker `x` reaches the bridge while another worker `y` is crossing the bridge, `x` waits at their side of the bridge.\n* If the bridge is free, the worker waiting on the right side of the bridge gets to cross the bridge. If more than one worker is waiting on the right side, the one with the lowest efficiency crosses first.\n* If the bridge is free and no worker is waiting on the right side, and at least one box remains at the old warehouse, the worker on the left side of the river gets to cross the bridge. If more than one worker is waiting on the left side, the one with the lowest efficiency crosses first.\n\nReturn the instance of time at which the last worker reaches the left bank of\nthe river after all n boxes have been put in the new warehouse.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def findCrossingTime(self, n: int, k: int, time: List[List[int]]) -> int:\n ans = 0\n leftBridgeQueue = [(-leftToRight - rightToLeft, -i) for i, (leftToRight, pickOld, rightToLeft, pickNew) in enumerate(time)]\n rightBridgeQueue = []\n leftWorkers = []\n rightWorkers = []\n\n heapq.heapify(leftBridgeQueue)\n\n while n > 0 or rightBridgeQueue or rightWorkers:\n while leftWorkers and leftWorkers[0][0] <= ans:\n i = heapq.heappop(leftWorkers)[1]\n heapq.heappush(leftBridgeQueue, (-time[i][0] - time[i][2], -i))\n while rightWorkers and rightWorkers[0][0] <= ans:\n i = heapq.heappop(rightWorkers)[1]\n heapq.heappush(rightBridgeQueue, (-time[i][0] - time[i][2], -i))\n if rightBridgeQueue:\n i = -heapq.heappop(rightBridgeQueue)[1]\n ans += time[i][2]\n heapq.heappush(leftWorkers, (ans + time[i][3], i))\n elif leftBridgeQueue and n > 0:\n i = -heapq.heappop(leftBridgeQueue)[1]\n ans += time[i][0]\n heapq.heappush(rightWorkers, (ans + time[i][1], i))\n n -= 1\n else:\n if leftWorkers and n > 0:\n ans1=leftWorkers[0][0]\n else:\n ans1=math.inf\n if rightWorkers:\n ans2=rightWorkers[0][0]\n else:\n ans2=math.inf\n ans=min(ans1,ans2)\n\n return ans", "java_solution": "class Solution {\n public int findCrossingTime(int n, int k, int[][] time) {\n int ans = 0;\n // (leftToRight + rightToLeft, i)\n Queue> leftBridgeQueue = createMaxHeap();\n Queue> rightBridgeQueue = createMaxHeap();\n // (time to be idle, i)\n Queue> leftWorkers = createMinHeap();\n Queue> rightWorkers = createMinHeap();\n\n for (int i = 0; i < k; ++i)\n leftBridgeQueue.offer(new Pair<>(\n /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i));\n\n while (n > 0 || !rightBridgeQueue.isEmpty() || !rightWorkers.isEmpty()) {\n // Idle left workers get on the left bridge.\n while (!leftWorkers.isEmpty() && leftWorkers.peek().getKey() <= ans) {\n final int i = leftWorkers.poll().getValue();\n leftBridgeQueue.offer(new Pair<>(\n /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i));\n }\n // Idle right workers get on the right bridge.\n while (!rightWorkers.isEmpty() && rightWorkers.peek().getKey() <= ans) {\n final int i = rightWorkers.poll().getValue();\n rightBridgeQueue.offer(new Pair<>(\n /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i));\n }\n\n if (!rightBridgeQueue.isEmpty()) {\n // If the bridge is free, the worker waiting on the right side of the\n // bridge gets to cross the bridge. If more than one worker is waiting\n // on the right side, the one with the lowest efficiency crosses first.\n final int i = rightBridgeQueue.poll().getValue();\n ans += /*rightToLeft*/ time[i][2];\n leftWorkers.offer(new Pair<>(ans + /*putNew*/ time[i][3], i));\n } else if (!leftBridgeQueue.isEmpty() && n > 0) {\n // If the bridge is free and no worker is waiting on the right side, and\n // at least one box remains at the old warehouse, the worker on the left\n // side of the river gets to cross the bridge. If more than one worker\n // is waiting on the left side, the one with the lowest efficiency\n // crosses first.\n final int i = leftBridgeQueue.poll().getValue();\n ans += /*leftToRight*/ time[i][0];\n rightWorkers.offer(new Pair<>(ans + /*pickOld*/ time[i][1], i));\n --n;\n } else {\n // Advance the time of the last crossing worker.\n ans = Math.min(!leftWorkers.isEmpty() && n > 0 ? leftWorkers.peek().getKey()\n : Integer.MAX_VALUE,\n !rightWorkers.isEmpty() ? rightWorkers.peek().getKey() : Integer.MAX_VALUE);\n }\n }\n\n return ans;\n }\n\n private Queue> createMaxHeap() {\n return new PriorityQueue<>(\n Comparator.comparing(Pair::getKey, Comparator.reverseOrder())\n .thenComparing(Pair::getValue, Comparator.reverseOrder()));\n }\n\n private Queue> createMinHeap() {\n return new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)\n .thenComparingInt(Pair::getValue));\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int findCrossingTime(int n, int k, vector>& time) {\n int ans = 0;\n using P = pair;\n // (leftToRight + rightToLeft, i)\n priority_queue

leftBridgeQueue;\n priority_queue

rightBridgeQueue;\n // (time to be idle, i)\n priority_queue, greater<>> leftWorkers;\n priority_queue, greater<>> rightWorkers;\n\n for (int i = 0; i < k; ++i)\n leftBridgeQueue.emplace(\n /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i);\n\n while (n > 0 || !rightBridgeQueue.empty() || !rightWorkers.empty()) {\n // Idle left workers get on the left bridge.\n while (!leftWorkers.empty() && leftWorkers.top().first <= ans) {\n const int i = leftWorkers.top().second;\n leftWorkers.pop();\n leftBridgeQueue.emplace(\n /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i);\n }\n // Idle right workers get on the right bridge.\n while (!rightWorkers.empty() && rightWorkers.top().first <= ans) {\n const int i = rightWorkers.top().second;\n rightWorkers.pop();\n rightBridgeQueue.emplace(\n /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i);\n }\n\n if (!rightBridgeQueue.empty()) {\n // If the bridge is free, the worker waiting on the right side of the\n // bridge gets to cross the bridge. If more than one worker is waiting\n // on the right side, the one with the lowest efficiency crosses first.\n const int i = rightBridgeQueue.top().second;\n rightBridgeQueue.pop();\n ans += /*rightToLeft*/ time[i][2];\n leftWorkers.emplace(ans + /*putNew*/ time[i][3], i);\n } else if (!leftBridgeQueue.empty() && n > 0) {\n // If the bridge is free and no worker is waiting on the right side, and\n // at least one box remains at the old warehouse, the worker on the left\n // side of the river gets to cross the bridge. If more than one worker\n // is waiting on the left side, the one with the lowest efficiency\n // crosses first.\n const int i = leftBridgeQueue.top().second;\n leftBridgeQueue.pop();\n ans += /*leftToRight*/ time[i][0];\n rightWorkers.emplace(ans + /*pickOld*/ time[i][1], i);\n --n;\n } else {\n // Advance the time of the last crossing worker.\n ans = min(\n !leftWorkers.empty() && n > 0 ? leftWorkers.top().first : INT_MAX,\n !rightWorkers.empty() ? rightWorkers.top().first : INT_MAX);\n }\n }\n\n return ans;\n }\n};\n"} +{"task_num": 2577, "task_title": "Minimum Time to Visit a Cell In a Grid", "difficulty": 3, "func_name": "minimumTime", "description": "You are given a `m x n` matrix `grid` consisting of non-negative integers\nwhere `grid[row][col]` represents the minimum time required to be able to\nvisit the cell `(row, col)`, which means you can visit the cell `(row, col)`\nonly when the time you visit it is greater than or equal to `grid[row][col]`.\n\nYou are standing in the top-left cell of the matrix in the `0th` second, and\nyou must move to any adjacent cell in the four directions: up, down, left, and\nright. Each move you make takes 1 second.\n\nReturn the minimum time required in which you can visit the bottom-right cell\nof the matrix. If you cannot visit the bottom-right cell, then return `-1`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumTime(self, grid: List[List[int]]) -> int:\n if grid[0][1] > 1 and grid[1][0] > 1:\n return -1\n\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n m = len(grid)\n n = len(grid[0])\n minHeap = [(0, 0, 0)]\n seen = {(0, 0)}\n\n while minHeap:\n time, i, j = heapq.heappop(minHeap)\n if i == m - 1 and j == n - 1:\n return time\n for dx, dy in dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == m or y < 0 or y == n:\n continue\n if (x, y) in seen:\n continue\n if (grid[x][y] - time) % 2 == 0:\n extraWait = 1\n else:\n extraWait = 0\n nextTime = max(time + 1, grid[x][y] + extraWait)\n heapq.heappush(minHeap, (nextTime, x, y))\n seen.add((x, y))\n", "java_solution": "class Solution {\n public int minimumTime(int[][] grid) {\n if (grid[0][1] > 1 && grid[1][0] > 1)\n return -1;\n\n final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n final int m = grid.length;\n final int n = grid[0].length;\n Queue minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) {\n { offer(new int[] {0, 0, 0}); } // (time, i, j)\n };\n boolean[][] seen = new boolean[m][n];\n seen[0][0] = true;\n\n while (!minHeap.isEmpty()) {\n final int time = minHeap.peek()[0];\n final int i = minHeap.peek()[1];\n final int j = minHeap.poll()[2];\n if (i == m - 1 && j == n - 1)\n return time;\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n final int extraWait = (grid[x][y] - time) % 2 == 0 ? 1 : 0;\n final int nextTime = Math.max(time + 1, grid[x][y] + extraWait);\n minHeap.offer(new int[] {nextTime, x, y});\n seen[x][y] = true;\n }\n }\n\n throw new IllegalArgumentException();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minimumTime(vector>& grid) {\n if (grid[0][1] > 1 && grid[1][0] > 1)\n return -1;\n\n constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n const int m = grid.size();\n const int n = grid[0].size();\n using T = tuple; // (time, i, j)\n priority_queue, greater<>> minHeap;\n vector> seen(m, vector(n));\n\n minHeap.emplace(0, 0, 0);\n seen[0][0] = true;\n\n while (!minHeap.empty()) {\n const auto [time, i, j] = minHeap.top();\n minHeap.pop();\n if (i == m - 1 && j == n - 1)\n return time;\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == m || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n const int extraWait = (grid[x][y] - time) % 2 == 0 ? 1 : 0;\n const int nextTime = max(time + 1, grid[x][y] + extraWait);\n minHeap.emplace(nextTime, x, y);\n seen[x][y] = true;\n }\n }\n\n throw;\n }\n};\n"} +{"task_num": 2601, "task_title": "Prime Subtraction Operation", "difficulty": 2, "func_name": "primeSubOperation", "description": "You are given a 0-indexed integer array `nums` of length `n`.\n\nYou can perform the following operation as many times as you want:\n\n* Pick an index `i` that you haven\u2019t picked before, and pick a prime `p` strictly less than `nums[i]`, then subtract `p` from `nums[i]`.\n\nReturn true if you can make `nums` a strictly increasing array using the above\noperation and false otherwise.\n\nA strictly increasing array is an array whose each element is strictly greater\nthan its preceding element.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def primeSubOperation(self, nums: List[int]) -> bool:\n kMax = 1000\n primes = self._sieveEratosthenes(kMax)\n\n prevNum = 0\n for num in nums:\n i = bisect.bisect_left(primes, num - prevNum)\n if i > 0:\n num -= primes[i - 1]\n if num <= prevNum:\n return False\n prevNum = num\n\n return True\n\n def _sieveEratosthenes(self, n: int) -> List[int]:\n isPrime = [True] * n\n isPrime[0] = False\n isPrime[1] = False\n for i in range(2, int(n**0.5) + 1):\n if isPrime[i]:\n for j in range(i * i, n, i):\n isPrime[j] = False\n return [i for i in range(n) if isPrime[i]]\n", "java_solution": "class Solution {\n public boolean primeSubOperation(int[] nums) {\n final int MAX = 1000;\n final List primes = sieveEratosthenes(MAX);\n\n int prevNum = 0;\n for (int num : nums) {\n // Make nums[i] the smallest as possible and still > nums[i - 1].\n final int i = firstGreaterEqual(primes, num - prevNum);\n if (i > 0)\n num -= primes.get(i - 1);\n if (num <= prevNum)\n return false;\n prevNum = num;\n }\n\n return true;\n }\n\n private List sieveEratosthenes(int n) {\n List primes = new ArrayList<>();\n boolean[] isPrime = new boolean[n];\n Arrays.fill(isPrime, true);\n isPrime[0] = false;\n isPrime[1] = false;\n for (int i = 2; i * i < n; ++i)\n if (isPrime[i])\n for (int j = i * i; j < n; j += i)\n isPrime[j] = false;\n for (int i = 2; i < n; ++i)\n if (isPrime[i])\n primes.add(i);\n return primes;\n }\n\n private int firstGreaterEqual(List A, int target) {\n final int i = Collections.binarySearch(A, target);\n return i < 0 ? -i - 1 : i;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n bool primeSubOperation(vector& nums) {\n constexpr int kMax = 1000;\n const vector primes = sieveEratosthenes(kMax);\n\n int prevNum = 0;\n for (int num : nums) {\n // Make nums[i] the smallest as possible and still > nums[i - 1].\n const auto it = ranges::lower_bound(primes, num - prevNum);\n if (it != primes.begin())\n num -= *prev(it);\n if (num <= prevNum)\n return false;\n prevNum = num;\n }\n\n return true;\n }\n\n vector sieveEratosthenes(int n) {\n vector primes;\n vector isPrime(n, true);\n isPrime[0] = false;\n isPrime[1] = false;\n for (int i = 2; i * i < n; ++i)\n if (isPrime[i])\n for (int j = i * i; j < n; j += i)\n isPrime[j] = false;\n for (int i = 2; i < n; ++i)\n if (isPrime[i])\n primes.push_back(i);\n return primes;\n }\n};\n"} +{"task_num": 2603, "task_title": "Collect Coins in a Tree", "difficulty": 3, "func_name": "collectTheCoins", "description": "There exists an undirected and unrooted tree with `n` nodes indexed from `0`\nto `n - 1`. You are given an integer `n` and a 2D integer array edges of\nlength `n - 1`, where `edges[i] = [ai, bi]` indicates that there is an edge\nbetween nodes `ai` and `bi` in the tree. You are also given an array `coins`\nof size `n` where `coins[i]` can be either `0` or `1`, where `1` indicates the\npresence of a coin in the vertex `i`.\n\nInitially, you choose to start at any vertex in the tree. Then, you can\nperform the following operations any number of times:\n\n* Collect all the coins that are at a distance of at most `2` from the current vertex, or\n* Move to any adjacent vertex in the tree.\n\nFind the minimum number of edges you need to go through to collect all the\ncoins and go back to the initial vertex.\n\nNote that if you pass an edge several times, you need to count it into the\nanswer several times.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def collectTheCoins(self, coins: List[int], edges: List[List[int]]) -> int:\n n = len(coins)\n tree = [set() for _ in range(n)]\n leavesToBeRemoved = collections.deque()\n\n for u, v in edges:\n tree[u].add(v)\n tree[v].add(u)\n\n for u in range(n):\n while len(tree[u]) == 1 and coins[u] == 0:\n v = tree[u].pop()\n tree[v].remove(u)\n u = v\n if len(tree[u]) == 1:\n leavesToBeRemoved.append(u)\n\n for _ in range(2):\n for _ in range(len(leavesToBeRemoved)):\n u = leavesToBeRemoved.popleft()\n if tree[u]:\n v = tree[u].pop()\n tree[v].remove(u)\n if len(tree[v]) == 1:\n leavesToBeRemoved.append(v)\n\n return sum(len(children) for children in tree)\n", "java_solution": "class Solution {\n public int collectTheCoins(int[] coins, int[][] edges) {\n final int n = coins.length;\n Set[] tree = new Set[n];\n Deque leavesToBeRemoved = new ArrayDeque<>();\n\n for (int i = 0; i < n; ++i)\n tree[i] = new HashSet<>();\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n tree[u].add(v);\n tree[v].add(u);\n }\n\n for (int i = 0; i < n; ++i) {\n int u = i;\n // Remove the leaves that don't have coins.\n while (tree[u].size() == 1 && coins[u] == 0) {\n final int v = tree[u].iterator().next();\n tree[u].clear();\n tree[v].remove(u);\n u = v; // Walk up to its parent.\n }\n // After trimming leaves without coins, leaves with coins may satisfy\n // `leavesToBeRemoved`.\n if (tree[u].size() == 1)\n leavesToBeRemoved.offer(u);\n }\n\n // Remove each remaining leaf node and its parent. The remaining nodes are\n // the ones that must be visited.\n for (int i = 0; i < 2; ++i)\n for (int sz = leavesToBeRemoved.size(); sz > 0; --sz) {\n final int u = leavesToBeRemoved.poll();\n if (!tree[u].isEmpty()) {\n final int v = tree[u].iterator().next();\n tree[u].clear();\n tree[v].remove(u);\n if (tree[v].size() == 1)\n leavesToBeRemoved.offer(v);\n }\n }\n\n return Arrays.stream(tree).mapToInt(children -> children.size()).sum();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int collectTheCoins(vector& coins, vector>& edges) {\n const int n = coins.size();\n vector> tree(n);\n queue leavesToBeRemoved;\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n tree[u].insert(v);\n tree[v].insert(u);\n }\n\n for (int i = 0; i < n; ++i) {\n int u = i;\n // Remove the leaves that don't have coins.\n while (tree[u].size() == 1 && coins[u] == 0) {\n const int v = *tree[u].begin();\n tree[u].clear();\n tree[v].erase(u);\n u = v; // Walk up to its parent.\n }\n // After trimming leaves without coins, leaves with coins may satisfy\n // `leavesToBeRemoved`.\n if (tree[u].size() == 1)\n leavesToBeRemoved.push(u);\n }\n\n // Remove each remaining leaf node and its parent. The remaining nodes are\n // the ones that must be visited.\n for (int i = 0; i < 2; ++i)\n for (int sz = leavesToBeRemoved.size(); sz > 0; --sz) {\n const int u = leavesToBeRemoved.front();\n leavesToBeRemoved.pop();\n if (!tree[u].empty()) {\n const int v = *tree[u].begin();\n tree[u].clear();\n tree[v].erase(u);\n if (tree[v].size() == 1)\n leavesToBeRemoved.push(v);\n }\n }\n\n return accumulate(tree.begin(), tree.end(), 0,\n [](int acc, const unordered_set& children) {\n return acc + children.size();\n });\n }\n};\n"} +{"task_num": 2653, "task_title": "Sliding Subarray Beauty", "difficulty": 2, "func_name": "getSubarrayBeauty", "description": "Given an integer array `nums` containing `n` integers, find the beauty of each\nsubarray of size `k`.\n\nThe beauty of a subarray is the `xth` smallest integer in the subarray if it\nis negative, or `0` if there are fewer than `x` negative integers.\n\nReturn an integer array containing `n - k + 1` integers, which denote the\nbeauty of the subarrays in order from the first index in the array.\n\n* A subarray is a contiguous non-empty sequence of elements within an array.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def getSubarrayBeauty(self, nums: List[int], k: int, x: int) -> List[int]:\n ans = []\n count = [0] * 50\n\n for i, num in enumerate(nums):\n if num < 0:\n count[num + 50] += 1\n if i - k >= 0 and nums[i - k] < 0:\n count[nums[i - k] + 50] -= 1\n if i + 1 >= k:\n ans.append(self._getXthSmallestNum(count, x))\n\n return ans\n\n def _getXthSmallestNum(self, count: List[int], x: int) -> int:\n prefix = 0\n for i in range(50):\n prefix += count[i]\n if prefix >= x:\n return i - 50\n return 0\n", "java_solution": "class Solution {\n public int[] getSubarrayBeauty(int[] nums, int k, int x) {\n int[] ans = new int[nums.length - k + 1];\n int[] count = new int[50]; // count[i] := the frequency of (i + 50)\n\n for (int i = 0; i < nums.length; ++i) {\n if (nums[i] < 0)\n ++count[nums[i] + 50];\n if (i - k >= 0 && nums[i - k] < 0)\n --count[nums[i - k] + 50];\n if (i + 1 >= k)\n ans[i - k + 1] = getXthSmallestNum(count, x);\n }\n\n return ans;\n }\n\n private int getXthSmallestNum(int[] count, int x) {\n int prefix = 0;\n for (int i = 0; i < 50; ++i) {\n prefix += count[i];\n if (prefix >= x)\n return i - 50;\n }\n return 0;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector getSubarrayBeauty(vector& nums, int k, int x) {\n vector ans;\n vector count(50); // count[i] := the frequency of (i + 50)\n\n for (int i = 0; i < nums.size(); ++i) {\n if (nums[i] < 0)\n ++count[nums[i] + 50];\n if (i - k >= 0 && nums[i - k] < 0)\n --count[nums[i - k] + 50];\n if (i + 1 >= k)\n ans.push_back(getXthSmallestNum(count, x));\n }\n\n return ans;\n }\n\n private:\n int getXthSmallestNum(const vector& count, int x) {\n int prefix = 0;\n for (int i = 0; i < 50; ++i) {\n prefix += count[i];\n if (prefix >= x)\n return i - 50;\n }\n return 0;\n }\n};\n"} +{"task_num": 2662, "task_title": "Minimum Cost of a Path With Special Roads", "difficulty": 2, "func_name": "minimumCost", "description": "You are given an array `start` where `start = [startX, startY]` represents\nyour initial position `(startX, startY)` in a 2D space. You are also given the\narray `target` where `target = [targetX, targetY]` represents your target\nposition `(targetX, targetY)`.\n\nThe cost of going from a position `(x1, y1)` to any other position in the\nspace `(x2, y2)` is `|x2 - x1| + |y2 - y1|`.\n\nThere are also some special roads. You are given a 2D array `specialRoads`\nwhere `specialRoads[i] = [x1i, y1i, x2i, y2i, costi]` indicates that the `ith`\nspecial road can take you from `(x1i, y1i)` to `(x2i, y2i)` with a cost equal\nto `costi`. You can use each special road any number of times.\n\nReturn the minimum cost required to go from `(startX, startY)` to `(targetX,\ntargetY)`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumCost(self, start: List[int], target: List[int], specialRoads: List[List[int]]) -> int:\n return self.dijkstra(specialRoads, *start, *target)\n\n def dijkstra(self, specialRoads: List[List[int]], srcX: int, srcY: int, dstX: int, dstY: int) -> int:\n n = len(specialRoads)\n dist = [math.inf] * n\n minHeap = []\n\n for u, (x1, y1, _, _, cost) in enumerate(specialRoads):\n d = abs(x1 - srcX) + abs(y1 - srcY) + cost\n dist[u] = d\n heapq.heappush(minHeap, (dist[u], u))\n\n while minHeap:\n d, u = heapq.heappop(minHeap)\n if d > dist[u]:\n continue\n _, _, ux2, uy2, _ = specialRoads[u]\n for v in range(n):\n if v == u:\n continue\n vx1, vy1, _, _, vcost = specialRoads[v]\n newDist = d + abs(vx1 - ux2) + abs(vy1 - uy2) + vcost\n if newDist < dist[v]:\n dist[v] = newDist\n heapq.heappush(minHeap, (dist[v], v))\n\n ans = abs(dstX - srcX) + abs(dstY - srcY)\n for u in range(n):\n _, _, x2, y2, _ = specialRoads[u]\n ans = min(ans, dist[u] + abs(dstX - x2) + abs(dstY - y2))\n\n return ans\n", "java_solution": "class Solution {\n public int minimumCost(int[] start, int[] target, int[][] specialRoads) {\n return dijkstra(specialRoads, start[0], start[1], target[0], target[1]);\n }\n\n private int dijkstra(int[][] specialRoads, int srcX, int srcY, int dstX, int dstY) {\n final int n = specialRoads.length;\n // dist[i] := the minimum distance of (srcX, srcY) to\n // specialRoads[i](x2, y2)\n int[] dist = new int[n];\n Arrays.fill(dist, Integer.MAX_VALUE);\n // (d, u), where u := the i-th specialRoads\n Queue> minHeap =\n new PriorityQueue<>(Comparator.comparingInt(Pair::getKey));\n\n // (srcX, srcY) -> (x1, y1) to cost -> (x2, y2)\n for (int u = 0; u < n; ++u) {\n final int x1 = specialRoads[u][0];\n final int y1 = specialRoads[u][1];\n final int cost = specialRoads[u][4];\n final int d = Math.abs(x1 - srcX) + Math.abs(y1 - srcY) + cost;\n dist[u] = d;\n minHeap.offer(new Pair<>(dist[u], u));\n }\n\n while (!minHeap.isEmpty()) {\n final int d = minHeap.peek().getKey();\n final int u = minHeap.poll().getValue();\n if (d > dist[u])\n continue;\n final int ux2 = specialRoads[u][2];\n final int uy2 = specialRoads[u][3];\n for (int v = 0; v < n; ++v) {\n if (v == u)\n continue;\n final int vx1 = specialRoads[v][0];\n final int vy1 = specialRoads[v][1];\n final int vcost = specialRoads[v][4];\n // (ux2, uy2) -> (vx1, vy1) to vcost -> (vx2, vy2)\n final int newDist = d + Math.abs(vx1 - ux2) + Math.abs(vy1 - uy2) + vcost;\n if (newDist < dist[v]) {\n dist[v] = newDist;\n minHeap.offer(new Pair<>(dist[v], v));\n }\n }\n }\n\n int ans = Math.abs(dstX - srcX) + Math.abs(dstY - srcY);\n for (int u = 0; u < n; ++u) {\n final int x2 = specialRoads[u][2];\n final int y2 = specialRoads[u][3];\n // (srcX, srcY) -> (x2, y2) -> (dstX, dstY).\n ans = Math.min(ans, dist[u] + Math.abs(dstX - x2) + Math.abs(dstY - y2));\n }\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minimumCost(vector& start, vector& target,\n vector>& specialRoads) {\n return dijkstra(specialRoads, start[0], start[1], target[0], target[1]);\n }\n\n private:\n int dijkstra(const vector>& specialRoads, int srcX, int srcY,\n int dstX, int dstY) {\n const int n = specialRoads.size();\n // dist[i] := the minimum distance of (srcX, srcY) to\n // specialRoads[i](x2, y2)\n vector dist(specialRoads.size(), INT_MAX);\n using P = pair; // (d, u), where u := the i-th specialRoads\n priority_queue, greater<>> minHeap;\n\n // (srcX, srcY) -> (x1, y1) to cost -> (x2, y2)\n for (int u = 0; u < n; ++u) {\n const int x1 = specialRoads[u][0];\n const int y1 = specialRoads[u][1];\n const int cost = specialRoads[u][4];\n const int d = abs(x1 - srcX) + abs(y1 - srcY) + cost;\n dist[u] = d;\n minHeap.emplace(dist[u], u);\n }\n\n while (!minHeap.empty()) {\n const auto [d, u] = minHeap.top();\n minHeap.pop();\n if (d > dist[u])\n continue;\n const int ux2 = specialRoads[u][2];\n const int uy2 = specialRoads[u][3];\n for (int v = 0; v < n; ++v) {\n if (v == u)\n continue;\n const int vx1 = specialRoads[v][0];\n const int vy1 = specialRoads[v][1];\n const int vcost = specialRoads[v][4];\n // (ux2, uy2) -> (vx1, vy1) to vcost -> (vx2, vy2)\n const int newDist = d + abs(vx1 - ux2) + abs(vy1 - uy2) + vcost;\n if (newDist < dist[v]) {\n dist[v] = newDist;\n minHeap.emplace(dist[v], v);\n }\n }\n }\n\n int ans = abs(dstX - srcX) + abs(dstY - srcY);\n for (int u = 0; u < n; ++u) {\n const int x2 = specialRoads[u][2];\n const int y2 = specialRoads[u][3];\n // (srcX, srcY) -> (x2, y2) -> (dstX, dstY).\n ans = min(ans, dist[u] + abs(dstX - x2) + abs(dstY - y2));\n }\n return ans;\n }\n};\n"} +{"task_num": 2663, "task_title": "Lexicographically Smallest Beautiful String", "difficulty": 3, "func_name": "smallestBeautifulString", "description": "A string is beautiful if:\n\n* It consists of the first `k` letters of the English lowercase alphabet.\n* It does not contain any substring of length `2` or more which is a palindrome.\n\nYou are given a beautiful string `s` of length `n` and a positive integer `k`.\n\nReturn the lexicographically smallest string of length `n`, which is larger\nthan `s` and is beautiful. If there is no such string, return an empty string.\n\nA string `a` is lexicographically larger than a string `b` (of the same\nlength) if in the first position where `a` and `b` differ, `a` has a character\nstrictly larger than the corresponding character in `b`.\n\n* For example, `\"abcd\"` is lexicographically larger than `\"abcc\"` because the first position they differ is at the fourth character, and `d` is greater than `c`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def smallestBeautifulString(self, s: str, k: int) -> str:\n chars = list(s)\n\n for i in reversed(range(len(chars))):\n chars[i] = chr(ord(chars[i]) + 1)\n while self._containsPalindrome(chars, i):\n chars[i] = chr(ord(chars[i]) + 1)\n if chars[i] < chr(ord('a') + k):\n return self._changeSuffix(chars, i + 1)\n\n return ''\n\n def _containsPalindrome(self, chars: List[str], i: int) -> bool:\n return (i > 0 and chars[i] == chars[i - 1]) or (i > 1 and chars[i] == chars[i - 2])\n\n def _changeSuffix(self, chars: List[str], i: int) -> str:\n for j in range(i, len(chars)):\n chars[j] = 'a'\n while self._containsPalindrome(chars, j):\n chars[j] = chr(ord(chars[j]) + 1)\n return ''.join(chars)\n", "java_solution": "class Solution {\n public String smallestBeautifulString(String s, int k) {\n StringBuilder sb = new StringBuilder(s);\n\n for (int i = s.length() - 1; i >= 0; --i) {\n do {\n sb.setCharAt(i, (char) (sb.charAt(i) + 1));\n } while (containsPalindrome(sb, i));\n if (sb.charAt(i) < 'a' + k)\n // If sb[i] is among the first k letters, then change the letters after\n // sb[i] to the smallest ones that don't form any palindrome substring.\n return changeSuffix(sb, i + 1);\n }\n\n return \"\";\n }\n\n // Returns true if sb[0..i] contains any palindrome.\n private boolean containsPalindrome(StringBuilder sb, int i) {\n return (i > 0 && sb.charAt(i) == sb.charAt(i - 1)) ||\n (i > 1 && sb.charAt(i) == sb.charAt(i - 2));\n }\n\n // Returns a string, where replacing sb[i..n) with the smallest possible\n // letters don't form any palindrome substring.\n private String changeSuffix(StringBuilder sb, int i) {\n for (int j = i; j < sb.length(); ++j)\n for (sb.setCharAt(j, 'a'); containsPalindrome(sb, j);\n sb.setCharAt(j, (char) (sb.charAt(j) + 1)))\n ;\n return sb.toString();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n string smallestBeautifulString(string s, int k) {\n for (int i = s.length() - 1; i >= 0; --i) {\n do {\n ++s[i];\n } while (containsPalindrome(s, i));\n if (s[i] < 'a' + k)\n // If s[i] is among the first k letters, then change the letters after\n // s[i] to the smallest ones that don't form any palindrome substring.\n return changeSuffix(s, i + 1);\n }\n\n return \"\";\n }\n\n private:\n // Returns true if s[0..i] contains any palindrome.\n bool containsPalindrome(const string& s, int i) {\n return (i > 0 && s[i] == s[i - 1]) || (i > 1 && s[i] == s[i - 2]);\n }\n\n // Returns a string, where replacing s[i..n) with the smallest possible\n // letters don't form any palindrome substring.\n string changeSuffix(string& s, int i) {\n for (int j = i; j < s.length(); ++j)\n for (s[j] = 'a'; containsPalindrome(s, j); ++s[j])\n ;\n return s;\n }\n};\n"} +{"task_num": 2672, "task_title": "Number of Adjacent Elements With the Same Color", "difficulty": 2, "func_name": "colorTheArray", "description": "There is a 0-indexed array `nums` of length `n`. Initially, all elements are\nuncolored (has a value of `0`).\n\nYou are given a 2D integer array `queries` where `queries[i] = [indexi,\ncolori]`.\n\nFor each query, you color the index `indexi` with the color `colori` in the\narray `nums`.\n\nReturn an array `answer` of the same length as `queries` where `answer[i]` is\nthe number of adjacent elements with the same color after the `ith` query.\n\nMore formally, `answer[i]` is the number of indices `j`, such that `0 <= j < n\n- 1` and `nums[j] == nums[j + 1]` and `nums[j] != 0` after the `ith` query.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def colorTheArray(self, n: int, queries: List[List[int]]) -> List[int]:\n ans = []\n arr = [0] * n\n sameColors = 0\n\n for i, color in queries:\n if i + 1 < n:\n if arr[i + 1] > 0 and arr[i + 1] == arr[i]:\n sameColors -= 1\n if arr[i + 1] == color:\n sameColors += 1\n if i > 0:\n if arr[i - 1] > 0 and arr[i - 1] == arr[i]:\n sameColors -= 1\n if arr[i - 1] == color:\n sameColors += 1\n arr[i] = color\n ans.append(sameColors)\n\n return ans\n", "java_solution": "class Solution {\n public int[] colorTheArray(int n, int[][] queries) {\n int[] ans = new int[queries.length];\n int[] arr = new int[n];\n int sameColors = 0;\n\n for (int i = 0; i < queries.length; ++i) {\n final int j = queries[i][0];\n final int color = queries[i][1];\n if (j + 1 < n) {\n if (arr[j + 1] > 0 && arr[j + 1] == arr[j])\n --sameColors;\n if (arr[j + 1] == color)\n ++sameColors;\n }\n if (j > 0) {\n if (arr[j - 1] > 0 && arr[j - 1] == arr[j])\n --sameColors;\n if (arr[j - 1] == color)\n ++sameColors;\n }\n arr[j] = color;\n ans[i] = sameColors;\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector colorTheArray(int n, vector>& queries) {\n vector ans;\n vector arr(n);\n int sameColors = 0;\n\n for (const vector& query : queries) {\n const int i = query[0];\n const int color = query[1];\n if (i + 1 < n) {\n if (arr[i + 1] > 0 && arr[i + 1] == arr[i])\n --sameColors;\n if (arr[i + 1] == color)\n ++sameColors;\n }\n if (i > 0) {\n if (arr[i - 1] > 0 && arr[i - 1] == arr[i])\n --sameColors;\n if (arr[i - 1] == color)\n ++sameColors;\n }\n arr[i] = color;\n ans.push_back(sameColors);\n }\n\n return ans;\n }\n};\n"} +{"task_num": 2684, "task_title": "Maximum Number of Moves in a Grid", "difficulty": 2, "func_name": "maxMoves", "description": "You are given a 0-indexed `m x n` matrix `grid` consisting of positive\nintegers.\n\nYou can start at any cell in the first column of the matrix, and traverse the\ngrid in the following way:\n\n* From a cell `(row, col)`, you can move to any of the cells: `(row - 1, col + 1)`, `(row, col + 1)` and `(row + 1, col + 1)` such that the value of the cell you move to, should be strictly bigger than the value of the current cell.\n\nReturn the maximum number of moves that you can perform.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def maxMoves(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n dp = [[0] * n for _ in range(m)]\n\n for j in range(n - 2, -1, -1):\n for i in range(m):\n if grid[i][j + 1] > grid[i][j]:\n dp[i][j] = 1 + dp[i][j + 1]\n if i > 0 and grid[i - 1][j + 1] > grid[i][j]:\n dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j + 1])\n if i + 1 < m and grid[i + 1][j + 1] > grid[i][j]:\n dp[i][j] = max(dp[i][j], 1 + dp[i + 1][j + 1])\n\n return max(dp[i][0] for i in range(m))\n", "java_solution": "class Solution {\n public int maxMoves(int[][] grid) {\n final int m = grid.length;\n final int n = grid[0].length;\n int ans = 0;\n // dp[i][j] := the maximum number of moves you can perform from (i, j)\n int[][] dp = new int[m][n];\n\n for (int j = n - 2; j >= 0; --j)\n for (int i = 0; i < m; ++i) {\n if (grid[i][j + 1] > grid[i][j])\n dp[i][j] = 1 + dp[i][j + 1];\n if (i > 0 && grid[i - 1][j + 1] > grid[i][j])\n dp[i][j] = Math.max(dp[i][j], 1 + dp[i - 1][j + 1]);\n if (i + 1 < m && grid[i + 1][j + 1] > grid[i][j])\n dp[i][j] = Math.max(dp[i][j], 1 + dp[i + 1][j + 1]);\n }\n\n for (int i = 0; i < m; ++i)\n ans = Math.max(ans, dp[i][0]);\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int maxMoves(vector>& grid) {\n const int m = grid.size();\n const int n = grid[0].size();\n int ans = 0;\n // dp[i][j] := the maximum number of moves you can perform from (i, j)\n vector> dp(m, vector(n));\n\n for (int j = n - 2; j >= 0; --j)\n for (int i = 0; i < m; ++i) {\n if (grid[i][j + 1] > grid[i][j])\n dp[i][j] = 1 + dp[i][j + 1];\n if (i > 0 && grid[i - 1][j + 1] > grid[i][j])\n dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j + 1]);\n if (i + 1 < m && grid[i + 1][j + 1] > grid[i][j])\n dp[i][j] = max(dp[i][j], 1 + dp[i + 1][j + 1]);\n }\n\n for (int i = 0; i < m; ++i)\n ans = max(ans, dp[i][0]);\n\n return ans;\n }\n};\n"} +{"task_num": 2685, "task_title": "Count the Number of Complete Components", "difficulty": 2, "func_name": "countCompleteComponents", "description": "You are given an integer `n`. There is an undirected graph with `n` vertices,\nnumbered from `0` to `n - 1`. You are given a 2D integer array `edges` where\n`edges[i] = [ai, bi]` denotes that there exists an undirected edge connecting\nvertices `ai` and `bi`.\n\nReturn the number of complete connected components of the graph.\n\nA connected component is a subgraph of a graph in which there exists a path\nbetween any two vertices, and no vertex of the subgraph shares an edge with a\nvertex outside of the subgraph.\n\nA connected component is said to be complete if there exists an edge between\nevery pair of its vertices.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n self.nodeCount = [1] * n\n self.edgeCount = [0] * n\n\n def unionByRank(self, u: int, v: int) -> None:\n i = self.find(u)\n j = self.find(v)\n self.edgeCount[i] += 1\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n self.edgeCount[j] += self.edgeCount[i]\n self.nodeCount[j] += self.nodeCount[i]\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n self.edgeCount[i] += self.edgeCount[j]\n self.nodeCount[i] += self.nodeCount[j]\n else:\n self.id[i] = j\n self.edgeCount[j] += self.edgeCount[i]\n self.nodeCount[j] += self.nodeCount[i]\n self.rank[j] += 1\n\n def find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self.find(self.id[u])\n return self.id[u]\n\n def isComplete(self, u):\n return self.nodeCount[u] * (self.nodeCount[u] - 1) // 2 == self.edgeCount[u]\n\n\nclass Solution:\n def countCompleteComponents(self, n: int, edges: List[List[int]]) -> int:\n ans = 0\n uf = UnionFind(n)\n parents = set()\n\n for u, v in edges:\n uf.unionByRank(u, v)\n\n for i in range(n):\n parent = uf.find(i)\n if parent not in parents and uf.isComplete(parent):\n ans += 1\n parents.add(parent)\n\n return ans\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n nodeCount = new int[n];\n edgeCount = new int[n];\n for (int i = 0; i < n; ++i) {\n id[i] = i;\n nodeCount[i] = 1;\n }\n }\n\n public void unionByRank(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n ++edgeCount[i];\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n edgeCount[j] += edgeCount[i];\n nodeCount[j] += nodeCount[i];\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n edgeCount[i] += edgeCount[j];\n nodeCount[i] += nodeCount[j];\n } else {\n id[i] = j;\n edgeCount[j] += edgeCount[i];\n nodeCount[j] += nodeCount[i];\n ++rank[j];\n }\n }\n\n public int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n\n public boolean isComplete(int u) {\n return nodeCount[u] * (nodeCount[u] - 1) / 2 == edgeCount[u];\n }\n\n private int[] id;\n private int[] rank;\n private int[] nodeCount;\n private int[] edgeCount;\n}\n\nclass Solution {\n public int countCompleteComponents(int n, int[][] edges) {\n int ans = 0;\n UnionFind uf = new UnionFind(n);\n Set parents = new HashSet<>();\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n uf.unionByRank(u, v);\n }\n\n for (int i = 0; i < n; ++i) {\n final int parent = uf.find(i);\n if (parents.add(parent) && uf.isComplete(parent))\n ++ans;\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n), rank(n), nodeCount(n, 1), edgeCount(n) {\n iota(id.begin(), id.end(), 0);\n }\n\n void unionByRank(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n ++edgeCount[i];\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n edgeCount[j] += edgeCount[i];\n nodeCount[j] += nodeCount[i];\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n edgeCount[i] += edgeCount[j];\n nodeCount[i] += nodeCount[j];\n } else {\n id[i] = j;\n edgeCount[j] += edgeCount[i];\n nodeCount[j] += nodeCount[i];\n ++rank[j];\n }\n }\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n\n bool isComplete(int u) {\n return nodeCount[u] * (nodeCount[u] - 1) / 2 == edgeCount[u];\n }\n\n private:\n vector id;\n vector rank;\n vector nodeCount;\n vector edgeCount;\n};\n\nclass Solution {\n public:\n int countCompleteComponents(int n, vector>& edges) {\n int ans = 0;\n UnionFind uf(n);\n unordered_set parents;\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n uf.unionByRank(u, v);\n }\n\n for (int i = 0; i < n; ++i) {\n const int parent = uf.find(i);\n if (parents.insert(parent).second && uf.isComplete(parent))\n ++ans;\n }\n\n return ans;\n }\n};\n"} +{"task_num": 2699, "task_title": "Modify Graph Edge Weights", "difficulty": 3, "func_name": "modifiedGraphEdges", "description": "You are given an undirected weighted connected graph containing `n` nodes\nlabeled from `0` to `n - 1`, and an integer array `edges` where `edges[i] =\n[ai, bi, wi]` indicates that there is an edge between nodes `ai` and `bi` with\nweight `wi`.\n\nSome edges have a weight of `-1` (`wi = -1`), while others have a positive\nweight (`wi > 0`).\n\nYour task is to modify all edges with a weight of `-1` by assigning them\npositive integer values in the range `[1, 2 * 109]` so that the shortest\ndistance between the nodes `source` and `destination` becomes equal to an\ninteger `target`. If there are multiple modifications that make the shortest\ndistance between `source` and `destination` equal to `target`, any of them\nwill be considered correct.\n\nReturn an array containing all edges (even unmodified ones) in any order if it\nis possible to make the shortest distance from `source` to `destination` equal\nto `target`, or an empty array if it's impossible.\n\nNote: You are not allowed to modify the weights of edges with initial positive\nweights.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\n\nclass Solution:\n def modifiedGraphEdges(self, n: int, edges: List[List[int]], source: int, destination: int, target: int) -> List[List[int]]:\n kMax = 2_000_000_000\n graph = [[] for _ in range(n)]\n\n for u, v, w in edges:\n if w == -1:\n continue\n graph[u].append((v, w))\n graph[v].append((u, w))\n\n distToDestination = self._dijkstra(graph, source, destination)\n if distToDestination < target:\n return []\n if distToDestination == target:\n for edge in edges:\n if edge[2] == -1:\n edge[2] = kMax\n return edges\n\n for i, (u, v, w) in enumerate(edges):\n if w != -1:\n continue\n edges[i][2] = 1\n graph[u].append((v, 1))\n graph[v].append((u, 1))\n distToDestination = self._dijkstra(graph, source, destination)\n if distToDestination <= target:\n edges[i][2] += target - distToDestination\n for j in range(i + 1, len(edges)):\n if edges[j][2] == -1:\n edges[j][2] = kMax\n return edges\n\n return []\n\n def _dijkstra(self, graph: List[List[int]], src: int, dst: int) -> int:\n dist = [math.inf] * len(graph)\n minHeap = []\n dist[src] = 0\n heapq.heappush(minHeap, (dist[src], src))\n\n while minHeap:\n d, u = heapq.heappop(minHeap)\n if d > dist[u]:\n continue\n for v, w in graph[u]:\n if d + w < dist[v]:\n dist[v] = d + w\n heapq.heappush(minHeap, (dist[v], v))\n\n return dist[dst]\n", "java_solution": "class Solution {\n public int[][] modifiedGraphEdges(int n, int[][] edges, int source, int destination, int target) {\n final int MAX = 2_000_000_000;\n List>[] graph = new List[n];\n\n for (int i = 0; i < n; i++)\n graph[i] = new ArrayList<>();\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n final int w = edge[2];\n if (w == -1)\n continue;\n graph[u].add(new Pair<>(v, w));\n graph[v].add(new Pair<>(u, w));\n }\n\n int distToDestination = dijkstra(graph, source, destination);\n if (distToDestination < target)\n return new int[0][];\n if (distToDestination == target) {\n // Change the weights of negative edges to an impossible value.\n for (int[] edge : edges)\n if (edge[2] == -1)\n edge[2] = MAX;\n return edges;\n }\n\n for (int i = 0; i < edges.length; ++i) {\n final int u = edges[i][0];\n final int v = edges[i][1];\n final int w = edges[i][2];\n if (w != -1)\n continue;\n edges[i][2] = 1;\n graph[u].add(new Pair<>(v, 1));\n graph[v].add(new Pair<>(u, 1));\n distToDestination = dijkstra(graph, source, destination);\n if (distToDestination <= target) {\n edges[i][2] += target - distToDestination;\n // Change the weights of negative edges to an impossible value.\n for (int j = i + 1; j < edges.length; ++j)\n if (edges[j][2] == -1)\n edges[j][2] = MAX;\n return edges;\n }\n }\n\n return new int[0][];\n }\n\n private int dijkstra(List>[] graph, int src, int dst) {\n int[] dist = new int[graph.length];\n Arrays.fill(dist, Integer.MAX_VALUE);\n\n dist[src] = 0;\n Queue> minHeap =\n new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) {\n { offer(new Pair<>(dist[src], src)); } // (d, u)\n };\n\n while (!minHeap.isEmpty()) {\n final int d = minHeap.peek().getKey();\n final int u = minHeap.poll().getValue();\n if (d > dist[u])\n continue;\n for (Pair pair : graph[u]) {\n final int v = pair.getKey();\n final int w = pair.getValue();\n if (d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.offer(new Pair<>(dist[v], v));\n }\n }\n }\n\n return dist[dst];\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector> modifiedGraphEdges(int n, vector>& edges,\n int source, int destination,\n int target) {\n constexpr int kMax = 2'000'000'000;\n vector>> graph(n);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n const int w = edge[2];\n if (w == -1)\n continue;\n graph[u].emplace_back(v, w);\n graph[v].emplace_back(u, w);\n }\n\n int distToDestination = dijkstra(graph, source, destination);\n if (distToDestination < target)\n return {};\n if (distToDestination == target) {\n // Change the weights of negative edges to an impossible value.\n for (vector& edge : edges)\n if (edge[2] == -1)\n edge[2] = kMax;\n return edges;\n }\n\n for (int i = 0; i < edges.size(); ++i) {\n const int u = edges[i][0];\n const int v = edges[i][1];\n int& w = edges[i][2];\n if (w != -1)\n continue;\n w = 1;\n graph[u].emplace_back(v, 1);\n graph[v].emplace_back(u, 1);\n distToDestination = dijkstra(graph, source, destination);\n if (distToDestination <= target) {\n w += target - distToDestination;\n // Change the weights of negative edges to an impossible value.\n for (int j = i + 1; j < edges.size(); ++j)\n if (edges[j][2] == -1)\n edges[j][2] = kMax;\n return edges;\n }\n }\n\n return {};\n }\n\n private:\n int dijkstra(const vector>>& graph, int src, int dst) {\n vector dist(graph.size(), INT_MAX);\n\n dist[src] = 0;\n using P = pair; // (d, u)\n priority_queue, greater<>> minHeap;\n minHeap.emplace(dist[src], src);\n\n while (!minHeap.empty()) {\n const auto [d, u] = minHeap.top();\n minHeap.pop();\n if (d > dist[u])\n continue;\n for (const auto& [v, w] : graph[u])\n if (d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.emplace(dist[v], v);\n }\n }\n\n return dist[dst];\n }\n};\n"} +{"task_num": 2708, "task_title": "Maximum Strength of a Group", "difficulty": 2, "func_name": "maxStrength", "description": "You are given a 0-indexed integer array `nums` representing the score of\nstudents in an exam. The teacher would like to form one non-empty group of\nstudents with maximal strength, where the strength of a group of students of\nindices `i0`, `i1`, `i2`, ... , `ik` is defined as `nums[i0] * nums[i1] *\nnums[i2] * ... * nums[ik\u200b]`.\n\nReturn the maximum strength of a group the teacher can create.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def maxStrength(self, nums: List[int]) -> int:\n posProd = 1\n negProd = 1\n maxNeg = -math.inf\n negCount = 0\n hasPos = False\n hasZero = False\n\n for num in nums:\n if num > 0:\n posProd *= num\n hasPos = True\n elif num < 0:\n negProd *= num\n maxNeg = max(maxNeg, num)\n negCount += 1\n else:\n hasZero = True\n\n if negCount == 0 and not hasPos:\n return 0\n if negCount % 2 == 0:\n return negProd * posProd\n if negCount >= 3:\n return negProd // maxNeg * posProd\n if hasPos:\n return posProd\n if hasZero:\n return 0\n return maxNeg\n", "java_solution": "class Solution {\n public long maxStrength(int[] nums) {\n long posProd = 1;\n long negProd = 1;\n int maxNeg = Integer.MIN_VALUE;\n int negCount = 0;\n boolean hasPos = false;\n boolean hasZero = false;\n\n for (final int num : nums)\n if (num > 0) {\n posProd *= num;\n hasPos = true;\n } else if (num < 0) {\n negProd *= num;\n maxNeg = Math.max(maxNeg, num);\n ++negCount;\n } else { // num == 0\n hasZero = true;\n }\n\n if (negCount == 0 && !hasPos)\n return 0;\n if (negCount % 2 == 0)\n return negProd * posProd;\n if (negCount >= 3)\n return negProd / maxNeg * posProd;\n if (hasPos)\n return posProd;\n if (hasZero)\n return 0;\n return maxNeg;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n long long maxStrength(vector& nums) {\n long posProd = 1;\n long negProd = 1;\n int maxNeg = INT_MIN;\n int negCount = 0;\n bool hasPos = false;\n bool hasZero = false;\n\n for (const int num : nums)\n if (num > 0) {\n posProd *= num;\n hasPos = true;\n } else if (num < 0) {\n negProd *= num;\n maxNeg = max(maxNeg, num);\n ++negCount;\n } else { // num == 0\n hasZero = true;\n }\n\n if (negCount == 0 && !hasPos)\n return 0;\n if (negCount % 2 == 0)\n return negProd * posProd;\n if (negCount >= 3)\n return negProd / maxNeg * posProd;\n if (hasPos)\n return posProd;\n if (hasZero)\n return 0;\n return maxNeg;\n }\n};\n"} +{"task_num": 2709, "task_title": "Greatest Common Divisor Traversal", "difficulty": 3, "func_name": "canTraverseAllPairs", "description": "You are given a 0-indexed integer array `nums`, and you are allowed to\ntraverse between its indices. You can traverse between index `i` and index\n`j`, `i != j`, if and only if `gcd(nums[i], nums[j]) > 1`, where `gcd` is the\ngreatest common divisor.\n\nYour task is to determine if for every pair of indices `i` and `j` in nums,\nwhere `i < j`, there exists a sequence of traversals that can take us from `i`\nto `j`.\n\nReturn `true` if it is possible to traverse between all such pairs of indices,\nor `false` otherwise.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.sz = [1] * n\n\n def unionBySize(self, u: int, v: int) -> None:\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return\n if self.sz[i] < self.sz[j]:\n self.sz[j] += self.sz[i]\n self.id[i] = j\n else:\n self.sz[i] += self.sz[j]\n self.id[j] = i\n\n def getSize(self, i: int) -> int:\n return self.sz[i]\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def canTraverseAllPairs(self, nums: List[int]) -> bool:\n n = len(nums)\n max_num = max(nums)\n maxPrimeFactor = self._sieveEratosthenes(max_num + 1)\n primeToFirstIndex = collections.defaultdict(int)\n uf = UnionFind(n)\n\n for i, num in enumerate(nums):\n for prime_factor in self._getPrimeFactors(num, maxPrimeFactor):\n if prime_factor in primeToFirstIndex:\n uf.unionBySize(primeToFirstIndex[prime_factor], i)\n else:\n primeToFirstIndex[prime_factor] = i\n\n return any(uf.getSize(i) == n for i in range(n))\n\n def _sieveEratosthenes(self, n: int) -> List[int]:\n minPrimeFactors = [i for i in range(n + 1)]\n for i in range(2, int(n**0.5) + 1):\n if minPrimeFactors[i] == i:\n for j in range(i * i, n, i):\n minPrimeFactors[j] = min(minPrimeFactors[j], i)\n return minPrimeFactors\n\n def _getPrimeFactors(self, num: int, minPrimeFactors: List[int]) -> List[int]:\n primeFactors = []\n while num > 1:\n divisor = minPrimeFactors[num]\n primeFactors.append(divisor)\n while num % divisor == 0:\n num //= divisor\n return primeFactors\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n sz = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n for (int i = 0; i < n; ++i)\n sz[i] = 1;\n }\n\n public void unionBySize(int u, int v) {\n final int i = find(u);\n final int j = find(v);\n if (i == j)\n return;\n if (sz[i] < sz[j]) {\n sz[j] += sz[i];\n id[i] = j;\n } else {\n sz[i] += sz[j];\n id[j] = i;\n }\n }\n\n public int getSize(int i) {\n return sz[i];\n }\n\n private int[] id;\n private int[] sz;\n\n private int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n}\n\nclass Solution {\n public boolean canTraverseAllPairs(int[] nums) {\n final int n = nums.length;\n final int mx = Arrays.stream(nums).max().getAsInt();\n final int[] minPrimeFactors = sieveEratosthenes(mx + 1);\n Map primeToFirstIndex = new HashMap<>();\n UnionFind uf = new UnionFind(n);\n\n for (int i = 0; i < n; ++i)\n for (final int primeFactor : getPrimeFactors(nums[i], minPrimeFactors))\n // `primeFactor` already appeared in the previous indices.\n if (primeToFirstIndex.containsKey(primeFactor))\n uf.unionBySize(primeToFirstIndex.get(primeFactor), i);\n else\n primeToFirstIndex.put(primeFactor, i);\n\n for (int i = 0; i < n; ++i)\n if (uf.getSize(i) == n)\n return true;\n return false;\n }\n\n // Gets the minimum prime factor of i, where 1 < i <= n.\n private int[] sieveEratosthenes(int n) {\n int[] minPrimeFactors = new int[n + 1];\n for (int i = 2; i <= n; ++i)\n minPrimeFactors[i] = i;\n for (int i = 2; i * i < n; ++i)\n if (minPrimeFactors[i] == i) // `i` is prime.\n for (int j = i * i; j < n; j += i)\n minPrimeFactors[j] = Math.min(minPrimeFactors[j], i);\n return minPrimeFactors;\n }\n\n private List getPrimeFactors(int num, int[] minPrimeFactors) {\n List primeFactors = new ArrayList<>();\n while (num > 1) {\n final int divisor = minPrimeFactors[num];\n primeFactors.add(divisor);\n while (num % divisor == 0)\n num /= divisor;\n }\n return primeFactors;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n UnionFind(int n) : id(n), sz(n, 1) {\n iota(id.begin(), id.end(), 0);\n }\n\n void unionBySize(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return;\n if (sz[i] < sz[j]) {\n sz[j] += sz[i];\n id[i] = j;\n } else {\n sz[i] += sz[j];\n id[j] = i;\n }\n }\n\n int getSize(int i) {\n return sz[i];\n }\n\n private:\n vector id;\n vector sz;\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n};\n\nclass Solution {\n public:\n bool canTraverseAllPairs(vector& nums) {\n const int n = nums.size();\n const int mx = ranges::max(nums);\n const vector minPrimeFactors = sieveEratosthenes(mx + 1);\n unordered_map primeToFirstIndex;\n UnionFind uf(n);\n\n for (int i = 0; i < n; ++i)\n for (const int primeFactor : getPrimeFactors(nums[i], minPrimeFactors))\n // `primeFactor` already appeared in the previous indices.\n if (const auto it = primeToFirstIndex.find(primeFactor);\n it != primeToFirstIndex.cend())\n uf.unionBySize(it->second, i);\n else\n primeToFirstIndex[primeFactor] = i;\n\n for (int i = 0; i < n; ++i)\n if (uf.getSize(i) == n)\n return true;\n\n return false;\n }\n\n private:\n // Gets the minimum prime factor of i, where 1 < i <= n.\n vector sieveEratosthenes(int n) {\n vector minPrimeFactors(n + 1);\n iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2);\n for (int i = 2; i * i < n; ++i)\n if (minPrimeFactors[i] == i) // `i` is prime.\n for (int j = i * i; j < n; j += i)\n minPrimeFactors[j] = min(minPrimeFactors[j], i);\n return minPrimeFactors;\n }\n\n vector getPrimeFactors(int num, const vector& minPrimeFactors) {\n vector primeFactors;\n while (num > 1) {\n const int divisor = minPrimeFactors[num];\n primeFactors.push_back(divisor);\n while (num % divisor == 0)\n num /= divisor;\n }\n return primeFactors;\n }\n};\n"} +{"task_num": 2736, "task_title": "Maximum Sum Queries", "difficulty": 3, "func_name": "maximumSumQueries", "description": "You are given two 0-indexed integer arrays `nums1` and `nums2`, each of length\n`n`, and a 1-indexed 2D array `queries` where `queries[i] = [xi, yi]`.\n\nFor the `ith` query, find the maximum value of `nums1[j] + nums2[j]` among all\nindices `j` `(0 <= j < n)`, where `nums1[j] >= xi` and `nums2[j] >= yi`, or -1\nif there is no `j` satisfying the constraints.\n\nReturn an array `answer` where `answer[i]` is the answer to the `ith` query.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Pair:\n def __init__(self, x: int, y: int):\n self.x = x\n self.y = y\n\n def __iter__(self):\n yield self.x\n yield self.y\n\n\nclass IndexedQuery:\n def __init__(self, queryIndex: int, minX: int, minY: int):\n self.queryIndex = queryIndex\n self.minX = minX\n self.minY = minY\n\n def __iter__(self):\n yield self.queryIndex\n yield self.minX\n yield self.minY\n\n\nclass Solution:\n def maximumSumQueries(self, nums1: List[int], nums2: List[int], queries: List[List[int]]) -> List[int]:\n pairs = sorted([Pair(nums1[i], nums2[i])\n for i in range(len(nums1))], key=lambda p: p.x, reverse=True)\n ans = [0] * len(queries)\n stack = [] # [(y, x + y)]\n\n pairsIndex = 0\n for queryIndex, minX, minY in sorted([IndexedQuery(i, query[0], query[1]) for i, query in enumerate(queries)], key=lambda iq: -iq.minX):\n while pairsIndex < len(pairs) and pairs[pairsIndex].x >= minX:\n x, y = pairs[pairsIndex]\n while stack and x + y >= stack[-1][1]:\n stack.pop()\n if not stack or y > stack[-1][0]:\n stack.append((y, x + y))\n pairsIndex += 1\n j = self._firstGreaterEqual(stack, minY)\n if j == len(stack):\n ans[queryIndex] = -1\n else:\n ans[queryIndex] = stack[j][1]\n\n return ans\n\n def _firstGreaterEqual(self, A: List[Tuple[int, int]], target: int) -> int:\n l = 0\n r = len(A)\n while l < r:\n m = (l + r) // 2\n if A[m][0] >= target:\n r = m\n else:\n l = m + 1\n return l\n", "java_solution": "class Solution {\n public int[] maximumSumQueries(int[] nums1, int[] nums2, int[][] queries) {\n MyPair[] pairs = getPairs(nums1, nums2);\n IndexedQuery[] indexedQueries = getIndexedQueries(queries);\n int[] ans = new int[queries.length];\n List> stack = new ArrayList<>(); // [(y, x + y)]\n\n int pairsIndex = 0;\n for (IndexedQuery indexedQuery : indexedQueries) {\n final int queryIndex = indexedQuery.queryIndex;\n final int minX = indexedQuery.minX;\n final int minY = indexedQuery.minY;\n while (pairsIndex < pairs.length && pairs[pairsIndex].x >= minX) {\n MyPair pair = pairs[pairsIndex++];\n // x + y is a better candidate. Given that x is decreasing, the\n // condition \"x + y >= stack.get(stack.size() - 1).getValue()\" suggests\n // that y is relatively larger, thereby making it a better candidate.\n final int x = pair.x;\n final int y = pair.y;\n while (!stack.isEmpty() && x + y >= stack.get(stack.size() - 1).getValue())\n stack.remove(stack.size() - 1);\n if (stack.isEmpty() || y > stack.get(stack.size() - 1).getKey())\n stack.add(new Pair<>(y, x + y));\n }\n final int j = firstGreaterEqual(stack, minY);\n ans[queryIndex] = j == stack.size() ? -1 : stack.get(j).getValue();\n }\n\n return ans;\n }\n\n private record MyPair(int x, int y){};\n private record IndexedQuery(int queryIndex, int minX, int minY){};\n\n private int firstGreaterEqual(List> A, int target) {\n int l = 0;\n int r = A.size();\n while (l < r) {\n final int m = (l + r) / 2;\n if (A.get(m).getKey() >= target)\n r = m;\n else\n l = m + 1;\n }\n return l;\n }\n\n private MyPair[] getPairs(int[] nums1, int[] nums2) {\n MyPair[] pairs = new MyPair[nums1.length];\n for (int i = 0; i < nums1.length; ++i)\n pairs[i] = new MyPair(nums1[i], nums2[i]);\n Arrays.sort(pairs, Comparator.comparing(MyPair::x, Comparator.reverseOrder()));\n return pairs;\n }\n\n private IndexedQuery[] getIndexedQueries(int[][] queries) {\n IndexedQuery[] indexedQueries = new IndexedQuery[queries.length];\n for (int i = 0; i < queries.length; ++i)\n indexedQueries[i] = new IndexedQuery(i, queries[i][0], queries[i][1]);\n Arrays.sort(indexedQueries,\n Comparator.comparing(IndexedQuery::minX, Comparator.reverseOrder()));\n return indexedQueries;\n }\n}\n", "cpp_solution": "struct Pair {\n int x;\n int y;\n};\n\nstruct IndexedQuery {\n int queryIndex;\n int minX;\n int minY;\n};\n\nclass Solution {\n public:\n vector maximumSumQueries(vector& nums1, vector& nums2,\n vector>& queries) {\n const vector pairs = getPairs(nums1, nums2);\n vector ans(queries.size());\n vector> stack; // [(y, x + y)]\n\n int pairsIndex = 0;\n for (const auto& [queryIndex, minX, minY] : getIndexedQueries(queries)) {\n while (pairsIndex < pairs.size() && pairs[pairsIndex].x >= minX) {\n const auto [x, y] = pairs[pairsIndex++];\n // x + y is a better candidate. Given that x is decreasing, the\n // condition \"x + y >= stack.back().second\" suggests that y is\n // relatively larger, thereby making it a better candidate.\n while (!stack.empty() && x + y >= stack.back().second)\n stack.pop_back();\n if (stack.empty() || y > stack.back().first)\n stack.emplace_back(y, x + y);\n }\n const auto it = ranges::lower_bound(stack, pair{minY, INT_MIN});\n ans[queryIndex] = it == stack.end() ? -1 : it->second;\n }\n\n return ans;\n }\n\n private:\n vector getPairs(const vector& nums1, const vector& nums2) {\n vector pairs;\n for (int i = 0; i < nums1.size(); ++i)\n pairs.push_back({nums1[i], nums2[i]});\n ranges::sort(pairs, ranges::greater{},\n [](const Pair& pair) { return pair.x; });\n return pairs;\n }\n\n vector getIndexedQueries(const vector>& queries) {\n vector indexedQueries;\n for (int i = 0; i < queries.size(); ++i)\n indexedQueries.push_back({i, queries[i][0], queries[i][1]});\n ranges::sort(indexedQueries,\n [](const IndexedQuery& a, const IndexedQuery& b) {\n return a.minX > b.minX;\n });\n return indexedQueries;\n }\n};\n"} +{"task_num": 2747, "task_title": "Count Zero Request Servers", "difficulty": 2, "func_name": "countServers", "description": "You are given an integer `n` denoting the total number of servers and a 2D\n0-indexed integer array `logs`, where `logs[i] = [server_id, time]` denotes\nthat the server with id `server_id` received a request at time `time`.\n\nYou are also given an integer `x` and a 0-indexed integer array `queries`.\n\nReturn a 0-indexed integer array `arr` of length `queries.length` where\n`arr[i]` represents the number of servers that did not receive any requests\nduring the time interval `[queries[i] - x, queries[i]]`.\n\nNote that the time intervals are inclusive.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass IndexedQuery:\n def __init__(self, queryIndex: int, query: int):\n self.queryIndex = queryIndex\n self.query = query\n\n def __iter__(self):\n yield self.queryIndex\n yield self.query\n\n\nclass Solution:\n def countServers(self, n: int, logs: List[List[int]], x: int, queries: List[int]) -> List[int]:\n ans = [0] * len(queries)\n count = [0] * (n + 1)\n\n logs.sort(key=lambda log: log[1])\n\n i = 0\n j = 0\n servers = 0\n\n for queryIndex, query in sorted([IndexedQuery(i, query) for i, query in enumerate(queries)], key=lambda iq: iq.query):\n while j < len(logs) and logs[j][1] <= query:\n count[logs[j][0]] += 1\n if count[logs[j][0]] == 1:\n servers += 1\n j += 1\n while i < len(logs) and logs[i][1] < query - x:\n count[logs[i][0]] -= 1\n if count[logs[i][0]] == 0:\n servers -= 1\n i += 1\n ans[queryIndex] = n - servers\n\n return ans\n", "java_solution": "class Solution {\n public int[] countServers(int n, int[][] logs, int x, int[] queries) {\n int[] ans = new int[queries.length];\n int[] count = new int[n + 1];\n\n Arrays.sort(logs, Comparator.comparingInt(log -> log[1]));\n\n int i = 0;\n int j = 0;\n int servers = 0;\n\n // For each query, we care about logs[i..j].\n for (IndexedQuery indexedQuery : getIndexedQueries(queries)) {\n final int queryIndex = indexedQuery.queryIndex;\n final int query = indexedQuery.query;\n for (; j < logs.length && logs[j][1] <= query; ++j)\n if (++count[logs[j][0]] == 1)\n ++servers;\n for (; i < logs.length && logs[i][1] < query - x; ++i)\n if (--count[logs[i][0]] == 0)\n --servers;\n ans[queryIndex] = n - servers;\n }\n\n return ans;\n }\n\n private record IndexedQuery(int queryIndex, int query){};\n\n private IndexedQuery[] getIndexedQueries(int[] queries) {\n IndexedQuery[] indexedQueries = new IndexedQuery[queries.length];\n for (int i = 0; i < queries.length; ++i)\n indexedQueries[i] = new IndexedQuery(i, queries[i]);\n Arrays.sort(indexedQueries, Comparator.comparingInt(IndexedQuery::query));\n return indexedQueries;\n }\n}\n", "cpp_solution": "struct IndexedQuery {\n int queryIndex;\n int query;\n};\n\nclass Solution {\n public:\n vector countServers(int n, vector>& logs, int x,\n vector& queries) {\n vector ans(queries.size());\n vector count(n + 1);\n\n ranges::sort(logs, ranges::less{},\n [](const vector& log) { return log[1]; });\n\n int i = 0;\n int j = 0;\n int servers = 0;\n\n // For each query, we care about logs[i..j].\n for (const auto& [queryIndex, query] : getIndexedQueries(queries)) {\n for (; j < logs.size() && logs[j][1] <= query; ++j)\n if (++count[logs[j][0]] == 1)\n ++servers;\n for (; i < logs.size() && logs[i][1] < query - x; ++i)\n if (--count[logs[i][0]] == 0)\n --servers;\n ans[queryIndex] = n - servers;\n }\n\n return ans;\n }\n\n private:\n vector getIndexedQueries(const vector& queries) {\n vector indexedQueries;\n for (int i = 0; i < queries.size(); ++i)\n indexedQueries.push_back({i, queries[i]});\n ranges::sort(indexedQueries,\n [](const IndexedQuery& a, const IndexedQuery& b) {\n return a.query < b.query;\n });\n return indexedQueries;\n }\n};\n"} +{"task_num": 2751, "task_title": "Robot Collisions", "difficulty": 3, "func_name": "survivedRobotsHealths", "description": "There are `n` 1-indexed robots, each having a position on a line, health, and\nmovement direction.\n\nYou are given 0-indexed integer arrays `positions`, `healths`, and a string\n`directions` (`directions[i]` is either 'L' for left or 'R' for right). All\nintegers in `positions` are unique.\n\nAll robots start moving on the line simultaneously at the same speed in their\ngiven directions. If two robots ever share the same position while moving,\nthey will collide.\n\nIf two robots collide, the robot with lower health is removed from the line,\nand the health of the other robot decreases by one. The surviving robot\ncontinues in the same direction it was going. If both robots have the same\nhealth, they are both removed from the line.\n\nYour task is to determine the health of the robots that survive the\ncollisions, in the same order that the robots were given, i.e. final heath of\nrobot 1 (if survived), final health of robot 2 (if survived), and so on. If\nthere are no survivors, return an empty array.\n\nReturn an array containing the health of the remaining robots (in the order\nthey were given in the input), after no further collisions can occur.\n\nNote: The positions may be unsorted.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\nfrom dataclasses import dataclass\n\n@dataclass\nclass Robot:\n index: int\n position: int\n health: int\n direction: str\n\n\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n robots = sorted([Robot(index, position, health, direction) for index, (position, health, direction) in enumerate(zip(positions, healths, directions))], key=lambda robot: robot.position)\n stack: List[Robot] = []\n\n for robot in robots:\n if robot.direction == 'R':\n stack.append(robot)\n continue\n while stack and stack[-1].direction == 'R' and robot.health > 0:\n if stack[-1].health == robot.health:\n stack.pop()\n robot.health = 0\n elif stack[-1].health < robot.health:\n stack.pop()\n robot.health -= 1\n else:\n stack[-1].health -= 1\n robot.health = 0\n if robot.health > 0:\n stack.append(robot)\n\n stack.sort(key=lambda robot: robot.index)\n return [robot.health for robot in stack]\n", "java_solution": "class Robot {\n public int index;\n public int position;\n public int health;\n public char direction;\n public Robot(int index, int position, int health, char direction) {\n this.index = index;\n this.position = position;\n this.health = health;\n this.direction = direction;\n }\n}\n\nclass Solution {\n public List survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n List ans = new ArrayList<>();\n Robot[] robots = new Robot[positions.length];\n List stack = new ArrayList<>(); // running robots\n\n for (int i = 0; i < positions.length; ++i)\n robots[i] = new Robot(i, positions[i], healths[i], directions.charAt(i));\n\n Arrays.sort(robots, Comparator.comparingInt((Robot robot) -> robot.position));\n\n for (Robot robot : robots) {\n if (robot.direction == 'R') {\n stack.add(robot);\n continue;\n }\n // Collide with robots going right if any.\n while (!stack.isEmpty() && stack.get(stack.size() - 1).direction == 'R' && robot.health > 0) {\n if (stack.get(stack.size() - 1).health == robot.health) {\n stack.remove(stack.size() - 1);\n robot.health = 0;\n } else if (stack.get(stack.size() - 1).health < robot.health) {\n stack.remove(stack.size() - 1);\n robot.health -= 1;\n } else { // stack[-1].health > robot.health\n stack.get(stack.size() - 1).health -= 1;\n robot.health = 0;\n }\n }\n if (robot.health > 0)\n stack.add(robot);\n }\n\n stack.sort(Comparator.comparingInt((Robot robot) -> robot.index));\n\n for (Robot robot : stack)\n ans.add(robot.health);\n\n return ans;\n }\n}\n", "cpp_solution": "struct Robot {\n int index;\n int position;\n int health;\n char direction;\n};\n\nclass Solution {\n public:\n vector survivedRobotsHealths(vector& positions,\n vector& healths, string directions) {\n vector ans;\n vector robots;\n vector stack; // the runnnig robots\n\n for (int i = 0; i < positions.size(); ++i)\n robots.push_back(Robot{i, positions[i], healths[i], directions[i]});\n\n ranges::sort(robots, ranges::less{},\n [](const Robot& robot) { return robot.position; });\n\n for (Robot& robot : robots) {\n if (robot.direction == 'R') {\n stack.push_back(robot);\n continue;\n }\n // Collide with robots going right if any.\n while (!stack.empty() && stack.back().direction == 'R' &&\n robot.health > 0) {\n if (stack.back().health == robot.health) {\n stack.pop_back();\n robot.health = 0;\n } else if (stack.back().health < robot.health) {\n stack.pop_back();\n robot.health -= 1;\n } else { // stack.back().health > robot.health\n stack.back().health -= 1;\n robot.health = 0;\n }\n }\n if (robot.health > 0)\n stack.push_back(robot);\n }\n\n ranges::sort(stack, ranges::less{},\n [](const Robot& robot) { return robot.index; });\n\n for (const Robot& robot : stack)\n ans.push_back(robot.health);\n\n return ans;\n }\n};\n"} +{"task_num": 2812, "task_title": "Find the Safest Path in a Grid", "difficulty": 2, "func_name": "maximumSafenessFactor", "description": "You are given a 0-indexed 2D matrix `grid` of size `n x n`, where `(r, c)`\nrepresents:\n\n* A cell containing a thief if `grid[r][c] = 1`\n* An empty cell if `grid[r][c] = 0`\n\nYou are initially positioned at cell `(0, 0)`. In one move, you can move to\nany adjacent cell in the grid, including cells containing thieves.\n\nThe safeness factor of a path on the grid is defined as the minimum manhattan\ndistance from any cell in the path to any thief in the grid.\n\nReturn the maximum safeness factor of all paths leading to cell `(n - 1, n -\n1)`.\n\nAn adjacent cell of cell `(r, c)`, is one of the cells `(r, c + 1)`, `(r, c -\n1)`, `(r + 1, c)` and `(r - 1, c)` if it exists.\n\nThe Manhattan distance between two cells `(a, b)` and `(x, y)` is equal to `|a\n- x| + |b - y|`, where `|val|` denotes the absolute value of val.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def maximumSafenessFactor(self, grid: List[List[int]]) -> int:\n self.dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n n = len(grid)\n distToThief = self._getDistToThief(grid)\n\n def hasValidPath(safeness: int) -> bool:\n if distToThief[0][0] < safeness:\n return False\n\n q = collections.deque([(0, 0)])\n seen = {(0, 0)}\n\n while q:\n i, j = q.popleft()\n if distToThief[i][j] < safeness:\n continue\n if i == n - 1 and j == n - 1:\n return True\n for dx, dy in self.dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == n or y < 0 or y == n:\n continue\n if (x, y) in seen:\n continue\n q.append((x, y))\n seen.add((x, y))\n\n return False\n\n return bisect.bisect_left(range(n * 2), True, key=lambda m: not hasValidPath(m)) - 1\n\n def _getDistToThief(self, grid: List[List[int]]) -> List[List[int]]:\n n = len(grid)\n distToThief = [[0] * n for _ in range(n)]\n q = collections.deque()\n seen = set()\n\n for i in range(n):\n for j in range(n):\n if grid[i][j] == 1:\n q.append((i, j))\n seen.add((i, j))\n\n dist = 0\n while q:\n for _ in range(len(q)):\n i, j = q.popleft()\n distToThief[i][j] = dist\n for dx, dy in self.dirs:\n x = i + dx\n y = j + dy\n if x < 0 or x == n or y < 0 or y == n:\n continue\n if (x, y) in seen:\n continue\n q.append((x, y))\n seen.add((x, y))\n dist += 1\n\n return distToThief\n", "java_solution": "class Solution {\n public int maximumSafenessFactor(List> grid) {\n int[][] distToThief = getDistToThief(grid);\n int l = 0;\n int r = grid.size() * 2;\n\n while (l < r) {\n final int m = (l + r) / 2;\n if (hasValidPath(distToThief, m))\n l = m + 1;\n else\n r = m;\n }\n\n return l - 1;\n }\n\n private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n private boolean hasValidPath(int[][] distToThief, int safeness) {\n if (distToThief[0][0] < safeness)\n return false;\n\n final int n = distToThief.length;\n Queue> q = new ArrayDeque<>(List.of(new Pair<>(0, 0)));\n boolean[][] seen = new boolean[n][n];\n seen[0][0] = true;\n\n while (!q.isEmpty()) {\n final int i = q.peek().getKey();\n final int j = q.poll().getValue();\n if (distToThief[i][j] < safeness)\n continue;\n if (i == n - 1 && j == n - 1)\n return true;\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == n || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n q.offer(new Pair<>(x, y));\n seen[x][y] = true;\n }\n }\n\n return false;\n }\n\n private int[][] getDistToThief(List> grid) {\n final int n = grid.size();\n int[][] distToThief = new int[n][n];\n Queue> q = new ArrayDeque<>();\n boolean[][] seen = new boolean[n][n];\n\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n if (grid.get(i).get(j) == 1) {\n q.offer(new Pair<>(i, j));\n seen[i][j] = true;\n }\n\n for (int dist = 0; !q.isEmpty(); ++dist) {\n for (int sz = q.size(); sz > 0; --sz) {\n final int i = q.peek().getKey();\n final int j = q.poll().getValue();\n distToThief[i][j] = dist;\n for (int[] dir : DIRS) {\n final int x = i + dir[0];\n final int y = j + dir[1];\n if (x < 0 || x == n || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n q.offer(new Pair<>(x, y));\n seen[x][y] = true;\n }\n }\n }\n\n return distToThief;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int maximumSafenessFactor(vector>& grid) {\n const vector> distToThief = getDistToThief(grid);\n int l = 0;\n int r = grid.size() * 2;\n\n while (l < r) {\n const int m = (l + r) / 2;\n if (hasValidPath(distToThief, m))\n l = m + 1;\n else\n r = m;\n }\n\n return l - 1;\n }\n\n private:\n static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n bool hasValidPath(const vector>& distToThief, int safeness) {\n if (distToThief[0][0] < safeness)\n return false;\n\n const int n = distToThief.size();\n queue> q{{{0, 0}}};\n vector> seen(n, vector(n));\n seen[0][0] = true;\n\n while (!q.empty()) {\n const auto [i, j] = q.front();\n q.pop();\n if (distToThief[i][j] < safeness)\n continue;\n if (i == n - 1 && j == n - 1)\n return true;\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == n || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n q.emplace(x, y);\n seen[x][y] = true;\n }\n }\n\n return false;\n }\n\n vector> getDistToThief(const vector>& grid) {\n const int n = grid.size();\n vector> distToThief(n, vector(n));\n queue> q;\n vector> seen(n, vector(n));\n\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == 1) {\n q.emplace(i, j);\n seen[i][j] = true;\n }\n\n for (int dist = 0; !q.empty(); ++dist) {\n for (int sz = q.size(); sz > 0; --sz) {\n const auto [i, j] = q.front();\n q.pop();\n distToThief[i][j] = dist;\n for (const auto& [dx, dy] : kDirs) {\n const int x = i + dx;\n const int y = j + dy;\n if (x < 0 || x == n || y < 0 || y == n)\n continue;\n if (seen[x][y])\n continue;\n q.emplace(x, y);\n seen[x][y] = true;\n }\n }\n }\n\n return distToThief;\n }\n};\n"} +{"task_num": 2818, "task_title": "Apply Operations to Maximize Score", "difficulty": 3, "func_name": "maximumScore", "description": "You are given an array `nums` of `n` positive integers and an integer `k`.\n\nInitially, you start with a score of `1`. You have to maximize your score by\napplying the following operation at most `k` times:\n\n* Choose any non-empty subarray `nums[l, ..., r]` that you haven't chosen previously.\n* Choose an element `x` of `nums[l, ..., r]` with the highest prime score. If multiple such elements exist, choose the one with the smallest index.\n* Multiply your score by `x`.\n\nHere, `nums[l, ..., r]` denotes the subarray of `nums` starting at index `l`\nand ending at the index `r`, both ends being inclusive.\n\nThe prime score of an integer `x` is equal to the number of distinct prime\nfactors of `x`. For example, the prime score of `300` is `3` since `300 = 2 *\n2 * 3 * 5 * 5`.\n\nReturn the maximum possible score after applying at most `k` operations.\n\nSince the answer may be large, return it modulo `109 + 7`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def maximumScore(self, nums: List[int], k: int) -> int:\n kMod = 1_000_000_007\n n = len(nums)\n ans = 1\n minPrimeFactors = self._sieveEratosthenes(max(nums) + 1)\n primeScores = [self._getPrimeScore(num, minPrimeFactors) for num in nums]\n left = [-1] * n\n right = [n] * n\n stack = []\n\n for i in reversed(range(n)):\n while stack and primeScores[stack[-1]] <= primeScores[i]:\n left[stack.pop()] = i\n stack.append(i)\n\n stack = []\n\n for i in range(n):\n while stack and primeScores[stack[-1]] < primeScores[i]:\n right[stack.pop()] = i\n stack.append(i)\n\n numAndIndexes = [(num, i) for i, num in enumerate(nums)]\n\n def modPow(x: int, n: int) -> int:\n if n == 0:\n return 1\n if n & 1:\n return x * modPow(x, n - 1) % kMod\n return modPow(x * x % kMod, n // 2)\n\n for num, i in sorted(numAndIndexes, key=lambda x: (-x[0], x[1])):\n rangeCount = (i - left[i]) * (right[i] - i)\n actualCount = min(rangeCount, k)\n k -= actualCount\n ans *= modPow(num, actualCount)\n ans %= kMod\n\n return ans\n\n def _sieveEratosthenes(self, n: int) -> List[int]:\n minPrimeFactors = [i for i in range(n + 1)]\n for i in range(2, int(n**0.5) + 1):\n if minPrimeFactors[i] == i:\n for j in range(i * i, n, i):\n minPrimeFactors[j] = min(minPrimeFactors[j], i)\n return minPrimeFactors\n\n def _getPrimeScore(self, num: int, minPrimeFactors: List[int]) -> int:\n primeFactors = set()\n while num > 1:\n divisor = minPrimeFactors[num]\n primeFactors.add(divisor)\n while num % divisor == 0:\n num //= divisor\n return len(primeFactors)\n", "java_solution": "class Solution {\n public int maximumScore(List nums, int k) {\n final int n = nums.size();\n final int mx = Collections.max(nums);\n final int[] minPrimeFactors = sieveEratosthenes(mx + 1);\n final int[] primeScores = getPrimeScores(nums, minPrimeFactors);\n int ans = 1;\n // left[i] := the next index on the left (if any)\n // s.t. primeScores[left[i]] >= primeScores[i]\n int[] left = new int[n];\n Arrays.fill(left, -1);\n // right[i] := the next index on the right (if any)\n // s.t. primeScores[right[i]] > primeScores[i]\n int[] right = new int[n];\n Arrays.fill(right, n);\n Deque stack = new ArrayDeque<>();\n\n // Find the next indices on the left where `primeScores` are greater or equal.\n for (int i = n - 1; i >= 0; --i) {\n while (!stack.isEmpty() && primeScores[stack.peek()] <= primeScores[i])\n left[stack.pop()] = i;\n stack.push(i);\n }\n\n stack.clear();\n\n // Find the next indices on the right where `primeScores` are greater.\n for (int i = 0; i < n; ++i) {\n while (!stack.isEmpty() && primeScores[stack.peek()] < primeScores[i])\n right[stack.pop()] = i;\n stack.push(i);\n }\n\n Pair[] numAndIndexes = new Pair[n];\n\n for (int i = 0; i < n; ++i)\n numAndIndexes[i] = new Pair<>(nums.get(i), i);\n\n Arrays.sort(numAndIndexes,\n Comparator.comparing(Pair::getKey, Comparator.reverseOrder())\n .thenComparingInt(Pair::getValue));\n\n for (Pair numAndIndex : numAndIndexes) {\n final int num = numAndIndex.getKey();\n final int i = numAndIndex.getValue();\n // nums[i] is the maximum value in the range [left[i] + 1, right[i] - 1]\n // So, there are (i - left[i]) * (right[i] - 1) ranges where nums[i] will\n // be chosen.\n final long rangeCount = (long) (i - left[i]) * (right[i] - i);\n final long actualCount = Math.min(rangeCount, (long) k);\n k -= actualCount;\n ans = (int) ((1L * ans * modPow(num, actualCount)) % MOD);\n }\n\n return ans;\n }\n\n private static final int MOD = 1_000_000_007;\n\n private long modPow(long x, long n) {\n if (n == 0)\n return 1;\n if (n % 2 == 1)\n return x * modPow(x, n - 1) % MOD;\n return modPow(x * x % MOD, n / 2);\n }\n\n // Gets the minimum prime factor of i, where 1 < i <= n.\n private int[] sieveEratosthenes(int n) {\n int[] minPrimeFactors = new int[n + 1];\n for (int i = 2; i <= n; ++i)\n minPrimeFactors[i] = i;\n for (int i = 2; i * i < n; ++i)\n if (minPrimeFactors[i] == i) // `i` is prime.\n for (int j = i * i; j < n; j += i)\n minPrimeFactors[j] = Math.min(minPrimeFactors[j], i);\n return minPrimeFactors;\n }\n\n private int[] getPrimeScores(List nums, int[] minPrimeFactors) {\n int[] primeScores = new int[nums.size()];\n for (int i = 0; i < nums.size(); ++i)\n primeScores[i] = getPrimeScore(nums.get(i), minPrimeFactors);\n return primeScores;\n }\n\n private int getPrimeScore(int num, int[] minPrimeFactors) {\n Set primeFactors = new HashSet<>();\n while (num > 1) {\n final int divisor = minPrimeFactors[num];\n primeFactors.add(divisor);\n while (num % divisor == 0)\n num /= divisor;\n }\n return primeFactors.size();\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int maximumScore(vector& nums, int k) {\n const int n = nums.size();\n const int mx = ranges::max(nums);\n const vector minPrimeFactors = sieveEratosthenes(mx + 1);\n const vector primeScores = getPrimeScores(nums, minPrimeFactors);\n int ans = 1;\n // left[i] := the next index on the left (if any) s.t.\n // primeScores[left[i]] >= primeScores[i]\n vector left(n, -1);\n // right[i] := the next index on the right (if any) s.t.\n // primeScores[right[i]] > primeScores[i]\n vector right(n, n);\n stack stack;\n\n // Find the next indices on the left where `primeScores` are greater or\n // equal.\n for (int i = n - 1; i >= 0; --i) {\n while (!stack.empty() && primeScores[stack.top()] <= primeScores[i])\n left[stack.top()] = i, stack.pop();\n stack.push(i);\n }\n\n stack = std::stack();\n\n // Find the next indices on the right where `primeScores` are greater.\n for (int i = 0; i < n; ++i) {\n while (!stack.empty() && primeScores[stack.top()] < primeScores[i])\n right[stack.top()] = i, stack.pop();\n stack.push(i);\n }\n\n vector> numAndIndexes;\n\n for (int i = 0; i < n; ++i)\n numAndIndexes.emplace_back(nums[i], i);\n\n ranges::sort(numAndIndexes,\n [&](const pair& a, const pair& b) {\n return a.first == b.first ? a.second < b.second : a.first > b.first;\n });\n\n for (const auto& [num, i] : numAndIndexes) {\n // nums[i] is the maximum value in the range [left[i] + 1, right[i] - 1]\n // So, there are (i - left[i]) * (right[i] - 1) ranges where nums[i] will\n // be chosen.\n const long rangeCount = static_cast(i - left[i]) * (right[i] - i);\n const long actualCount = min(rangeCount, static_cast(k));\n k -= actualCount;\n ans = static_cast(ans) * modPow(num, actualCount) % kMod;\n }\n\n return ans;\n }\n\n private:\n static constexpr int kMod = 1'000'000'007;\n\n long modPow(long x, long n) {\n if (n == 0)\n return 1;\n if (n % 2 == 1)\n return x * modPow(x % kMod, (n - 1)) % kMod;\n return modPow(x * x % kMod, (n / 2)) % kMod;\n }\n\n // Gets the minimum prime factor of i, where 1 < i <= n.\n vector sieveEratosthenes(int n) {\n vector minPrimeFactors(n + 1);\n iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2);\n for (int i = 2; i * i < n; ++i)\n if (minPrimeFactors[i] == i) // `i` is prime.\n for (int j = i * i; j < n; j += i)\n minPrimeFactors[j] = min(minPrimeFactors[j], i);\n return minPrimeFactors;\n }\n\n vector getPrimeScores(const vector& nums,\n const vector& minPrimeFactors) {\n vector primeScores;\n for (const int num : nums)\n primeScores.push_back(getPrimeScore(num, minPrimeFactors));\n return primeScores;\n }\n\n int getPrimeScore(int num, const vector& minPrimeFactors) {\n unordered_set primeFactors;\n while (num > 1) {\n const int divisor = minPrimeFactors[num];\n primeFactors.insert(divisor);\n while (num % divisor == 0)\n num /= divisor;\n }\n return primeFactors.size();\n }\n};\n"} +{"task_num": 2836, "task_title": "Maximize Value of Function in a Ball Passing Game", "difficulty": 3, "func_name": "getMaxFunctionValue", "description": "You are given an integer array `receiver` of length `n` and an integer `k`.\n`n` players are playing a ball-passing game.\n\nYou choose the starting player, `i`. The game proceeds as follows: player `i`\npasses the ball to player `receiver[i]`, who then passes it to\n`receiver[receiver[i]]`, and so on, for `k` passes in total. The game's score\nis the sum of the indices of the players who touched the ball, including\nrepetitions, i.e. `i + receiver[i] + receiver[receiver[i]] + ... +\nreceiver(k)[i]`.\n\nReturn the maximum possible score.\n\nNotes:\n\n* `receiver` may contain duplicates.\n* `receiver[i]` may be equal to `i`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def getMaxFunctionValue(self, receiver: List[int], k: int) -> int:\n n = len(receiver)\n m = int(math.log2(k)) + 1\n ans = 0\n jump = [[0] * m for _ in range(n)]\n summ = [[0] * m for _ in range(n)]\n\n for i in range(n):\n jump[i][0] = receiver[i]\n summ[i][0] = receiver[i]\n\n for j in range(1, m):\n for i in range(n):\n midNode = jump[i][j - 1]\n jump[i][j] = jump[midNode][j - 1]\n summ[i][j] = summ[i][j - 1] + summ[midNode][j - 1]\n\n for i in range(n):\n currSum = i\n currPos = i\n for j in range(m):\n if (k >> j) & 1 == 1:\n currSum += summ[currPos][j]\n currPos = jump[currPos][j]\n ans = max(ans, currSum)\n\n return ans\n", "java_solution": "class Solution {\n public long getMaxFunctionValue(List receiver, long k) {\n final int n = receiver.size();\n final int m = (int) (Math.log(k) / Math.log(2)) + 1;\n long ans = 0;\n // jump[i][j] := the the node you reach after jumping 2^j steps from i\n int[][] jump = new int[n][m];\n // sum[i][j] := the sum of the first 2^j nodes you reach when jumping from i\n long[][] sum = new long[n][m];\n\n for (int i = 0; i < n; ++i) {\n jump[i][0] = receiver.get(i);\n sum[i][0] = receiver.get(i);\n }\n\n // Calculate binary lifting.\n for (int j = 1; j < m; ++j)\n for (int i = 0; i < n; ++i) {\n final int midNode = jump[i][j - 1];\n // the the node you reach after jumping 2^j steps from i\n // = the node you reach after jumping 2^(j - 1) steps from i\n // + the node you reach after jumping another 2^(j - 1) steps\n jump[i][j] = jump[midNode][j - 1];\n // the sum of the first 2^j nodes you reach when jumping from i\n // = the sum of the first 2^(j - 1) nodes you reach when jumping from i\n // + the sum of another 2^(j - 1) nodes you reach\n sum[i][j] = sum[i][j - 1] + sum[midNode][j - 1];\n }\n\n for (int i = 0; i < n; ++i) {\n long currSum = i;\n int currPos = i;\n for (int j = 0; j < m; ++j)\n if ((k >> j & 1) == 1) {\n currSum += sum[currPos][j];\n currPos = jump[currPos][j];\n }\n ans = Math.max(ans, currSum);\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n long long getMaxFunctionValue(vector& receiver, long long k) {\n const int n = receiver.size();\n const int m = log2(k) + 1;\n long ans = 0;\n // jump[i][j] := the the node you reach after jumping 2^j steps from i\n vector> jump(n, vector(m));\n // sum[i][j] := the sum of the first 2^j nodes you reach when jumping from i\n vector> sum(n, vector(m));\n\n for (int i = 0; i < n; ++i) {\n jump[i][0] = receiver[i];\n sum[i][0] = receiver[i];\n }\n\n // Calculate binary lifting.\n for (int j = 1; j < m; ++j)\n for (int i = 0; i < n; ++i) {\n const int midNode = jump[i][j - 1];\n // the the node you reach after jumping 2^j steps from i\n // = the node you reach after jumping 2^(j - 1) steps from i\n // + the node you reach after jumping another 2^(j - 1) steps\n jump[i][j] = jump[midNode][j - 1];\n // the sum of the first 2^j nodes you reach when jumping from i\n // = the sum of the first 2^(j - 1) nodes you reach when jumping from i\n // + the sum of another 2^(j - 1) nodes you reach\n sum[i][j] = sum[i][j - 1] + sum[midNode][j - 1];\n }\n\n for (int i = 0; i < n; ++i) {\n long currSum = i;\n int currPos = i;\n for (int j = 0; j < m; ++j)\n if (k >> j & 1) {\n currSum += sum[currPos][j];\n currPos = jump[currPos][j];\n }\n ans = max(ans, currSum);\n }\n\n return ans;\n }\n};\n"} +{"task_num": 2844, "task_title": "Minimum Operations to Make a Special Number", "difficulty": 2, "func_name": "minimumOperations", "description": "You are given a 0-indexed string `num` representing a non-negative integer.\n\nIn one operation, you can pick any digit of `num` and delete it. Note that if\nyou delete all the digits of `num`, `num` becomes `0`.\n\nReturn the minimum number of operations required to make `num` special.\n\nAn integer `x` is considered special if it is divisible by `25`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumOperations(self, num: str) -> int:\n n = len(num)\n seenFive = False\n seenZero = False\n\n for i in range(n - 1, -1, -1):\n if seenZero and num[i] == '0':\n return n - i - 2\n if seenZero and num[i] == '5':\n return n - i - 2\n if seenFive and num[i] == '2':\n return n - i - 2\n if seenFive and num[i] == '7':\n return n - i - 2\n seenZero = seenZero or num[i] == '0'\n seenFive = seenFive or num[i] == '5'\n\n if seenZero:\n return n - 1\n else:\n return n\n", "java_solution": "class Solution {\n public int minimumOperations(String num) {\n final int n = num.length();\n boolean seenFive = false;\n boolean seenZero = false;\n\n for (int i = n - 1; i >= 0; --i) {\n if (seenZero && num.charAt(i) == '0') // '00'\n return n - i - 2;\n if (seenZero && num.charAt(i) == '5') // '50'\n return n - i - 2;\n if (seenFive && num.charAt(i) == '2') // '25'\n return n - i - 2;\n if (seenFive && num.charAt(i) == '7') // '75'\n return n - i - 2;\n seenZero = seenZero || num.charAt(i) == '0';\n seenFive = seenFive || num.charAt(i) == '5';\n }\n\n return seenZero ? n - 1 : n;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minimumOperations(string num) {\n const int n = num.length();\n bool seenFive = false;\n bool seenZero = false;\n\n for (int i = n - 1; i >= 0; --i) {\n if (seenZero && num[i] == '0') // '00'\n return n - i - 2;\n if (seenZero && num[i] == '5') // '50'\n return n - i - 2;\n if (seenFive && num[i] == '2') // '25'\n return n - i - 2;\n if (seenFive && num[i] == '7') // '75'\n return n - i - 2;\n seenZero = seenZero || num[i] == '0';\n seenFive = seenFive || num[i] == '5';\n }\n\n return seenZero ? n - 1 : n;\n }\n};\n"} +{"task_num": 2846, "task_title": "Minimum Edge Weight Equilibrium Queries in a Tree", "difficulty": 3, "func_name": "minOperationsQueries", "description": "There is an undirected tree with `n` nodes labeled from `0` to `n - 1`. You\nare given the integer `n` and a 2D integer array `edges` of length `n - 1`,\nwhere `edges[i] = [ui, vi, wi]` indicates that there is an edge between nodes\n`ui` and `vi` with weight `wi` in the tree.\n\nYou are also given a 2D integer array `queries` of length `m`, where\n`queries[i] = [ai, bi]`. For each query, find the minimum number of operations\nrequired to make the weight of every edge on the path from `ai` to `bi` equal.\nIn one operation, you can choose any edge of the tree and change its weight to\nany value.\n\nNote that:\n\n* Queries are independent of each other, meaning that the tree returns to its initial state on each new query.\n* The path from `ai` to `bi` is a sequence of distinct nodes starting with node `ai` and ending with node `bi` such that every two adjacent nodes in the sequence share an edge in the tree.\n\nReturn an array `answer` of length `m` where `answer[i]` is the answer to the\n`ith` query.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n kMax = 26\n m = int(math.log2(n)) + 1\n ans = []\n graph = [[] for _ in range(n)]\n jump = [[0] * m for _ in range(n)]\n count = [[] for _ in range(n)]\n depth = [0] * n\n\n for u, v, w in edges:\n graph[u].append((v, w))\n graph[v].append((u, w))\n\n def dfs(u: int, prev: int, d: int):\n if prev != -1:\n jump[u][0] = prev\n depth[u] = d\n for v, w in graph[u]:\n if v == prev:\n continue\n count[v] = count[u][:]\n count[v][w] += 1\n dfs(v, u, d + 1)\n\n count[0] = [0] * (kMax + 1)\n dfs(0, -1, 0)\n\n for j in range(1, m):\n for i in range(n):\n jump[i][j] = jump[jump[i][j - 1]][j - 1]\n\n def getLCA(u: int, v: int) -> int:\n if depth[u] > depth[v]:\n return getLCA(v, u)\n for j in range(m):\n if depth[v] - depth[u] >> j & 1:\n v = jump[v][j]\n if u == v:\n return u\n for j in range(m - 1, -1, -1):\n if jump[u][j] != jump[v][j]:\n u = jump[u][j]\n v = jump[v][j]\n return jump[v][0]\n\n for u, v in queries:\n lca = getLCA(u, v)\n numEdges = depth[u] + depth[v] - 2 * depth[lca]\n maxFreq = max(count[u][j] + count[v][j] - 2 * count[lca][j] for j in range(1, kMax + 1))\n ans.append(numEdges - maxFreq)\n\n return ans\n", "java_solution": "class Solution {\n public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) {\n final int MAX = 26;\n final int m = (int) Math.ceil(Math.log(n) / Math.log(2));\n int[] ans = new int[queries.length];\n List>[] graph = new List[n];\n // jump[i][j] := the 2^j-th ancestor of i\n int[][] jump = new int[n][m];\n // depth[i] := the depth of i\n int[] depth = new int[n];\n // count[i][j] := the count of j from root to i, where 1 <= j <= 26\n int[][] count = new int[n][MAX + 1];\n Arrays.setAll(graph, i -> new ArrayList<>());\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n final int w = edge[2];\n graph[u].add(new Pair<>(v, w));\n graph[v].add(new Pair<>(u, w));\n }\n\n count[0] = new int[MAX + 1];\n dfs(graph, 0, /*prev=*/-1, jump, depth, count);\n\n for (int j = 1; j < m; ++j)\n for (int i = 0; i < n; ++i)\n jump[i][j] = jump[jump[i][j - 1]][j - 1];\n\n for (int i = 0; i < queries.length; ++i) {\n final int u = queries[i][0];\n final int v = queries[i][1];\n final int lca = getLCA(u, v, jump, depth);\n // the number of edges between (u, v).\n final int numEdges = depth[u] + depth[v] - 2 * depth[lca];\n // the maximum frequency of edges between (u, v)\n int maxFreq = 0;\n for (int j = 1; j <= MAX; ++j)\n maxFreq = Math.max(maxFreq, count[u][j] + count[v][j] - 2 * count[lca][j]);\n ans[i] = numEdges - maxFreq;\n }\n\n return ans;\n }\n\n private void dfs(List>[] graph, int u, int prev, int[][] jump, int[] depth,\n int[][] count) {\n for (Pair pair : graph[u]) {\n final int v = pair.getKey();\n final int w = pair.getValue();\n if (v == prev)\n continue;\n jump[v][0] = u;\n depth[v] = depth[u] + 1;\n count[v] = count[u].clone();\n ++count[v][w];\n dfs(graph, v, u, jump, depth, count);\n }\n }\n\n // Returns the lca(u, v) by binary jump.\n private int getLCA(int u, int v, int[][] jump, int[] depth) {\n // v is always deeper than u.\n if (depth[u] > depth[v])\n return getLCA(v, u, jump, depth);\n // Jump v to the same height of u.\n for (int j = 0; j < jump[0].length; ++j)\n if ((depth[v] - depth[u] >> j & 1) == 1)\n v = jump[v][j];\n if (u == v)\n return u;\n // Jump u and v to the node right below the lca.\n for (int j = jump[0].length - 1; j >= 0; --j)\n if (jump[u][j] != jump[v][j]) {\n u = jump[u][j];\n v = jump[v][j];\n }\n return jump[v][0];\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector minOperationsQueries(int n, vector>& edges,\n vector>& queries) {\n constexpr int kMax = 26;\n const int m = ceil(log2(n));\n vector ans;\n vector>> graph(n);\n // jump[i][j] := the 2^j-th ancestor of i\n vector> jump(n, vector(m));\n // depth[i] := the depth of i\n vector depth(n);\n // count[i][j] := the count of j from root to i, where 1 <= j <= 26\n vector> count(n);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n const int w = edge[2];\n graph[u].emplace_back(v, w);\n graph[v].emplace_back(u, w);\n }\n\n count[0] = vector(kMax + 1);\n dfs(graph, 0, /*prev=*/-1, jump, depth, count);\n\n for (int j = 1; j < m; ++j)\n for (int i = 0; i < n; ++i)\n jump[i][j] = jump[jump[i][j - 1]][j - 1];\n\n for (const vector& query : queries) {\n const int u = query[0];\n const int v = query[1];\n const int lca = getLCA(u, v, jump, depth);\n // the number of edges between (u, v).\n const int numEdges = depth[u] + depth[v] - 2 * depth[lca];\n // the maximum frequency of edges between (u, v)\n int maxFreq = 0;\n for (int j = 1; j <= kMax; ++j)\n maxFreq = max(maxFreq, count[u][j] + count[v][j] - 2 * count[lca][j]);\n ans.push_back(numEdges - maxFreq);\n }\n\n return ans;\n }\n\n private:\n void dfs(const vector>>& graph, int u, int prev,\n vector>& jump, vector& depth,\n vector>& count) {\n for (const auto& [v, w] : graph[u]) {\n if (v == prev)\n continue;\n jump[v][0] = u;\n depth[v] = depth[u] + 1;\n count[v] = count[u];\n ++count[v][w];\n dfs(graph, v, u, jump, depth, count);\n }\n }\n\n // Returns the lca(u, v) by binary jump.\n int getLCA(int u, int v, const vector>& jump,\n const vector& depth) {\n // v is always deeper than u.\n if (depth[u] > depth[v])\n return getLCA(v, u, jump, depth);\n // Jump v to the same height of u.\n for (int j = 0; j < jump[0].size(); ++j)\n if (depth[v] - depth[u] >> j & 1)\n v = jump[v][j];\n if (u == v)\n return u;\n // Jump u and v to the node right below the lca.\n for (int j = jump[0].size() - 1; j >= 0; --j)\n if (jump[u][j] != jump[v][j]) {\n u = jump[u][j];\n v = jump[v][j];\n }\n return jump[v][0];\n }\n};\n"} +{"task_num": 2850, "task_title": "Minimum Moves to Spread Stones Over Grid", "difficulty": 2, "func_name": "minimumMoves", "description": "You are given a 0-indexed 2D integer matrix `grid` of size `3 * 3`,\nrepresenting the number of stones in each cell. The grid contains exactly `9`\nstones, and there can be multiple stones in a single cell.\n\nIn one move, you can move a single stone from its current cell to any other\ncell if the two cells share a side.\n\nReturn the minimum number of moves required to place one stone in each cell.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n if sum(row.count(0) for row in grid) == 0:\n return 0\n\n ans = math.inf\n\n for i in range(3):\n for j in range(3):\n if grid[i][j] == 0:\n for x in range(3):\n for y in range(3):\n if grid[x][y] > 1:\n grid[x][y] -= 1\n grid[i][j] += 1\n ans = min(ans, abs(x - i) + abs(y - j) + self.minimumMoves(grid))\n grid[x][y] += 1\n grid[i][j] -= 1\n\n return ans\n", "java_solution": "class Solution {\n public int minimumMoves(int[][] grid) {\n int zeroCount = 0;\n for (int[] row : grid)\n for (int cell : row)\n if (cell == 0)\n ++zeroCount;\n if (zeroCount == 0)\n return 0;\n\n int ans = Integer.MAX_VALUE;\n\n for (int i = 0; i < 3; ++i)\n for (int j = 0; j < 3; ++j)\n if (grid[i][j] == 0)\n for (int x = 0; x < 3; ++x)\n for (int y = 0; y < 3; ++y)\n if (grid[x][y] > 1) {\n --grid[x][y];\n ++grid[i][j];\n ans = Math.min(ans, Math.abs(x - i) + Math.abs(y - j) + minimumMoves(grid));\n ++grid[x][y];\n --grid[i][j];\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minimumMoves(vector>& grid) {\n const int zeroCount = accumulate(grid.begin(), grid.end(), 0,\n [](int acc, const vector& row) {\n return acc + ranges::count(row, 0);\n });\n if (zeroCount == 0)\n return 0;\n\n int ans = INT_MAX;\n\n for (int i = 0; i < 3; ++i)\n for (int j = 0; j < 3; ++j)\n if (grid[i][j] == 0)\n for (int x = 0; x < 3; ++x)\n for (int y = 0; y < 3; ++y)\n // Move a stone at (x, y) to (i, j).\n if (grid[x][y] > 1) {\n --grid[x][y];\n ++grid[i][j];\n ans = min(ans, abs(x - i) + abs(y - j) + minimumMoves(grid));\n ++grid[x][y];\n --grid[i][j];\n }\n\n return ans;\n }\n};\n"} +{"task_num": 2851, "task_title": "String Transformation", "difficulty": 3, "func_name": "numberOfWays", "description": "You are given two strings `s` and `t` of equal length `n`. You can perform the\nfollowing operation on the string `s`:\n\n* Remove a suffix of `s` of length `l` where `0 < l < n` and append it at the start of `s`. \nFor example, let `s = 'abcd'` then in one operation you can remove the suffix\n`'cd'` and append it in front of `s` making `s = 'cdab'`.\n\nYou are also given an integer `k`. Return the number of ways in which `s` can\nbe transformed into `t` in exactly `k` operations.\n\nSince the answer can be large, return it modulo `109 + 7`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n kMod = 1_000_000_007\n n = len(s)\n negOnePowK = 1 if k % 2 == 0 else -1 # (-1)^k\n z = self._zFunction(s + t + t)\n\n indices = [i - n for i in range(n, n + n) if z[i] >= n]\n dp = [0] * 2\n dp[1] = (pow(n - 1, k, kMod) - negOnePowK) * pow(n, kMod - 2, kMod)\n dp[0] = dp[1] + negOnePowK\n res = 0\n for index in indices:\n if index == 0:\n res += dp[0]\n else: \n res += dp[1]\n return res % kMod\n\n\n def _zFunction(self, s: str) -> List[int]:\n n = len(s)\n z = [0] * n\n l = 0\n r = 0\n for i in range(1, n):\n if i < r:\n z[i] = min(r - i, z[i - l])\n while i + z[i] < n and s[z[i]] == s[i + z[i]]:\n z[i] += 1\n if i + z[i] > r:\n l = i\n r = i + z[i]\n return z\n", "java_solution": "class Solution {\n // This dynamic programming table dp[k][i] represents the number of ways to\n // rearrange the String s after k steps such that it starts with s[i].\n // A String can be rotated from 1 to n - 1 times. The transition rule is\n // dp[k][i] = sum(dp[k - 1][j]) for all j != i. For example, when n = 4 and\n // k = 3, the table looks like this:\n //\n // -----------------------------------------------------------\n // | | i = 0 | i = 1 | i = 2 | i = 3 | sum = (n - 1)^k |\n // -----------------------------------------------------------\n // | k = 0 | 1 | 0 | 0 | 0 | 1 |\n // | k = 1 | 0 | 1 | 1 | 1 | 3 |\n // | k = 2 | 3 | 2 | 2 | 2 | 9 |\n // | k = 3 | 6 | 7 | 7 | 7 | 27 |\n // -----------------------------------------------------------\n //\n // By observation, we have\n // * dp[k][!0] = ((n - 1)^k - (-1)^k) / n\n // * dp[k][0] = dp[k][!0] + (-1)^k\n public int numberOfWays(String s, String t, long k) {\n final int n = s.length();\n final int negOnePowK = (k % 2 == 0 ? 1 : -1); // (-1)^k\n final int[] z = zFunction(s + t + t);\n final List indices = getIndices(z, n);\n int[] dp = new int[2]; // dp[0] := dp[k][0]; dp[1] := dp[k][!0]\n dp[1] = (int) ((modPow(n - 1, k) - negOnePowK + MOD) % MOD * modPow(n, MOD - 2) % MOD);\n dp[0] = (int) ((dp[1] + negOnePowK + MOD) % MOD);\n int ans = 0;\n for (final int index : getIndices(z, n)) {\n ans += dp[index == 0 ? 0 : 1];\n ans %= MOD;\n }\n return ans;\n }\n\n private static final int MOD = 1_000_000_007;\n\n private long modPow(long x, long n) {\n if (n == 0)\n return 1;\n if (n % 2 == 1)\n return x * modPow(x, n - 1) % MOD;\n return modPow(x * x % MOD, n / 2);\n }\n\n // Returns the z array, where z[i] is the length of the longest prefix of\n // s[i..n) which is also a prefix of s.\n //\n // https://cp-algorithms.com/string/z-function.html#implementation\n private int[] zFunction(final String s) {\n final int n = s.length();\n int[] z = new int[n];\n int l = 0;\n int r = 0;\n for (int i = 1; i < n; ++i) {\n if (i < r)\n z[i] = Math.min(r - i, z[i - l]);\n while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))\n ++z[i];\n if (i + z[i] > r) {\n l = i;\n r = i + z[i];\n }\n }\n return z;\n }\n\n // Returns the indices in `s` s.t. for each `i` in the returned indices,\n // `s[i..n) + s[0..i) = t`.\n private List getIndices(int[] z, int n) {\n List indices = new ArrayList<>();\n for (int i = n; i < n + n; ++i)\n if (z[i] >= n)\n indices.add(i - n);\n return indices;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n // This dynamic programming table dp[k][i] represents the number of ways to\n // rearrange the string s after k steps such that it starts with s[i].\n // A string can be rotated from 1 to n - 1 times. The transition rule is\n // dp[k][i] = sum(dp[k - 1][j]) for all j != i. For example, when n = 4 and\n // k = 3, the table looks like this:\n //\n // -----------------------------------------------------------\n // | | i = 0 | i = 1 | i = 2 | i = 3 | sum = (n - 1)^k |\n // -----------------------------------------------------------\n // | k = 0 | 1 | 0 | 0 | 0 | 1 |\n // | k = 1 | 0 | 1 | 1 | 1 | 3 |\n // | k = 2 | 3 | 2 | 2 | 2 | 9 |\n // | k = 3 | 6 | 7 | 7 | 7 | 27 |\n // -----------------------------------------------------------\n //\n // By observation, we have\n // * dp[k][!0] = ((n - 1)^k - (-1)^k) / n\n // * dp[k][0] = dp[k][!0] + (-1)^k\n int numberOfWays(string s, string t, long long k) {\n const int n = s.length();\n const int negOnePowK = (k % 2 == 0 ? 1 : -1); // (-1)^k\n const vector z = zFunction(s + t + t);\n const vector indices = getIndices(z, n);\n vector dp(2); // dp[0] := dp[k][0]; dp[1] := dp[k][!0]\n dp[1] = (modPow(n - 1, k) - negOnePowK + kMod) % kMod *\n modPow(n, kMod - 2) % kMod;\n dp[0] = (dp[1] + negOnePowK + kMod) % kMod;\n return accumulate(indices.begin(), indices.end(), 0L,\n [&](long acc, int index) {\n return (acc + dp[index == 0 ? 0 : 1]) % kMod;\n });\n }\n\n private:\n static constexpr int kMod = 1'000'000'007;\n\n long modPow(long x, long n) {\n if (n == 0)\n return 1;\n if (n % 2 == 1)\n return x * modPow(x, n - 1) % kMod;\n return modPow(x * x % kMod, n / 2);\n }\n\n // Returns the z array, where z[i] is the length of the longest prefix of\n // s[i..n) which is also a prefix of s.\n //\n // https://cp-algorithms.com/string/z-function.html#implementation\n vector zFunction(const string& s) {\n const int n = s.length();\n vector z(n);\n int l = 0;\n int r = 0;\n for (int i = 1; i < n; ++i) {\n if (i < r)\n z[i] = min(r - i, z[i - l]);\n while (i + z[i] < n && s[z[i]] == s[i + z[i]])\n ++z[i];\n if (i + z[i] > r) {\n l = i;\n r = i + z[i];\n }\n }\n return z;\n }\n\n // Returns the indices in `s` s.t. for each `i` in the returned indices,\n // `s[i..n) + s[0..i) = t`.\n vector getIndices(const vector& z, int n) {\n vector indices;\n for (int i = n; i < n + n; ++i)\n if (z[i] >= n)\n indices.push_back(i - n);\n return indices;\n }\n};\n"} +{"task_num": 2876, "task_title": "Count Visited Nodes in a Directed Graph", "difficulty": 3, "func_name": "countVisitedNodes", "description": "There is a directed graph consisting of `n` nodes numbered from `0` to `n - 1`\nand `n` directed edges.\n\nYou are given a 0-indexed array `edges` where `edges[i]` indicates that there\nis an edge from node `i` to node `edges[i]`.\n\nConsider the following process on the graph:\n\n* You start from a node `x` and keep visiting other nodes through edges until you reach a node that you have already visited before on this same process.\n\nReturn an array `answer` where `answer[i]` is the number of different nodes\nthat you will visit if you perform the process starting from node `i`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def countVisitedNodes(self, edges: List[int]) -> List[int]:\n n = len(edges)\n ans = [0] * n\n inDegrees = [0] * n\n seen = [False] * n\n stack = []\n\n for v in edges:\n inDegrees[v] += 1\n\n q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0])\n\n while q:\n u = q.popleft()\n inDegrees[edges[u]] -= 1\n if inDegrees[edges[u]] == 0:\n q.append(edges[u])\n stack.append(u)\n seen[u] = True\n\n for i in range(n):\n if not seen[i]:\n self._fillCycle(edges, i, seen, ans)\n\n while stack:\n u = stack.pop()\n ans[u] = ans[edges[u]] + 1\n\n return ans\n\n def _fillCycle(self, edges: List[int], start: int, seen: List[bool], ans: List[int]) -> None:\n cycleLength = 0\n u = start\n while not seen[u]:\n cycleLength += 1\n seen[u] = True\n u = edges[u]\n ans[start] = cycleLength\n u = edges[start]\n while u != start:\n ans[u] = cycleLength\n u = edges[u]\n", "java_solution": "class Solution {\n public int[] countVisitedNodes(List edges) {\n final int n = edges.size();\n int[] ans = new int[n];\n int[] inDegrees = new int[n];\n boolean[] seen = new boolean[n];\n Queue q = new ArrayDeque<>();\n Stack stack = new Stack<>();\n\n for (int v : edges)\n ++inDegrees[v];\n\n // Perform topological sorting.\n for (int i = 0; i < n; ++i)\n if (inDegrees[i] == 0)\n q.add(i);\n\n // Push non-cyclic nodes to stack.\n while (!q.isEmpty()) {\n final int u = q.poll();\n if (--inDegrees[edges.get(u)] == 0)\n q.add(edges.get(u));\n stack.push(u);\n seen[u] = true;\n }\n\n // Fill the length of cyclic nodes.\n for (int i = 0; i < n; ++i)\n if (!seen[i])\n fillCycle(edges, i, seen, ans);\n\n // Fill the length of non-cyclic nodes.\n while (!stack.isEmpty()) {\n final int u = stack.pop();\n ans[u] = ans[edges.get(u)] + 1;\n }\n\n return ans;\n }\n\n private void fillCycle(List edges, int start, boolean[] seen, int[] ans) {\n int cycleLength = 0;\n for (int u = start; !seen[u]; u = edges.get(u)) {\n ++cycleLength;\n seen[u] = true;\n }\n ans[start] = cycleLength;\n for (int u = edges.get(start); u != start; u = edges.get(u))\n ans[u] = cycleLength;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector countVisitedNodes(vector& edges) {\n const int n = edges.size();\n vector ans(n);\n vector inDegrees(n);\n vector seen(n);\n queue q;\n stack stack;\n\n for (const int v : edges)\n ++inDegrees[v];\n\n // Perform topological sorting.\n for (int i = 0; i < n; ++i)\n if (inDegrees[i] == 0)\n q.push(i);\n\n // Push non-cyclic nodes to stack.\n while (!q.empty()) {\n const int u = q.front();\n q.pop();\n if (--inDegrees[edges[u]] == 0)\n q.push(edges[u]);\n stack.push(u);\n seen[u] = true;\n }\n\n // Fill the length of cyclic nodes.\n for (int i = 0; i < n; ++i)\n if (!seen[i])\n fillCycle(edges, i, seen, ans);\n\n // Fill the length of non-cyclic nodes.\n while (!stack.empty()) {\n const int u = stack.top();\n stack.pop();\n ans[u] = ans[edges[u]] + 1;\n }\n\n return ans;\n }\n\n private:\n void fillCycle(const vector& edges, int start, vector& seen,\n vector& ans) {\n int cycleLength = 0;\n for (int u = start; !seen[u]; u = edges[u]) {\n ++cycleLength;\n seen[u] = true;\n }\n ans[start] = cycleLength;\n for (int u = edges[start]; u != start; u = edges[u])\n ans[u] = cycleLength;\n }\n};\n"} +{"task_num": 2901, "task_title": "Longest Unequal Adjacent Groups Subsequence II", "difficulty": 2, "func_name": "getWordsInLongestSubsequence", "description": "You are given a string array `words`, and an array `groups`, both arrays\nhaving length `n`.\n\nThe hamming distance between two strings of equal length is the number of\npositions at which the corresponding characters are different.\n\nYou need to select the longest subsequence from an array of indices `[0, 1,\n..., n - 1]`, such that for the subsequence denoted as `[i0, i1, ..., ik-1]`\nhaving length `k`, the following holds:\n\n* For adjacent indices in the subsequence, their corresponding groups are unequal, i.e., `groups[ij] != groups[ij+1]`, for each `j` where `0 < j + 1 < k`.\n* `words[ij]` and `words[ij+1]` are equal in length, and the hamming distance between them is `1`, where `0 < j + 1 < k`, for all indices in the subsequence.\n\nReturn a string array containing the words corresponding to the indices (in\norder) in the selected subsequence. If there are multiple answers, return any\nof them.\n\nNote: strings in `words` may be unequal in length.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def getWordsInLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]:\n ans = []\n n=len(words)\n dp = [1] * n\n prev = [-1] * n\n\n for i in range(1, n):\n for j in range(i):\n if groups[i] == groups[j]:\n continue\n if len(words[i]) != len(words[j]):\n continue\n if sum(a != b for a, b in zip(words[i], words[j])) != 1:\n continue\n if dp[i] < dp[j] + 1:\n dp[i] = dp[j] + 1\n prev[i] = j\n\n index = dp.index(max(dp))\n while index != -1:\n ans.append(words[index])\n index = prev[index]\n\n return ans[::-1]\n", "java_solution": "class Solution {\n public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) {\n List ans = new ArrayList<>();\n // dp[i] := the length of the longest subsequence ending in `words[i]`\n int[] dp = new int[n];\n Arrays.fill(dp, 1);\n // prev[i] := the best index of words[i]\n int[] prev = new int[n];\n Arrays.fill(prev, -1);\n\n for (int i = 1; i < n; ++i)\n for (int j = 0; j < i; ++j) {\n if (groups[i] == groups[j])\n continue;\n if (words[i].length() != words[j].length())\n continue;\n if (hammingDist(words[i], words[j]) != 1)\n continue;\n if (dp[i] < dp[j] + 1) {\n dp[i] = dp[j] + 1;\n prev[i] = j;\n }\n }\n\n // Find the last index of the subsequence.\n int index = getMaxIndex(dp);\n while (index != -1) {\n ans.add(words[index]);\n index = prev[index];\n }\n\n Collections.reverse(ans);\n return ans;\n }\n\n private int hammingDist(final String s1, final String s2) {\n int dist = 0;\n for (int i = 0; i < s1.length(); ++i)\n if (s1.charAt(i) != s2.charAt(i))\n ++dist;\n return dist;\n }\n\n private int getMaxIndex(int[] dp) {\n int maxIndex = 0;\n for (int i = 0; i < dp.length; ++i)\n if (dp[i] > dp[maxIndex])\n maxIndex = i;\n return maxIndex;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector getWordsInLongestSubsequence(int n, vector& words,\n vector& groups) {\n vector ans;\n // dp[i] := the length of the longest subsequence ending in `words[i]`\n vector dp(n, 1);\n // prev[i] := the best index of words[i]\n vector prev(n, -1);\n\n for (int i = 1; i < n; ++i)\n for (int j = 0; j < i; ++j) {\n if (groups[i] == groups[j])\n continue;\n if (words[i].length() != words[j].length())\n continue;\n if (hammingDist(words[i], words[j]) != 1)\n continue;\n if (dp[i] < dp[j] + 1) {\n dp[i] = dp[j] + 1;\n prev[i] = j;\n }\n }\n\n // Find the last index of the subsequence.\n int index = ranges::max_element(dp) - dp.begin();\n while (index != -1) {\n ans.push_back(words[index]);\n index = prev[index];\n }\n\n ranges::reverse(ans);\n return ans;\n }\n\n private:\n int hammingDist(const string& s1, const string& s2) {\n int dist = 0;\n for (int i = 0; i < s1.length(); ++i)\n if (s1[i] != s2[i])\n ++dist;\n return dist;\n }\n};\n"} +{"task_num": 2904, "task_title": "Shortest and Lexicographically Smallest Beautiful String", "difficulty": 2, "func_name": "shortestBeautifulSubstring", "description": "You are given a binary string `s` and a positive integer `k`.\n\nA substring of `s` is beautiful if the number of `1`'s in it is exactly `k`.\n\nLet `len` be the length of the shortest beautiful substring.\n\nReturn the lexicographically smallest beautiful substring of string `s` with\nlength equal to `len`. If `s` doesn't contain a beautiful substring, return an\nempty string.\n\nA string `a` is lexicographically larger than a string `b` (of the same\nlength) if in the first position where `a` and `b` differ, `a` has a character\nstrictly larger than the corresponding character in `b`.\n\n* For example, `\"abcd\"` is lexicographically larger than `\"abcc\"` because the first position they differ is at the fourth character, and `d` is greater than `c`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def shortestBeautifulSubstring(self, s: str, k: int) -> str:\n bestLeft = -1\n minLength = len(s) + 1\n ones = 0\n\n l = 0\n for r, c in enumerate(s):\n if c == '1':\n ones += 1\n while ones == k:\n if r - l + 1 < minLength:\n bestLeft = l\n minLength = r - l + 1\n elif r - l + 1 == minLength and s[l:l + minLength] < s[bestLeft:bestLeft + minLength]:\n bestLeft = l\n if s[l] == '1':\n ones -= 1\n l += 1\n\n if bestLeft == -1:\n return \"\"\n else:\n return s[bestLeft:bestLeft + minLength]\n", "java_solution": "class Solution {\n // Same as 76. Minimum Window Substring\n public String shortestBeautifulSubstring(String s, int k) {\n int bestLeft = -1;\n int minLength = s.length() + 1;\n int ones = 0;\n\n for (int l = 0, r = 0; r < s.length(); ++r) {\n if (s.charAt(r) == '1')\n ++ones;\n while (ones == k) {\n if (r - l + 1 < minLength) {\n bestLeft = l;\n minLength = r - l + 1;\n } else if (r - l + 1 == minLength &&\n s.substring(l, l + minLength)\n .compareTo(s.substring(bestLeft, bestLeft + minLength)) < 0) {\n bestLeft = l;\n }\n if (s.charAt(l++) == '1')\n --ones;\n }\n }\n\n return bestLeft == -1 ? \"\" : s.substring(bestLeft, bestLeft + minLength);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n // Same as 76. Minimum Window Substring\n string shortestBeautifulSubstring(string s, int k) {\n int bestLeft = -1;\n int minLength = s.length() + 1;\n int ones = 0;\n\n for (int l = 0, r = 0; r < s.length(); ++r) {\n if (s[r] == '1')\n ++ones;\n while (ones == k) {\n if (r - l + 1 < minLength) {\n bestLeft = l;\n minLength = r - l + 1;\n } else if (r - l + 1 == minLength &&\n s.compare(l, minLength, s, bestLeft, minLength) < 0) {\n bestLeft = l;\n }\n if (s[l++] == '1')\n --ones;\n }\n }\n\n return bestLeft == -1 ? \"\" : s.substr(bestLeft, minLength);\n }\n};\n"} +{"task_num": 2911, "task_title": "Minimum Changes to Make K Semi-palindromes", "difficulty": 3, "func_name": "minimumChanges", "description": "Given a string `s` and an integer `k`, partition `s` into `k` substrings such\nthat the letter changes needed to make each substring a semi-palindrome are\nminimized.\n\nReturn the minimum number of letter changes required.\n\nA semi-palindrome is a special type of string that can be divided into\npalindromes based on a repeating pattern. To check if a string is a semi-\npalindrome:\u200b\n\n1. Choose a positive divisor `d` of the string's length. `d` can range from `1` up to, but not including, the string's length. For a string of length `1`, it does not have a valid divisor as per this definition, since the only divisor is its length, which is not allowed.\n2. For a given divisor `d`, divide the string into groups where each group contains characters from the string that follow a repeating pattern of length `d`. Specifically, the first group consists of characters at positions `1`, `1 + d`, `1 + 2d`, and so on; the second group includes characters at positions `2`, `2 + d`, `2 + 2d`, etc.\n3. The string is considered a semi-palindrome if each of these groups forms a palindrome.\n\nConsider the string `\"abcabc\"`:\n\n* The length of `\"abcabc\"` is `6`. Valid divisors are `1`, `2`, and `3`.\n* For `d = 1`: The entire string `\"abcabc\"` forms one group. Not a palindrome.\n* For `d = 2`: \n* Group 1 (positions `1, 3, 5`): `\"acb\"`\n* Group 2 (positions `2, 4, 6`): `\"bac\"`\n* Neither group forms a palindrome.\n* For `d = 3`: \n* Group 1 (positions `1, 4`): `\"aa\"`\n* Group 2 (positions `2, 5`): `\"bb\"`\n* Group 3 (positions `3, 6`): `\"cc\"`\n* All groups form palindromes. Therefore, `\"abcabc\"` is a semi-palindrome.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumChanges(self, s: str, k: int) -> int:\n n = len(s)\n factors = self._getFactors(n)\n cost = self._getCost(s, n, factors)\n dp = [[n] * (k + 1) for _ in range(n + 1)]\n\n dp[n][0] = 0\n\n for i in range(n - 1, -1, -1):\n for j in range(1, k + 1):\n for l in range(i + 1, n):\n dp[i][j] = min(dp[i][j], dp[l + 1][j - 1] + cost[i][l])\n\n return dp[0][k]\n\n def _getFactors(self, n: int) -> List[List[int]]:\n factors = [[1] for _ in range(n + 1)]\n for d in range(2, n):\n for i in range(d * 2, n + 1, d):\n factors[i].append(d)\n return factors\n\n def _getCost(self, s: str, n: int, factors: List[List[int]]) -> List[List[int]]:\n cost = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(i + 1, n):\n length = j - i + 1\n minCost = length\n for d in factors[length]:\n minCost = min(minCost, self._getCostD(s, i, j, d))\n cost[i][j] = minCost\n return cost\n\n def _getCostD(self, s: str, i: int, j: int, d: int) -> int:\n cost = 0\n for offset in range(d):\n l = i + offset\n r = j - d + 1 + offset\n while l < r:\n if s[l] != s[r]:\n cost += 1\n l += d\n r -= d\n return cost\n", "java_solution": "class Solution {\n public int minimumChanges(String s, int k) {\n final int n = s.length();\n // factors[i] := factors of i\n List[] factors = getFactors(n);\n // cost[i][j] := changes to make s[i..j] a semi-palindrome\n int[][] cost = getCost(s, n, factors);\n // dp[i][j] := the minimum changes to split s[i:] into j valid parts\n int[][] dp = new int[n + 1][k + 1];\n\n Arrays.stream(dp).forEach(A -> Arrays.fill(A, n));\n dp[n][0] = 0;\n\n for (int i = n - 1; i >= 0; --i)\n for (int j = 1; j <= k; ++j)\n for (int l = i + 1; l < n; ++l)\n dp[i][j] = Math.min(dp[i][j], dp[l + 1][j - 1] + cost[i][l]);\n\n return dp[0][k];\n }\n\n private List[] getFactors(int n) {\n List[] factors = new List[n + 1];\n for (int i = 1; i <= n; ++i)\n factors[i] = new ArrayList<>(List.of(1));\n for (int d = 2; d < n; ++d)\n for (int i = d * 2; i <= n; i += d)\n factors[i].add(d);\n return factors;\n }\n\n private int[][] getCost(final String s, int n, List[] factors) {\n int[][] cost = new int[n][n];\n for (int i = 0; i < n; ++i)\n for (int j = i + 1; j < n; ++j) {\n final int length = j - i + 1;\n int minCost = length;\n for (final int d : factors[length])\n minCost = Math.min(minCost, getCost(s, i, j, d));\n cost[i][j] = minCost;\n }\n return cost;\n }\n\n // Returns the cost to make s[i..j] a semi-palindrome of `d`.\n private int getCost(final String s, int i, int j, int d) {\n int cost = 0;\n for (int offset = 0; offset < d; ++offset) {\n int l = i + offset;\n int r = j - d + 1 + offset;\n while (l < r) {\n if (s.charAt(l) != s.charAt(r))\n ++cost;\n l += d;\n r -= d;\n }\n }\n return cost;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minimumChanges(string s, int k) {\n const int n = s.length();\n // factors[i] := factors of i\n const vector> factors = getFactors(n);\n // cost[i][j] := changes to make s[i..j] a semi-palindrome\n const vector> cost = getCost(s, n, factors);\n // dp[i][j] := the minimum changes to split s[i:] into j valid parts\n vector> dp(n + 1, vector(k + 1, n));\n\n dp[n][0] = 0;\n\n for (int i = n - 1; i >= 0; --i)\n for (int j = 1; j <= k; ++j)\n for (int l = i + 1; l < n; ++l)\n dp[i][j] = min(dp[i][j], dp[l + 1][j - 1] + cost[i][l]);\n\n return dp[0][k];\n }\n\n private:\n vector> getFactors(int n) {\n vector> factors(n + 1);\n for (int i = 1; i <= n; ++i)\n factors[i].push_back(1);\n for (int d = 2; d < n; ++d)\n for (int i = d * 2; i <= n; i += d)\n factors[i].push_back(d);\n return factors;\n }\n\n vector> getCost(const string& s, int n,\n const vector>& factors) {\n vector> cost(n, vector(n));\n for (int i = 0; i < n; ++i)\n for (int j = i + 1; j < n; ++j) {\n const int length = j - i + 1;\n int minCost = length;\n for (const int d : factors[length])\n minCost = min(minCost, getCost(s, i, j, d));\n cost[i][j] = minCost;\n }\n return cost;\n }\n\n // Returns the cost to make s[i..j] a semi-palindrome of `d`.\n int getCost(const string& s, int i, int j, int d) {\n int cost = 0;\n for (int offset = 0; offset < d; ++offset) {\n int l = i + offset;\n int r = j - d + 1 + offset;\n while (l < r) {\n if (s[l] != s[r])\n ++cost;\n l += d;\n r -= d;\n }\n }\n return cost;\n }\n};\n"} +{"task_num": 2932, "task_title": "Maximum Strong Pair XOR I", "difficulty": 1, "func_name": "maximumStrongPairXor", "description": "You are given a 0-indexed integer array `nums`. A pair of integers `x` and `y`\nis called a strong pair if it satisfies the condition:\n\n* `|x - y| <= min(x, y)`\n\nYou need to select two integers from `nums` such that they form a strong pair\nand their bitwise `XOR` is the maximum among all strong pairs in the array.\n\nReturn the maximum `XOR` value out of all possible strong pairs in the array\n`nums`.\n\nNote that you can pick the same integer twice to form a pair.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator, Optional\n\nclass TrieNode:\n def __init__(self):\n self.children: List[Optional[TrieNode]] = [None] * 2\n self.min = math.inf\n self.max = -math.inf\n\n\nclass BitTrie:\n def __init__(self, maxBit: int):\n self.maxBit = maxBit\n self.root = TrieNode()\n\n def insert(self, num: int) -> None:\n node = self.root\n for i in range(self.maxBit, -1, -1):\n bit = num >> i & 1\n if not node.children[bit]:\n node.children[bit] = TrieNode()\n node = node.children[bit]\n node.min = min(node.min, num)\n node.max = max(node.max, num)\n\n def getMaxXor(self, x: int) -> int:\n maxXor = 0\n node = self.root\n for i in range(self.maxBit, -1, -1):\n bit = x >> i & 1\n toggleBit = bit ^ 1\n if node.children[toggleBit] and node.children[toggleBit].max > x and node.children[toggleBit].min <= 2 * x:\n maxXor = maxXor | 1 << i\n node = node.children[toggleBit]\n elif node.children[bit]:\n node = node.children[bit]\n else:\n return 0\n return maxXor\n\n\nclass Solution:\n def maximumStrongPairXor(self, nums: List[int]) -> int:\n maxNum = max(nums)\n maxBit = int(math.log2(maxNum))\n bitTrie = BitTrie(maxBit)\n\n for num in nums:\n bitTrie.insert(num)\n\n return max(bitTrie.getMaxXor(num) for num in nums)\n", "java_solution": "class TrieNode {\n public TrieNode[] children = new TrieNode[2];\n public int mn = Integer.MAX_VALUE;\n public int mx = Integer.MIN_VALUE;\n}\n\nclass BitTrie {\n public BitTrie(int maxBit) {\n this.maxBit = maxBit;\n }\n\n public void insert(int num) {\n TrieNode node = root;\n for (int i = maxBit; i >= 0; --i) {\n final int bit = (int) (num >> i & 1);\n if (node.children[bit] == null)\n node.children[bit] = new TrieNode();\n node = node.children[bit];\n node.mn = Math.min(node.mn, num);\n node.mx = Math.max(node.mx, num);\n }\n }\n\n // Returns max(x ^ y), where |x - y| <= min(x, y).\n //\n // If x <= y, |x - y| <= min(x, y) can be written as y - x <= x.\n // So, y <= 2 * x.\n public int getMaxXor(int x) {\n int maxXor = 0;\n TrieNode node = root;\n for (int i = maxBit; i >= 0; --i) {\n final int bit = (int) (x >> i & 1);\n final int toggleBit = bit ^ 1;\n // If `node.children[toggleBit].mx > x`, it means there's a number in the\n // node that satisfies the condition to ensure that x <= y among x and y.\n // If `node.children[toggleBit].mn <= 2 * x`, it means there's a number\n // in the node that satisfies the condition for a valid y.\n if (node.children[toggleBit] != null && node.children[toggleBit].mx > x &&\n node.children[toggleBit].mn <= 2 * x) {\n maxXor = maxXor | 1 << i;\n node = node.children[toggleBit];\n } else if (node.children[bit] != null) {\n node = node.children[bit];\n } else { // There's nothing in the Bit Trie.\n return 0;\n }\n }\n return maxXor;\n }\n\n private int maxBit;\n private TrieNode root = new TrieNode();\n}\n\nclass Solution {\n // Similar to 421. Maximum XOR of Two Numbers in an Array\n public int maximumStrongPairXor(int[] nums) {\n final int maxNum = Arrays.stream(nums).max().getAsInt();\n final int maxBit = (int) (Math.log(maxNum) / Math.log(2));\n int ans = 0;\n BitTrie bitTrie = new BitTrie(maxBit);\n\n for (final int num : nums)\n bitTrie.insert(num);\n\n for (final int num : nums)\n ans = Math.max(ans, bitTrie.getMaxXor(num));\n\n return ans;\n }\n}\n", "cpp_solution": "struct TrieNode {\n vector> children;\n TrieNode() : children(2) {}\n int mn = INT_MAX;\n int mx = INT_MIN;\n};\n\nclass BitTrie {\n public:\n BitTrie(int maxBit) : maxBit(maxBit) {}\n\n void insert(int num) {\n shared_ptr node = root;\n for (int i = maxBit; i >= 0; --i) {\n const int bit = num >> i & 1;\n if (node->children[bit] == nullptr)\n node->children[bit] = make_shared();\n node = node->children[bit];\n node->mn = min(node->mn, num);\n node->mx = max(node->mx, num);\n }\n }\n\n // Returns max(x ^ y), where |x - y| <= min(x, y).\n //\n // If x <= y, |x - y| <= min(x, y) can be written as y - x <= x.\n // So, y <= 2 * x.\n int getMaxXor(int x) {\n int maxXor = 0;\n shared_ptr node = root;\n for (int i = maxBit; i >= 0; --i) {\n const int bit = x >> i & 1;\n const int toggleBit = bit ^ 1;\n // If `node.children[toggleBit].mx > x`, it means there's a number in the\n // node that satisfies the condition to ensure that x <= y among x and y.\n // If `node.children[toggleBit].mn <= 2 * x`, it means there's a number\n // in the node that satisfies the condition for a valid y.\n if (node->children[toggleBit] != nullptr &&\n node->children[toggleBit]->mx > x &&\n node->children[toggleBit]->mn <= 2 * x) {\n maxXor = maxXor | 1 << i;\n node = node->children[toggleBit];\n } else if (node->children[bit] != nullptr) {\n node = node->children[bit];\n } else { // There's nothing in the Bit Trie.\n return 0;\n }\n }\n return maxXor;\n }\n\n private:\n const int maxBit;\n shared_ptr root = make_shared();\n};\n\nclass Solution {\n public:\n // Similar to 421. Maximum XOR of Two Numbers in an Array\n int maximumStrongPairXor(vector& nums) {\n const int maxNum = ranges::max(nums);\n const int maxBit = static_cast(log2(maxNum));\n int ans = 0;\n BitTrie bitTrie(maxBit);\n\n for (const int num : nums)\n bitTrie.insert(num);\n\n for (const int num : nums)\n ans = max(ans, bitTrie.getMaxXor(num));\n\n return ans;\n }\n};\n"} +{"task_num": 2940, "task_title": "Find Building Where Alice and Bob Can Meet", "difficulty": 3, "func_name": "leftmostBuildingQueries", "description": "You are given a 0-indexed array `heights` of positive integers, where\n`heights[i]` represents the height of the `ith` building.\n\nIf a person is in building `i`, they can move to any other building `j` if and\nonly if `i < j` and `heights[i] < heights[j]`.\n\nYou are also given another array `queries` where `queries[i] = [ai, bi]`. On\nthe `ith` query, Alice is in building `ai` while Bob is in building `bi`.\n\nReturn an array `ans` where `ans[i]` is the index of the leftmost building\nwhere Alice and Bob can meet on the `ith` query. If Alice and Bob cannot move\nto a common building on query `i`, set `ans[i]` to `-1`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass IndexedQuery:\n def __init__(self, queryIndex: int, a: int, b: int):\n self.queryIndex = queryIndex\n self.a = a\n self.b = b\n\n def __iter__(self):\n yield self.queryIndex\n yield self.a\n yield self.b\n\n\nclass Solution:\n def leftmostBuildingQueries(self, heights: List[int], queries: List[List[int]]) -> List[int]:\n ans = [-1] * len(queries)\n stack = []\n\n heightsIndex = len(heights) - 1\n for queryIndex, a, b in sorted([IndexedQuery(i, min(a, b), max(a, b)) for i, (a, b) in enumerate(queries)], key=lambda iq: -iq.b):\n if a == b or heights[a] < heights[b]:\n ans[queryIndex] = b\n else:\n while heightsIndex > b:\n while stack and heights[stack[-1]] <= heights[heightsIndex]:\n stack.pop()\n stack.append(heightsIndex)\n heightsIndex -= 1\n j = self._lastGreater(stack, a, heights)\n if j != -1:\n ans[queryIndex] = stack[j]\n\n return ans\n\n def _lastGreater(self, A: List[int], target: int, heights: List[int]):\n l = -1\n r = len(A) - 1\n while l < r:\n m = (l + r + 1) // 2\n if heights[A[m]] > heights[target]:\n l = m\n else:\n r = m - 1\n return l\n", "java_solution": "class Solution {\n // Similar to 2736. Maximum Sum Queries\n public int[] leftmostBuildingQueries(int[] heights, int[][] queries) {\n IndexedQuery[] indexedQueries = getIndexedQueries(queries);\n int[] ans = new int[queries.length];\n Arrays.fill(ans, -1);\n // Store indices (heightsIndex) of heights with heights[heightsIndex] in\n // descending order.\n List stack = new ArrayList<>();\n\n // Iterate through queries and heights simultaneously.\n int heightsIndex = heights.length - 1;\n for (IndexedQuery indexedQuery : indexedQueries) {\n final int queryIndex = indexedQuery.queryIndex;\n final int a = indexedQuery.a;\n final int b = indexedQuery.b;\n if (a == b || heights[a] < heights[b]) {\n // 1. Alice and Bob are already in the same index (a == b) or\n // 2. Alice can jump from a -> b (heights[a] < heights[b]).\n ans[queryIndex] = b;\n } else {\n // Now, a < b and heights[a] >= heights[b].\n // Gradually add heights with an index > b to the monotonic stack.\n while (heightsIndex > b) {\n // heights[heightsIndex] is a better candidate, given that\n // heightsIndex is smaller than the indices in the stack and\n // heights[heightsIndex] is larger or equal to the heights mapped in\n // the stack.\n while (!stack.isEmpty() && heights[stack.get(stack.size() - 1)] <= heights[heightsIndex])\n stack.remove(stack.size() - 1);\n stack.add(heightsIndex--);\n }\n // Binary search to find the smallest index j such that j > b and\n // heights[j] > heights[a], thereby ensuring heights[t] > heights[b].\n final int j = lastGreater(stack, a, heights);\n if (j != -1)\n ans[queryIndex] = stack.get(j);\n }\n }\n\n return ans;\n }\n\n private record IndexedQuery(int queryIndex, int a, int b){};\n\n // Returns the last index i in A s.t. heights[A.get(i)] is > heights[target].\n private int lastGreater(List A, int target, int[] heights) {\n int l = -1;\n int r = A.size() - 1;\n while (l < r) {\n final int m = (l + r + 1) / 2;\n if (heights[A.get(m)] > heights[target])\n l = m;\n else\n r = m - 1;\n }\n return l;\n }\n\n private IndexedQuery[] getIndexedQueries(int[][] queries) {\n IndexedQuery[] indexedQueries = new IndexedQuery[queries.length];\n for (int i = 0; i < queries.length; ++i) {\n // Make sure that a <= b.\n final int a = Math.min(queries[i][0], queries[i][1]);\n final int b = Math.max(queries[i][0], queries[i][1]);\n indexedQueries[i] = new IndexedQuery(i, a, b);\n }\n Arrays.sort(indexedQueries, Comparator.comparing(IndexedQuery::b, Comparator.reverseOrder()));\n return indexedQueries;\n }\n}\n", "cpp_solution": "struct IndexedQuery {\n int queryIndex;\n int a; // Alice's index\n int b; // Bob's index\n};\n\nclass Solution {\n public:\n // Similar to 2736. Maximum Sum Queries\n vector leftmostBuildingQueries(vector& heights,\n vector>& queries) {\n vector ans(queries.size(), -1);\n // Store indices (heightsIndex) of heights with heights[heightsIndex] in\n // descending order.\n vector stack;\n\n // Iterate through queries and heights simultaneously.\n int heightsIndex = heights.size() - 1;\n for (const auto& [queryIndex, a, b] : getIndexedQueries(queries)) {\n if (a == b || heights[a] < heights[b]) {\n // 1. Alice and Bob are already in the same index (a == b) or\n // 2. Alice can jump from a -> b (heights[a] < heights[b]).\n ans[queryIndex] = b;\n } else {\n // Now, a < b and heights[a] >= heights[b].\n // Gradually add heights with an index > b to the monotonic stack.\n while (heightsIndex > b) {\n // heights[heightsIndex] is a better candidate, given that\n // heightsIndex is smaller than the indices in the stack and\n // heights[heightsIndex] is larger or equal to the heights mapped in\n // the stack.\n while (!stack.empty() &&\n heights[stack.back()] <= heights[heightsIndex])\n stack.pop_back();\n stack.push_back(heightsIndex--);\n }\n // Binary search to find the smallest index j such that j > b and\n // heights[j] > heights[a], thereby ensuring heights[j] > heights[b].\n if (const auto it = upper_bound(\n stack.rbegin(), stack.rend(), a,\n [&](int a, int b) { return heights[a] < heights[b]; });\n it != stack.rend())\n ans[queryIndex] = *it;\n }\n }\n\n return ans;\n }\n\n private:\n vector getIndexedQueries(const vector>& queries) {\n vector indexedQueries;\n for (int i = 0; i < queries.size(); ++i) {\n // Make sure that a <= b.\n const int a = min(queries[i][0], queries[i][1]);\n const int b = max(queries[i][0], queries[i][1]);\n indexedQueries.push_back({i, a, b});\n }\n ranges::sort(\n indexedQueries,\n [](const IndexedQuery& a, const IndexedQuery& b) { return a.b > b.b; });\n return indexedQueries;\n }\n};\n"} +{"task_num": 2948, "task_title": "Make Lexicographically Smallest Array by Swapping Elements", "difficulty": 2, "func_name": "lexicographicallySmallestArray", "description": "You are given a 0-indexed array of positive integers `nums` and a positive\ninteger `limit`.\n\nIn one operation, you can choose any two indices `i` and `j` and swap\n`nums[i]` and `nums[j]` if `|nums[i] - nums[j]| <= limit`.\n\nReturn the lexicographically smallest array that can be obtained by performing\nthe operation any number of times.\n\nAn array `a` is lexicographically smaller than an array `b` if in the first\nposition where `a` and `b` differ, array `a` has an element that is less than\nthe corresponding element in `b`. For example, the array `[2,10,3]` is\nlexicographically smaller than the array `[10,2,3]` because they differ at\nindex `0` and `2 < 10`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]:\n ans = [0] * len(nums)\n numAndIndexes = sorted([(num, i) for i, num in enumerate(nums)])\n numAndIndexesGroups: List[List[Tuple[int, int]]] = []\n\n for numAndIndex in numAndIndexes:\n if not numAndIndexesGroups or numAndIndex[0] - numAndIndexesGroups[-1][-1][0] > limit:\n numAndIndexesGroups.append([numAndIndex])\n else:\n numAndIndexesGroups[-1].append(numAndIndex)\n\n for numAndIndexesGroup in numAndIndexesGroups:\n sortedNums = [num for num, _ in numAndIndexesGroup]\n sortedIndices = sorted([index for _, index in numAndIndexesGroup])\n for num, index in zip(sortedNums, sortedIndices):\n ans[index] = num\n\n return ans\n", "java_solution": "class Solution {\n public int[] lexicographicallySmallestArray(int[] nums, int limit) {\n int[] ans = new int[nums.length];\n List>> numAndIndexesGroups = new ArrayList<>();\n\n for (Pair numAndIndex : getNumAndIndexes(nums))\n if (numAndIndexesGroups.isEmpty() ||\n numAndIndex.getKey() -\n numAndIndexesGroups.get(numAndIndexesGroups.size() - 1)\n .get(numAndIndexesGroups.get(numAndIndexesGroups.size() - 1).size() - 1)\n .getKey() >\n limit) {\n // Start a new group.\n numAndIndexesGroups.add(new ArrayList<>(List.of(numAndIndex)));\n } else {\n // Append to the existing group.\n numAndIndexesGroups.get(numAndIndexesGroups.size() - 1).add(numAndIndex);\n }\n\n for (List> numAndIndexesGroup : numAndIndexesGroups) {\n List sortedNums = new ArrayList<>();\n List sortedIndices = new ArrayList<>();\n for (Pair pair : numAndIndexesGroup) {\n sortedNums.add(pair.getKey());\n sortedIndices.add(pair.getValue());\n }\n sortedIndices.sort(null);\n for (int i = 0; i < sortedNums.size(); ++i) {\n ans[sortedIndices.get(i)] = sortedNums.get(i);\n }\n }\n\n return ans;\n }\n\n private Pair[] getNumAndIndexes(int[] nums) {\n Pair[] numAndIndexes = new Pair[nums.length];\n for (int i = 0; i < nums.length; ++i)\n numAndIndexes[i] = new Pair<>(nums[i], i);\n Arrays.sort(numAndIndexes, Comparator.comparingInt(Pair::getKey));\n return numAndIndexes;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector lexicographicallySmallestArray(vector& nums, int limit) {\n vector ans(nums.size());\n // [[(num, index)]], where the difference between in each pair in each\n // `[(num, index)]` group <= `limit`\n vector>> numAndIndexesGroups;\n\n for (const pair& numAndIndex : getNumAndIndexes(nums))\n if (numAndIndexesGroups.empty() ||\n numAndIndex.first - numAndIndexesGroups.back().back().first > limit) {\n // Start a new group.\n numAndIndexesGroups.push_back({numAndIndex});\n } else {\n // Append to the existing group.\n numAndIndexesGroups.back().push_back(numAndIndex);\n }\n\n for (const vector>& numAndIndexesGroup :\n numAndIndexesGroups) {\n vector sortedNums;\n vector sortedIndices;\n for (const auto& [num, index] : numAndIndexesGroup) {\n sortedNums.push_back(num);\n sortedIndices.push_back(index);\n }\n ranges::sort(sortedIndices);\n for (int i = 0; i < sortedNums.size(); ++i)\n ans[sortedIndices[i]] = sortedNums[i];\n }\n\n return ans;\n }\n\n private:\n vector> getNumAndIndexes(const vector& nums) {\n vector> numAndIndexes;\n for (int i = 0; i < nums.size(); ++i)\n numAndIndexes.emplace_back(nums[i], i);\n ranges::sort(numAndIndexes);\n return numAndIndexes;\n }\n};\n"} +{"task_num": 2953, "task_title": "Count Complete Substrings", "difficulty": 3, "func_name": "countCompleteSubstrings", "description": "You are given a string `word` and an integer `k`.\n\nA substring `s` of `word` is complete if:\n\n* Each character in `s` occurs exactly `k` times.\n* The difference between two adjacent characters is at most `2`. That is, for any two adjacent characters `c1` and `c2` in `s`, the absolute difference in their positions in the alphabet is at most `2`.\n\nReturn the number of complete substrings of `word`.\n\nA substring is a non-empty contiguous sequence of characters in a string.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def countCompleteSubstrings(self, word: str, k: int) -> int:\n uniqueLetters = len(set(word))\n return sum(self._countCompleteStrings(word, k, windowSize) for windowSize in range(k, k * uniqueLetters + 1, k))\n\n def _countCompleteStrings(self, word: str, k: int, windowSize: int) -> int:\n res = 0\n countLetters = 0\n count = collections.Counter()\n\n for i, c in enumerate(word):\n count[c] += 1\n countLetters += 1\n if i > 0 and abs(ord(c) - ord(word[i - 1])) > 2:\n count = collections.Counter()\n count[c] += 1\n countLetters = 1\n if countLetters == windowSize + 1:\n count[word[i - windowSize]] -= 1\n countLetters -= 1\n if countLetters == windowSize:\n res += all(freq == 0 or freq == k for freq in count.values())\n\n return res\n", "java_solution": "class Solution {\n public int countCompleteSubstrings(String word, int k) {\n final int uniqueLetters = word.chars().boxed().collect(Collectors.toSet()).size();\n int ans = 0;\n\n for (int windowSize = k; windowSize <= k * uniqueLetters && windowSize <= word.length();\n windowSize += k) {\n ans += countCompleteStrings(word, k, windowSize);\n }\n\n return ans;\n }\n\n // Returns the number of complete substrings of `windowSize` of `word`.\n private int countCompleteStrings(final String word, int k, int windowSize) {\n int res = 0;\n int countLetters = 0; // the number of letters in the running substring\n int[] count = new int[26];\n\n for (int i = 0; i < word.length(); ++i) {\n ++count[word.charAt(i) - 'a'];\n ++countLetters;\n if (i > 0 && Math.abs(word.charAt(i) - word.charAt(i - 1)) > 2) {\n count = new int[26];\n // Start a new substring starting at word[i].\n ++count[word.charAt(i) - 'a'];\n countLetters = 1;\n }\n if (countLetters == windowSize + 1) {\n --count[word.charAt(i - windowSize) - 'a'];\n --countLetters;\n }\n if (countLetters == windowSize)\n res += Arrays.stream(count).allMatch(freq -> freq == 0 || freq == k) ? 1 : 0;\n }\n\n return res;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int countCompleteSubstrings(string word, int k) {\n const int uniqueLetters =\n unordered_set{word.begin(), word.end()}.size();\n int ans = 0;\n\n for (int windowSize = k;\n windowSize <= k * uniqueLetters && windowSize <= word.length();\n windowSize += k)\n ans += countCompleteStrings(word, k, windowSize);\n\n return ans;\n }\n\n private:\n // Returns the number of complete substrings of `windowSize` of `word`.\n int countCompleteStrings(const string& word, int k, int windowSize) {\n int res = 0;\n int countLetters = 0; // the number of letters in the running substring\n vector count(26);\n\n for (int i = 0; i < word.length(); ++i) {\n ++count[word[i] - 'a'];\n ++countLetters;\n if (i > 0 && abs(word[i] - word[i - 1]) > 2) {\n count = vector(26);\n // Start a new substring starting at word[i].\n ++count[word[i] - 'a'];\n countLetters = 1;\n }\n if (countLetters == windowSize + 1) {\n --count[word[i - windowSize] - 'a'];\n --countLetters;\n }\n if (countLetters == windowSize)\n res += ranges::all_of(count,\n [k](int freq) { return freq == 0 || freq == k; })\n ? 1\n : 0;\n }\n\n return res;\n }\n};\n"} +{"task_num": 2959, "task_title": "Number of Possible Sets of Closing Branches", "difficulty": 3, "func_name": "numberOfSets", "description": "There is a company with `n` branches across the country, some of which are\nconnected by roads. Initially, all branches are reachable from each other by\ntraveling some roads.\n\nThe company has realized that they are spending an excessive amount of time\ntraveling between their branches. As a result, they have decided to close down\nsome of these branches (possibly none). However, they want to ensure that the\nremaining branches have a distance of at most `maxDistance` from each other.\n\nThe distance between two branches is the minimum total traveled length needed\nto reach one branch from another.\n\nYou are given integers `n`, `maxDistance`, and a 0-indexed 2D array `roads`,\nwhere `roads[i] = [ui, vi, wi]` represents the undirected road between\nbranches `ui` and `vi` with length `wi`.\n\nReturn the number of possible sets of closing branches, so that any branch has\na distance of at most `maxDistance` from any other.\n\nNote that, after closing a branch, the company will no longer have access to\nany roads connected to it.\n\nNote that, multiple roads are allowed.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def numberOfSets(self, n: int, maxDistance: int, roads: List[List[int]]) -> int:\n return sum(self._floydWarshall(n, maxDistance, roads, mask) <= maxDistance for mask in range(1 << n))\n\n def _floydWarshall(self, n: int, maxDistanceThreshold: int, roads: List[List[int]], mask: int) -> List[List[int]]:\n maxDistance = 0\n dist = [[maxDistanceThreshold + 1] * n for _ in range(n)]\n\n for i in range(n):\n if mask >> i & 1:\n dist[i][i] = 0\n\n for u, v, w in roads:\n if mask >> u & 1 and mask >> v & 1:\n dist[u][v] = min(dist[u][v], w)\n dist[v][u] = min(dist[v][u], w)\n\n for k in range(n):\n if mask >> k & 1:\n for i in range(n):\n if mask >> i & 1:\n for j in range(n):\n if mask >> j & 1:\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n\n for i in range(n):\n if mask >> i & 1:\n for j in range(i + 1, n):\n if mask >> j & 1:\n maxDistance = max(maxDistance, dist[i][j])\n\n return maxDistance\n", "java_solution": "class Solution {\n public int numberOfSets(int n, int maxDistance, int[][] roads) {\n final int maxMask = 1 << n;\n int ans = 0;\n\n for (int mask = 0; mask < maxMask; ++mask)\n if (floydWarshall(n, maxDistance, roads, mask) <= maxDistance)\n ++ans;\n\n return ans;\n }\n\n private int floydWarshall(int n, int maxDistanceThreshold, int[][] roads, int mask) {\n int maxDistance = 0;\n int[][] dist = new int[n][n];\n Arrays.stream(dist).forEach(A -> Arrays.fill(A, maxDistanceThreshold + 1));\n\n for (int i = 0; i < n; ++i)\n if ((mask >> i & 1) == 1)\n dist[i][i] = 0;\n\n for (int[] road : roads) {\n final int u = road[0];\n final int v = road[1];\n final int w = road[2];\n if ((mask >> u & 1) == 1 && (mask >> v & 1) == 1) {\n dist[u][v] = Math.min(dist[u][v], w);\n dist[v][u] = Math.min(dist[v][u], w);\n }\n }\n\n for (int k = 0; k < n; ++k)\n if ((mask >> k & 1) == 1)\n for (int i = 0; i < n; ++i)\n if ((mask >> i & 1) == 1)\n for (int j = 0; j < n; ++j)\n if ((mask >> j & 1) == 1)\n dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);\n\n for (int i = 0; i < n; ++i)\n if ((mask >> i & 1) == 1)\n for (int j = i + 1; j < n; ++j)\n if ((mask >> j & 1) == 1)\n maxDistance = Math.max(maxDistance, dist[i][j]);\n\n return maxDistance;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int numberOfSets(int n, int maxDistance, vector>& roads) {\n const int maxMask = 1 << n;\n int ans = 0;\n\n for (int mask = 0; mask < maxMask; ++mask)\n if (floydWarshall(n, maxDistance, roads, mask) <= maxDistance)\n ++ans;\n\n return ans;\n }\n\n private:\n // Returns the maximum distance between any two branches, where the mask\n // represents the selected branches.\n int floydWarshall(int n, int maxDistanceThreshold, vector>& roads,\n int mask) {\n int maxDistance = 0;\n vector> dist(n, vector(n, maxDistanceThreshold + 1));\n\n for (int i = 0; i < n; ++i)\n if (mask >> i & 1)\n dist[i][i] = 0;\n\n for (const vector& road : roads) {\n const int u = road[0];\n const int v = road[1];\n const int w = road[2];\n if (mask >> u & 1 && mask >> v & 1) {\n dist[u][v] = min(dist[u][v], w);\n dist[v][u] = min(dist[v][u], w);\n }\n }\n\n for (int k = 0; k < n; ++k)\n if (mask >> k & 1)\n for (int i = 0; i < n; ++i)\n if (mask >> i & 1)\n for (int j = 0; j < n; ++j)\n if (mask >> j & 1)\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n\n for (int i = 0; i < n; ++i)\n if (mask >> i & 1)\n for (int j = i + 1; j < n; ++j)\n if (mask >> j & 1)\n maxDistance = max(maxDistance, dist[i][j]);\n\n return maxDistance;\n }\n};\n"} +{"task_num": 2973, "task_title": "Find Number of Coins to Place in Tree Nodes", "difficulty": 3, "func_name": "placedCoins", "description": "You are given an undirected tree with `n` nodes labeled from `0` to `n - 1`,\nand rooted at node `0`. You are given a 2D integer array `edges` of length `n\n- 1`, where `edges[i] = [ai, bi]` indicates that there is an edge between\nnodes `ai` and `bi` in the tree.\n\nYou are also given a 0-indexed integer array `cost` of length `n`, where\n`cost[i]` is the cost assigned to the `ith` node.\n\nYou need to place some coins on every node of the tree. The number of coins to\nbe placed at node `i` can be calculated as:\n\n* If size of the subtree of node `i` is less than `3`, place `1` coin.\n* Otherwise, place an amount of coins equal to the maximum product of cost values assigned to `3` distinct nodes in the subtree of node `i`. If this product is negative, place `0` coins.\n\nReturn an array `coin` of size `n` such that `coin[i]` is the number of coins\nplaced at node `i`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass ChildCost:\n def __init__(self, cost: int):\n self.numNodes = 1\n self.maxPosCosts = [cost] if cost > 0 else []\n self.minNegCosts = [cost] if cost < 0 else []\n\n def update(self, childCost: 'ChildCost') -> None:\n self.numNodes += childCost.numNodes\n self.maxPosCosts.extend(childCost.maxPosCosts)\n self.minNegCosts.extend(childCost.minNegCosts)\n self.maxPosCosts.sort(reverse=True)\n self.minNegCosts.sort()\n self.maxPosCosts = self.maxPosCosts[:3]\n self.minNegCosts = self.minNegCosts[:2]\n\n def maxProduct(self) -> int:\n if self.numNodes < 3:\n return 1\n if not self.maxPosCosts:\n return 0\n res = 0\n if len(self.maxPosCosts) == 3:\n res = self.maxPosCosts[0] * self.maxPosCosts[1] * self.maxPosCosts[2]\n if len(self.minNegCosts) == 2:\n res = max(res, self.minNegCosts[0] * self.minNegCosts[1] * self.maxPosCosts[0])\n return res\n\n\nclass Solution:\n def placedCoins(self, edges: List[List[int]], cost: List[int]) -> List[int]:\n n = len(cost)\n ans = [0] * n\n tree = [[] for _ in range(n)]\n\n for u, v in edges:\n tree[u].append(v)\n tree[v].append(u)\n\n def dfs(u: int, prev: int) -> None:\n res = ChildCost(cost[u])\n for v in tree[u]:\n if v != prev:\n res.update(dfs(v, u))\n ans[u] = res.maxProduct()\n return res\n\n dfs(0, -1)\n return ans\n", "java_solution": "class ChildCost {\n public ChildCost(int cost) {\n if (cost > 0)\n maxPosCosts.add(cost);\n else\n minNegCosts.add(cost);\n }\n\n public void update(ChildCost childCost) {\n numNodes += childCost.numNodes;\n maxPosCosts.addAll(childCost.maxPosCosts);\n minNegCosts.addAll(childCost.minNegCosts);\n maxPosCosts.sort(Comparator.reverseOrder());\n minNegCosts.sort(Comparator.naturalOrder());\n if (maxPosCosts.size() > 3)\n maxPosCosts = maxPosCosts.subList(0, 3);\n if (minNegCosts.size() > 2)\n minNegCosts = minNegCosts.subList(0, 2);\n }\n\n public long maxProduct() {\n if (numNodes < 3)\n return 1;\n if (maxPosCosts.isEmpty())\n return 0;\n long res = 0;\n if (maxPosCosts.size() == 3)\n res = (long) maxPosCosts.get(0) * maxPosCosts.get(1) * maxPosCosts.get(2);\n if (minNegCosts.size() == 2)\n res = Math.max(res, (long) minNegCosts.get(0) * minNegCosts.get(1) * maxPosCosts.get(0));\n return res;\n }\n\n private int numNodes = 1;\n private List maxPosCosts = new ArrayList<>();\n private List minNegCosts = new ArrayList<>();\n}\n\nclass Solution {\n public long[] placedCoins(int[][] edges, int[] cost) {\n final int n = cost.length;\n long[] ans = new long[n];\n List[] tree = new List[n];\n\n for (int i = 0; i < n; i++)\n tree[i] = new ArrayList<>();\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n tree[u].add(v);\n tree[v].add(u);\n }\n\n dfs(tree, 0, /*prev=*/-1, cost, ans);\n return ans;\n }\n\n private ChildCost dfs(List[] tree, int u, int prev, int[] cost, long[] ans) {\n ChildCost res = new ChildCost(cost[u]);\n for (final int v : tree[u])\n if (v != prev)\n res.update(dfs(tree, v, u, cost, ans));\n ans[u] = res.maxProduct();\n return res;\n }\n}\n", "cpp_solution": "class ChildCost {\n public:\n ChildCost(int cost) {\n numNodes = 1;\n if (cost > 0)\n maxPosCosts.push_back(cost);\n else\n minNegCosts.push_back(cost);\n }\n\n void update(ChildCost childCost) {\n numNodes += childCost.numNodes;\n ranges::copy(childCost.maxPosCosts, back_inserter(maxPosCosts));\n ranges::copy(childCost.minNegCosts, back_inserter(minNegCosts));\n ranges::sort(maxPosCosts, greater());\n ranges::sort(minNegCosts);\n maxPosCosts.resize(min(static_cast(maxPosCosts.size()), 3));\n minNegCosts.resize(min(static_cast(minNegCosts.size()), 2));\n }\n\n long maxProduct() {\n if (numNodes < 3)\n return 1;\n if (maxPosCosts.empty())\n return 0;\n long res = 0;\n if (maxPosCosts.size() == 3)\n res = static_cast(maxPosCosts[0]) * maxPosCosts[1] * maxPosCosts[2];\n if (minNegCosts.size() == 2)\n res = max(res, static_cast(minNegCosts[0]) * minNegCosts[1] *\n maxPosCosts[0]);\n return res;\n }\n\n private:\n int numNodes;\n vector maxPosCosts;\n vector minNegCosts;\n};\n\nclass Solution {\n public:\n vector placedCoins(vector>& edges, vector& cost) {\n const int n = cost.size();\n vector ans(n);\n vector> tree(n);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n tree[u].push_back(v);\n tree[v].push_back(u);\n }\n\n dfs(tree, 0, /*prev=*/-1, cost, ans);\n return ans;\n }\n\n private:\n ChildCost dfs(const vector>& tree, int u, int prev,\n const vector& cost, vector& ans) {\n ChildCost res(cost[u]);\n for (const int v : tree[u])\n if (v != prev)\n res.update(dfs(tree, v, u, cost, ans));\n ans[u] = res.maxProduct();\n return res;\n }\n};\n"} +{"task_num": 2976, "task_title": "Minimum Cost to Convert String I", "difficulty": 2, "func_name": "minimumCost", "description": "You are given two 0-indexed strings `source` and `target`, both of length `n`\nand consisting of lowercase English letters. You are also given two 0-indexed\ncharacter arrays `original` and `changed`, and an integer array `cost`, where\n`cost[i]` represents the cost of changing the character `original[i]` to the\ncharacter `changed[i]`.\n\nYou start with the string `source`. In one operation, you can pick a character\n`x` from the string and change it to the character `y` at a cost of `z` if\nthere exists any index `j` such that `cost[j] == z`, `original[j] == x`, and\n`changed[j] == y`.\n\nReturn the minimum cost to convert the string `source` to the string `target`\nusing any number of operations. If it is impossible to convert `source` to\n`target`, return `-1`.\n\nNote that there may exist indices `i`, `j` such that `original[j] ==\noriginal[i]` and `changed[j] == changed[i]`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumCost(self, source: str, target: str, original: List[str], changed: List[str], cost: List[int]) -> int:\n ans = 0\n dist = [[math.inf] * 26 for _ in range(26)]\n\n for a, b, c in zip(original, changed, cost):\n u = ord(a) - ord('a')\n v = ord(b) - ord('a')\n dist[u][v] = min(dist[u][v], c)\n\n for k in range(26):\n for i in range(26):\n if dist[i][k] < math.inf:\n for j in range(26):\n if dist[k][j] < math.inf:\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n\n for s, t in zip(source, target):\n if s == t:\n continue\n u = ord(s) - ord('a')\n v = ord(t) - ord('a')\n if dist[u][v] == math.inf:\n return -1\n ans += dist[u][v]\n\n return ans\n", "java_solution": "class Solution {\n public long minimumCost(String source, String target, char[] original, char[] changed,\n int[] cost) {\n long ans = 0;\n // dist[u][v] := the minimum distance to change ('a' + u) to ('a' + v)\n long[][] dist = new long[26][26];\n Arrays.stream(dist).forEach(A -> Arrays.fill(A, Long.MAX_VALUE));\n\n for (int i = 0; i < cost.length; ++i) {\n final int u = original[i] - 'a';\n final int v = changed[i] - 'a';\n dist[u][v] = Math.min(dist[u][v], cost[i]);\n }\n\n for (int k = 0; k < 26; ++k)\n for (int i = 0; i < 26; ++i)\n if (dist[i][k] < Long.MAX_VALUE)\n for (int j = 0; j < 26; ++j)\n if (dist[k][j] < Long.MAX_VALUE)\n dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);\n\n for (int i = 0; i < source.length(); ++i) {\n if (source.charAt(i) == target.charAt(i))\n continue;\n final int u = source.charAt(i) - 'a';\n final int v = target.charAt(i) - 'a';\n if (dist[u][v] == Long.MAX_VALUE)\n return -1;\n ans += dist[u][v];\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n long long minimumCost(string source, string target, vector& original,\n vector& changed, vector& cost) {\n long ans = 0;\n // dist[u][v] := the minimum distance to change ('a' + u) to ('a' + v)\n vector> dist(26, vector(26, LONG_MAX));\n\n for (int i = 0; i < cost.size(); ++i) {\n const int u = original[i] - 'a';\n const int v = changed[i] - 'a';\n dist[u][v] = min(dist[u][v], static_cast(cost[i]));\n }\n\n for (int k = 0; k < 26; ++k)\n for (int i = 0; i < 26; ++i)\n if (dist[i][k] < LONG_MAX)\n for (int j = 0; j < 26; ++j)\n if (dist[k][j] < LONG_MAX)\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n\n for (int i = 0; i < source.length(); ++i) {\n if (source[i] == target[i])\n continue;\n const int u = source[i] - 'a';\n const int v = target[i] - 'a';\n if (dist[u][v] == LONG_MAX)\n return -1;\n ans += dist[u][v];\n }\n\n return ans;\n }\n};\n"} +{"task_num": 2977, "task_title": "Minimum Cost to Convert String II", "difficulty": 3, "func_name": "minimumCost", "description": "You are given two 0-indexed strings `source` and `target`, both of length `n`\nand consisting of lowercase English characters. You are also given two\n0-indexed string arrays `original` and `changed`, and an integer array `cost`,\nwhere `cost[i]` represents the cost of converting the string `original[i]` to\nthe string `changed[i]`.\n\nYou start with the string `source`. In one operation, you can pick a substring\n`x` from the string, and change it to `y` at a cost of `z` if there exists any\nindex `j` such that `cost[j] == z`, `original[j] == x`, and `changed[j] == y`.\nYou are allowed to do any number of operations, but any pair of operations\nmust satisfy either of these two conditions:\n\n* The substrings picked in the operations are `source[a..b]` and `source[c..d]` with either `b < c` or `d < a`. In other words, the indices picked in both operations are disjoint.\n* The substrings picked in the operations are `source[a..b]` and `source[c..d]` with `a == c` and `b == d`. In other words, the indices picked in both operations are identical.\n\nReturn the minimum cost to convert the string `source` to the string `target`\nusing any number of operations. If it is impossible to convert `source` to\n`target`, return `-1`.\n\nNote that there may exist indices `i`, `j` such that `original[j] ==\noriginal[i]` and `changed[j] == changed[i]`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumCost(self, source: str, target: str, original: List[str], changed: List[str], cost: List[int]) -> int:\n subLengths = set(len(s) for s in original)\n subToId = self._getSubToId(original, changed)\n subCount = len(subToId)\n dist = [[math.inf for _ in range(subCount)] for _ in range(subCount)]\n dp = [math.inf for _ in range(len(source) + 1)]\n\n for a, b, c in zip(original, changed, cost):\n u = subToId[a]\n v = subToId[b]\n dist[u][v] = min(dist[u][v], c)\n\n for k in range(subCount):\n for i in range(subCount):\n if dist[i][k] < math.inf:\n for j in range(subCount):\n if dist[k][j] < math.inf:\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n\n dp[0] = 0\n\n for i, (s, t) in enumerate(zip(source, target)):\n if dp[i] == math.inf:\n continue\n if s == t:\n dp[i + 1] = min(dp[i + 1], dp[i])\n for subLength in subLengths:\n if i + subLength > len(source):\n continue\n subSource = source[i:i + subLength]\n subTarget = target[i:i + subLength]\n if subSource not in subToId or subTarget not in subToId:\n continue\n u = subToId[subSource]\n v = subToId[subTarget]\n if dist[u][v] != math.inf:\n dp[i + subLength] = min(dp[i + subLength], dp[i] + dist[u][v])\n\n if dp[len(source)] == math.inf:\n return -1\n else:\n return dp[len(source)]\n\n def _getSubToId(self, original: str, changed: str) -> Dict[str, int]:\n subToId = {}\n for s in original + changed:\n if s not in subToId:\n subToId[s] = len(subToId)\n return subToId\n", "java_solution": "class Solution {\n public long minimumCost(String source, String target, String[] original, String[] changed,\n int[] cost) {\n Set subLengths = getSubLengths(original);\n Map subToId = getSubToId(original, changed);\n final int subCount = subToId.size();\n // dist[u][v] := the minimum distance to change the substring with id u to\n // the substring with id v\n long[][] dist = new long[subCount][subCount];\n Arrays.stream(dist).forEach(A -> Arrays.fill(A, Long.MAX_VALUE));\n // dp[i] := the minimum cost to change the first i letters of `source` into\n // `target`, leaving the suffix untouched\n long[] dp = new long[source.length() + 1];\n Arrays.fill(dp, Long.MAX_VALUE);\n\n for (int i = 0; i < cost.length; ++i) {\n final int u = subToId.get(original[i]);\n final int v = subToId.get(changed[i]);\n dist[u][v] = Math.min(dist[u][v], (long) cost[i]);\n }\n\n for (int k = 0; k < subCount; ++k)\n for (int i = 0; i < subCount; ++i)\n if (dist[i][k] < Long.MAX_VALUE)\n for (int j = 0; j < subCount; ++j)\n if (dist[k][j] < Long.MAX_VALUE)\n dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);\n\n dp[0] = 0;\n\n for (int i = 0; i < source.length(); ++i) {\n if (dp[i] == Long.MAX_VALUE)\n continue;\n if (target.charAt(i) == source.charAt(i))\n dp[i + 1] = Math.min(dp[i + 1], dp[i]);\n for (int subLength : subLengths) {\n if (i + subLength > source.length())\n continue;\n String subSource = source.substring(i, i + subLength);\n String subTarget = target.substring(i, i + subLength);\n if (!subToId.containsKey(subSource) || !subToId.containsKey(subTarget))\n continue;\n final int u = subToId.get(subSource);\n final int v = subToId.get(subTarget);\n if (dist[u][v] < Long.MAX_VALUE)\n dp[i + subLength] = Math.min(dp[i + subLength], dp[i] + dist[u][v]);\n }\n }\n\n return dp[source.length()] == Long.MAX_VALUE ? -1 : dp[source.length()];\n }\n\n private Map getSubToId(String[] original, String[] changed) {\n Map subToId = new HashMap<>();\n for (final String s : original)\n subToId.putIfAbsent(s, subToId.size());\n for (final String s : changed)\n subToId.putIfAbsent(s, subToId.size());\n return subToId;\n }\n\n private Set getSubLengths(String[] original) {\n Set subLengths = new HashSet<>();\n for (final String s : original)\n subLengths.add(s.length());\n return subLengths;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n long long minimumCost(string source, string target, vector& original,\n vector& changed, vector& cost) {\n const unordered_set subLengths = getSubLengths(original);\n const unordered_map subToId = getSubToId(original, changed);\n const int subCount = subToId.size();\n // dist[u][v] := the minimum distance to change the substring with id u to\n // the substring with id v\n vector> dist(subCount, vector(subCount, LONG_MAX));\n // dp[i] := the minimum cost to change the first i letters of `source` into\n // `target`, leaving the suffix untouched\n vector dp(source.length() + 1, LONG_MAX);\n\n for (int i = 0; i < cost.size(); ++i) {\n const int u = subToId.at(original[i]);\n const int v = subToId.at(changed[i]);\n dist[u][v] = min(dist[u][v], static_cast(cost[i]));\n }\n\n for (int k = 0; k < subCount; ++k)\n for (int i = 0; i < subCount; ++i)\n if (dist[i][k] < LONG_MAX)\n for (int j = 0; j < subCount; ++j)\n if (dist[k][j] < LONG_MAX)\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n\n dp[0] = 0;\n\n for (int i = 0; i < source.length(); ++i) {\n if (dp[i] == LONG_MAX)\n continue;\n if (target[i] == source[i])\n dp[i + 1] = min(dp[i + 1], dp[i]);\n for (const int subLength : subLengths) {\n if (i + subLength > source.length())\n continue;\n const string subSource = source.substr(i, subLength);\n const string subTarget = target.substr(i, subLength);\n if (!subToId.contains(subSource) || !subToId.contains(subTarget))\n continue;\n const int u = subToId.at(subSource);\n const int v = subToId.at(subTarget);\n if (dist[u][v] < LONG_MAX)\n dp[i + subLength] = min(dp[i + subLength], dp[i] + dist[u][v]);\n }\n }\n\n return dp[source.length()] == LONG_MAX ? -1 : dp[source.length()];\n }\n\n private:\n unordered_map getSubToId(const vector& original,\n const vector& changed) {\n unordered_map subToId;\n for (const string& s : original)\n if (!subToId.contains(s))\n subToId[s] = subToId.size();\n for (const string& s : changed)\n if (!subToId.contains(s))\n subToId[s] = subToId.size();\n return subToId;\n }\n\n unordered_set getSubLengths(const vector& original) {\n unordered_set subLengths;\n for (const string& s : original)\n subLengths.insert(s.length());\n return subLengths;\n }\n};\n"} +{"task_num": 2983, "task_title": "Palindrome Rearrangement Queries", "difficulty": 3, "func_name": "canMakePalindromeQueries", "description": "You are given a 0-indexed string `s` having an even length `n`.\n\nYou are also given a 0-indexed 2D integer array, `queries`, where `queries[i]\n= [ai, bi, ci, di]`.\n\nFor each query `i`, you are allowed to perform the following operations:\n\n* Rearrange the characters within the substring `s[ai:bi]`, where `0 <= ai <= bi < n / 2`.\n* Rearrange the characters within the substring `s[ci:di]`, where `n / 2 <= ci <= di < n`.\n\nFor each query, your task is to determine whether it is possible to make `s` a\npalindrome by performing the operations.\n\nEach query is answered independently of the others.\n\nReturn a 0-indexed array `answer`, where `answer[i] == true` if it is possible\nto make `s` a palindrome by performing operations specified by the `ith`\nquery, and `false` otherwise.\n\n* A substring is a contiguous sequence of characters within a string.\n* `s[x:y]` represents the substring consisting of characters from the index `x` to index `y` in `s`, both inclusive.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def canMakePalindromeQueries(self, s: str, queries: List[List[int]]) -> List[bool]:\n n = len(s)\n mirroredDiffs = self._getMirroredDiffs(s)\n counts = self._getCounts(s)\n ans = []\n\n def subtractArrays(a: List[int], b: List[int]):\n return [x - y for x, y in zip(a, b)]\n\n for a, b, c, d in queries:\n b += 1\n d += 1\n ra = n - a\n rb = n - b\n rc = n - c\n rd = n - d\n\n if (min(a, rd) > 0 and mirroredDiffs[min(a, rd)] > 0) or (n // 2 > max(b, rc) and mirroredDiffs[n // 2] - mirroredDiffs[max(b, rc)] > 0) or (rd > b and mirroredDiffs[rd] - mirroredDiffs[b] > 0) or (a > rc and mirroredDiffs[a] - mirroredDiffs[rc] > 0):\n ans.append(False)\n else:\n leftRangeCount = subtractArrays(counts[b], counts[a])\n rightRangeCount = subtractArrays(counts[d], counts[c])\n if a > rd:\n rightRangeCount = subtractArrays(\n rightRangeCount, subtractArrays(counts[min(a, rc)], counts[rd]))\n if rc > b:\n rightRangeCount = subtractArrays(\n rightRangeCount, subtractArrays(counts[rc], counts[max(b, rd)]))\n if c > rb:\n leftRangeCount = subtractArrays(\n leftRangeCount, subtractArrays(counts[min(c, ra)], counts[rb]))\n if ra > d:\n leftRangeCount = subtractArrays(\n leftRangeCount, subtractArrays(counts[ra], counts[max(d, rb)]))\n ans.append(min(leftRangeCount) >= 0\n and min(rightRangeCount) >= 0\n and leftRangeCount == rightRangeCount)\n\n return ans\n\n def _getMirroredDiffs(self, s: str) -> List[int]:\n diffs = [0]\n for i, j in zip(range(len(s)), reversed(range(len(s)))):\n if i >= j:\n break\n diffs.append(diffs[-1] + (s[i] != s[j]))\n return diffs\n\n def _getCounts(self, s: str) -> List[List[int]]:\n count = [0] * 26\n counts = [count.copy()]\n for c in s:\n count[ord(c) - ord('a')] += 1\n counts.append(count.copy())\n return counts\n", "java_solution": "class Solution {\n public boolean[] canMakePalindromeQueries(String s, int[][] queries) {\n final int n = s.length();\n // mirroredDiffs[i] := the number of different letters between the first i\n // letters of s[0..n / 2) and the first i letters of s[n / 2..n)[::-1]\n final int[] mirroredDiffs = getMirroredDiffs(s);\n // counts[i] := the count of s[0..i)\n final int[][] counts = getCounts(s);\n boolean[] ans = new boolean[queries.length];\n\n for (int i = 0; i < queries.length; i++) {\n // Use left-closed, right-open intervals to facilitate the calculation.\n // ...... [a, b) ...|... [rb, ra) ......\n // .... [rd, rc) .....|..... [c, d) ....\n int[] query = queries[i];\n final int a = query[0];\n final int b = query[1] + 1;\n final int c = query[2];\n final int d = query[3] + 1;\n final int ra = n - a; // the reflected index of a in s[n / 2..n)\n final int rb = n - b; // the reflected index of b in s[n / 2..n)\n final int rc = n - c; // the reflected index of c in s[n / 2..n)\n final int rd = n - d; // the reflected index of d in s[n / 2..n)\n // No difference is allowed outside the query ranges.\n if ((Math.min(a, rd) > 0 && mirroredDiffs[Math.min(a, rd)] > 0) ||\n (n / 2 > Math.max(b, rc) && mirroredDiffs[n / 2] - mirroredDiffs[Math.max(b, rc)] > 0) ||\n (rd > b && mirroredDiffs[rd] - mirroredDiffs[b] > 0) ||\n (a > rc && mirroredDiffs[a] - mirroredDiffs[rc] > 0)) {\n ans[i] = false;\n } else {\n // The `count` map of the intersection of [a, b) and [rd, rc) in\n // s[0..n / 2) must equate to the `count` map of the intersection of\n // [c, d) and [rb, ra) in s[n / 2..n).\n int[] leftRangeCount = subtractArrays(counts[b], counts[a]);\n int[] rightRangeCount = subtractArrays(counts[d], counts[c]);\n if (a > rd)\n rightRangeCount =\n subtractArrays(rightRangeCount, subtractArrays(counts[Math.min(a, rc)], counts[rd]));\n if (rc > b)\n rightRangeCount =\n subtractArrays(rightRangeCount, subtractArrays(counts[rc], counts[Math.max(b, rd)]));\n if (c > rb)\n leftRangeCount =\n subtractArrays(leftRangeCount, subtractArrays(counts[Math.min(c, ra)], counts[rb]));\n if (ra > d)\n leftRangeCount =\n subtractArrays(leftRangeCount, subtractArrays(counts[ra], counts[Math.max(d, rb)]));\n ans[i] = Arrays.stream(leftRangeCount).allMatch(freq -> freq >= 0) &&\n Arrays.stream(rightRangeCount).allMatch(freq -> freq >= 0) &&\n Arrays.equals(leftRangeCount, rightRangeCount);\n }\n }\n\n return ans;\n }\n\n private int[] getMirroredDiffs(final String s) {\n int[] diffs = new int[s.length() / 2 + 1];\n for (int i = 0, j = s.length() - 1; i < j; i++, j--) {\n diffs[i + 1] = diffs[i] + (s.charAt(i) != s.charAt(j) ? 1 : 0);\n }\n return diffs;\n }\n\n private int[][] getCounts(final String s) {\n int[][] counts = new int[s.length() + 1][26];\n int[] count = new int[26];\n for (int i = 0; i < s.length(); ++i) {\n ++count[s.charAt(i) - 'a'];\n System.arraycopy(count, 0, counts[i + 1], 0, 26);\n }\n return counts;\n }\n\n private int[] subtractArrays(int[] a, int[] b) {\n int[] res = new int[a.length];\n for (int i = 0; i < a.length; ++i)\n res[i] = a[i] - b[i];\n return res;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector canMakePalindromeQueries(string s,\n vector>& queries) {\n const int n = s.length();\n // mirroredDiffs[i] := the number of different letters between the first i\n // letters of s[0..n / 2) and the first i letters of s[n / 2..n)[::-1]\n const vector mirroredDiffs = getMirroredDiffs(s);\n // counts[i] := the count of s[0..i)\n const vector> counts = getCounts(s);\n vector ans;\n\n for (const vector& query : queries) {\n // Use left-closed, right-open intervals to facilitate the calculation.\n // ...... [a, b) ...|... [rb, ra) ......\n // .... [rd, rc) .....|..... [c, d) ....\n const int a = query[0];\n const int b = query[1] + 1;\n const int c = query[2];\n const int d = query[3] + 1;\n const int ra = n - a; // the reflected index of a in s[n / 2..n)\n const int rb = n - b; // the reflected index of b in s[n / 2..n)\n const int rc = n - c; // the reflected index of c in s[n / 2..n)\n const int rd = n - d; // the reflected index of d in s[n / 2..n)\n // No difference is allowed outside the query ranges.\n if (min(a, rd) > 0 && mirroredDiffs[min(a, rd)] > 0 ||\n n / 2 > max(b, rc) &&\n mirroredDiffs[n / 2] - mirroredDiffs[max(b, rc)] > 0 ||\n rd > b && mirroredDiffs[rd] - mirroredDiffs[b] > 0 ||\n a > rc && mirroredDiffs[a] - mirroredDiffs[rc] > 0) {\n ans.push_back(false);\n } else {\n // The `count` map of the intersection of [a, b) and [rd, rc) in\n // s[0..n / 2) must equate to the `count` map of the intersection of\n // [c, d) and [rb, ra) in s[n / 2..n).\n vector leftRangeCount = subtractArrays(counts[b], counts[a]);\n vector rightRangeCount = subtractArrays(counts[d], counts[c]);\n if (a > rd)\n rightRangeCount = subtractArrays(\n rightRangeCount, subtractArrays(counts[min(a, rc)], counts[rd]));\n if (rc > b)\n rightRangeCount = subtractArrays(\n rightRangeCount, subtractArrays(counts[rc], counts[max(b, rd)]));\n if (c > rb)\n leftRangeCount = subtractArrays(\n leftRangeCount, subtractArrays(counts[min(c, ra)], counts[rb]));\n if (ra > d)\n leftRangeCount = subtractArrays(\n leftRangeCount, subtractArrays(counts[ra], counts[max(d, rb)]));\n ans.push_back(ranges::all_of(leftRangeCount, [](int freq) {\n return freq >= 0;\n }) && ranges::all_of(rightRangeCount, [](int freq) {\n return freq >= 0;\n }) && leftRangeCount == rightRangeCount);\n }\n }\n\n return ans;\n }\n\n private:\n vector getMirroredDiffs(const string& s) {\n vector diffs(1);\n for (int i = 0, j = s.length() - 1; i < j; ++i, --j)\n diffs.push_back(diffs.back() + (s[i] != s[j] ? 1 : 0));\n return diffs;\n }\n\n vector> getCounts(const string& s) {\n vector count(26);\n vector> counts{count};\n for (const char c : s) {\n ++count[c - 'a'];\n counts.push_back(count);\n }\n return counts;\n }\n\n vector subtractArrays(const vector& a, const vector& b) {\n vector res;\n for (int i = 0; i < a.size(); ++i)\n res.push_back(a[i] - b[i]);\n return res;\n }\n};\n"} +{"task_num": 3001, "task_title": "Minimum Moves to Capture The Queen", "difficulty": 2, "func_name": "minMovesToCaptureTheQueen", "description": "There is a 1-indexed `8 x 8` chessboard containing `3` pieces.\n\nYou are given `6` integers `a`, `b`, `c`, `d`, `e`, and `f` where:\n\n* `(a, b)` denotes the position of the white rook.\n* `(c, d)` denotes the position of the white bishop.\n* `(e, f)` denotes the position of the black queen.\n\nGiven that you can only move the white pieces, return the minimum number of\nmoves required to capture the black queen.\n\nNote that:\n\n* Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces.\n* Bishops can move any number of squares diagonally, but cannot jump over other pieces.\n* A rook or a bishop can capture the queen if it is located in a square that they can move to.\n* The queen does not move.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minMovesToCaptureTheQueen(self, a: int, b: int, c: int, d: int, e: int, f: int) -> int:\n if a == e:\n if c == a and (b < d < f or b > d > f):\n return 2\n else:\n return 1\n if b == f:\n if d == f and (a < c < e or a > c > e):\n return 2\n else:\n return 1\n if c + d == e + f:\n if a + b == c + d and (c < a < e or c > a > e):\n return 2\n else:\n return 1\n if c - d == e - f:\n if a - b == c - d and (c < a < e or c > a > e):\n return 2\n else:\n return 1\n return 2\n", "java_solution": "class Solution {\n public int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) {\n // The rook is in the same row as the queen.\n if (a == e)\n // The bishop blocks the rook or not.\n return (c == a && (b < d && d < f || b > d && d > f)) ? 2 : 1;\n // The rook is in the same column as the queen.\n if (b == f)\n // The bishop blocks the rook or not.\n return (d == f && (a < c && c < e || a > c && c > e)) ? 2 : 1;\n // The bishop is in the same up-diagonal as the queen.\n if (c + d == e + f)\n // The rook blocks the bishop or not.\n return (a + b == c + d && (c < a && a < e || c > a && a > e)) ? 2 : 1;\n // The bishop is in the same down-diagonal as the queen.\n if (c - d == e - f)\n // The rook blocks the bishop or not.\n return (a - b == c - d && (c < a && a < e || c > a && a > e)) ? 2 : 1;\n // The rook can always get the green in two steps.\n return 2;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) {\n // The rook is in the same row as the queen.\n if (a == e)\n // The bishop blocks the rook or not.\n return (c == a && (b < d && d < f || b > d && d > f)) ? 2 : 1;\n // The rook is in the same column as the queen.\n if (b == f)\n // The bishop blocks the rook or not.\n return (d == f && (a < c && c < e || a > c && c > e)) ? 2 : 1;\n // The bishop is in the same up-diagonal as the queen.\n if (c + d == e + f)\n // The rook blocks the bishop or not.\n return (a + b == c + d && (c < a && a < e || c > a && a > e)) ? 2 : 1;\n // The bishop is in the same down-diagonal as the queen.\n if (c - d == e - f)\n // The rook blocks the bishop or not.\n return (a - b == c - d && (c < a && a < e || c > a && a > e)) ? 2 : 1;\n // The rook can always get the green in two steps.\n return 2;\n }\n};\n"} +{"task_num": 3006, "task_title": "Find Beautiful Indices in the Given Array I", "difficulty": 2, "func_name": "beautifulIndices", "description": "You are given a 0-indexed string `s`, a string `a`, a string `b`, and an\ninteger `k`.\n\nAn index `i` is beautiful if:\n\n* `0 <= i <= s.length - a.length`\n* `s[i..(i + a.length - 1)] == a`\n* There exists an index `j` such that: \n* `0 <= j <= s.length - b.length`\n* `s[j..(j + b.length - 1)] == b`\n* `|j - i| <= k`\n\nReturn the array that contains beautiful indices in sorted order from smallest\nto largest.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def beautifulIndices(self, s: str, a: str, b: str, k: int) -> List[int]:\n ans = []\n indicesA = self._kmp(s, a)\n indicesB = self._kmp(s, b)\n indicesBIndex = 0\n\n for i in indicesA:\n while indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i < -k:\n indicesBIndex += 1\n if indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i <= k:\n ans.append(i)\n\n return ans\n\n def _kmp(self, s: str, pattern: str) -> List[int]:\n def getLPS(pattern: str) -> List[int]:\n lps = [0] * len(pattern)\n j = 0\n for i in range(1, len(pattern)):\n while j > 0 and pattern[j] != pattern[i]:\n j = lps[j - 1]\n if pattern[i] == pattern[j]:\n lps[i] = j + 1\n j += 1\n return lps\n\n res = []\n lps = getLPS(pattern)\n i = 0\n j = 0\n while i < len(s):\n if s[i] == pattern[j]:\n i += 1\n j += 1\n if j == len(pattern):\n res.append(i - j)\n j = lps[j - 1]\n elif j != 0:\n j = lps[j - 1]\n else:\n i += 1\n return res\n", "java_solution": "class Solution {\n public List beautifulIndices(String s, String a, String b, int k) {\n List ans = new ArrayList<>();\n List indicesA = kmp(s, a);\n List indicesB = kmp(s, b);\n int indicesBIndex = 0; // indicesB' index\n\n for (final int i : indicesA) {\n // The constraint is: |j - i| <= k. So, -k <= j - i <= k. So, move\n // `indicesBIndex` s.t. j - i >= -k, where j := indicesB[indicesBIndex].\n while (indicesBIndex < indicesB.size() && indicesB.get(indicesBIndex) - i < -k)\n ++indicesBIndex;\n if (indicesBIndex < indicesB.size() && indicesB.get(indicesBIndex) - i <= k)\n ans.add(i);\n }\n\n return ans;\n }\n\n // Returns the starting indices of all occurrences of the pattern in `s`.\n private List kmp(final String s, final String pattern) {\n List res = new ArrayList<>();\n int[] lps = getLPS(pattern);\n int i = 0; // s' index\n int j = 0; // pattern's index\n while (i < s.length()) {\n if (s.charAt(i) == pattern.charAt(j)) {\n ++i;\n ++j;\n if (j == pattern.length()) {\n res.add(i - j);\n j = lps[j - 1];\n }\n } else if (j != 0) { // Mismatch after j matches.\n // Don't match lps[0..lps[j - 1]] since they will match anyway.\n j = lps[j - 1];\n } else {\n ++i;\n }\n }\n return res;\n }\n\n // Returns the lps array, where lps[i] is the length of the longest prefix of\n // pattern[0..i] which is also a suffix of this substring.\n private int[] getLPS(final String pattern) {\n int[] lps = new int[pattern.length()];\n for (int i = 1, j = 0; i < pattern.length(); ++i) {\n while (j > 0 && pattern.charAt(j) != pattern.charAt(i))\n j = lps[j - 1];\n if (pattern.charAt(i) == pattern.charAt(j))\n lps[i] = ++j;\n }\n return lps;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector beautifulIndices(string s, string a, string b, int k) {\n vector ans;\n const vector indicesA = kmp(s, a);\n const vector indicesB = kmp(s, b);\n int indicesBIndex = 0; // indicesB's index\n\n for (const int i : indicesA) {\n // The constraint is: |j - i| <= k. So, -k <= j - i <= k. So, move\n // `indicesBIndex` s.t. j - i >= -k, where j := indicesB[indicesBIndex].\n while (indicesBIndex < indicesB.size() &&\n indicesB[indicesBIndex] - i < -k)\n ++indicesBIndex;\n if (indicesBIndex < indicesB.size() && indicesB[indicesBIndex] - i <= k)\n ans.push_back(i);\n }\n\n return ans;\n }\n\n private:\n // Returns the starting indices of all occurrences of the pattern in `s`.\n vector kmp(const string& s, const string& pattern) {\n vector res;\n const vector lps = getLPS(pattern);\n int i = 0; // s' index\n int j = 0; // pattern's index\n while (i < s.length()) {\n if (s[i] == pattern[j]) {\n ++i;\n ++j;\n if (j == pattern.length()) {\n res.push_back(i - j);\n j = lps[j - 1];\n }\n } else if (j > 0) { // Mismatch after j matches.\n // Don't match lps[0..lps[j - 1]] since they will match anyway.\n j = lps[j - 1];\n } else {\n ++i;\n }\n }\n return res;\n }\n\n // Returns the lps array, where lps[i] is the length of the longest prefix of\n // pattern[0..i] which is also a suffix of this substring.\n vector getLPS(const string& pattern) {\n vector lps(pattern.length());\n for (int i = 1, j = 0; i < pattern.length(); ++i) {\n while (j > 0 && pattern[j] != pattern[i])\n j = lps[j - 1];\n if (pattern[i] == pattern[j])\n lps[i] = ++j;\n }\n return lps;\n }\n};\n"} +{"task_num": 3029, "task_title": "Minimum Time to Revert Word to Initial State I", "difficulty": 2, "func_name": "minimumTimeToInitialState", "description": "You are given a 0-indexed string `word` and an integer `k`.\n\nAt every second, you must perform the following operations:\n\n* Remove the first `k` characters of `word`.\n* Add any `k` characters to the end of `word`.\n\nNote that you do not necessarily need to add the same characters that you\nremoved. However, you must perform both operations at every second.\n\nReturn the minimum time greater than zero required for `word` to revert to its\ninitial state.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumTimeToInitialState(self, word: str, k: int) -> int:\n n = len(word)\n maxOps = (n - 1) // k + 1\n z = self._zFunction(word)\n\n for ans in range(1, maxOps):\n if z[ans * k] >= n - ans * k:\n return ans\n\n return maxOps\n\n def _zFunction(self, s: str) -> List[int]:\n n = len(s)\n z = [0] * n\n l = 0\n r = 0\n for i in range(1, n):\n if i < r:\n z[i] = min(r - i, z[i - l])\n while i + z[i] < n and s[z[i]] == s[i + z[i]]:\n z[i] += 1\n if i + z[i] > r:\n l = i\n r = i + z[i]\n return z\n", "java_solution": "class Solution {\n // Same as 3029. Minimum Time to Revert Word to Initial State I\n public int minimumTimeToInitialState(String word, int k) {\n final int n = word.length();\n final int maxOps = (n - 1) / k + 1;\n final int[] z = zFunction(word);\n for (int ans = 1; ans < maxOps; ++ans)\n if (z[ans * k] >= n - ans * k)\n return ans;\n return maxOps;\n }\n\n // Returns the z array, where z[i] is the length of the longest prefix of\n // s[i..n) which is also a prefix of s.\n //\n // https://cp-algorithms.com/string/z-function.html#implementation\n private int[] zFunction(final String s) {\n final int n = s.length();\n int[] z = new int[n];\n int l = 0;\n int r = 0;\n for (int i = 1; i < n; ++i) {\n if (i < r)\n z[i] = Math.min(r - i, z[i - l]);\n while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))\n ++z[i];\n if (i + z[i] > r) {\n l = i;\n r = i + z[i];\n }\n }\n return z;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n // Same as 3029. Minimum Time to Revert Word to Initial State I\n int minimumTimeToInitialState(string word, int k) {\n const int n = word.length();\n const int maxOps = (n - 1) / k + 1;\n const vector z = zFunction(word);\n for (int ans = 1; ans < maxOps; ++ans)\n if (z[ans * k] >= n - ans * k)\n return ans;\n return maxOps;\n }\n\n // Returns the z array, where z[i] is the length of the longest prefix of\n // s[i..n) which is also a prefix of s.\n //\n // https://cp-algorithms.com/string/z-function.html#implementation\n vector zFunction(const string& s) {\n const int n = s.length();\n vector z(n);\n int l = 0;\n int r = 0;\n for (int i = 1; i < n; ++i) {\n if (i < r)\n z[i] = min(r - i, z[i - l]);\n while (i + z[i] < n && s[z[i]] == s[i + z[i]])\n ++z[i];\n if (i + z[i] > r) {\n l = i;\n r = i + z[i];\n }\n }\n return z;\n }\n};\n"} +{"task_num": 3030, "task_title": "Find the Grid of Region Average", "difficulty": 2, "func_name": "resultGrid", "description": "You are given a 0-indexed `m x n` grid `image` which represents a grayscale\nimage, where `image[i][j]` represents a pixel with intensity in the\nrange`[0..255]`. You are also given a non-negative integer `threshold`.\n\nTwo pixels `image[a][b]` and `image[c][d]` are said to be adjacent if `|a - c|\n+ |b - d| == 1`.\n\nA region is a `3 x 3` subgrid where the absolute difference in intensity\nbetween any two adjacent pixels is less than or equal to `threshold`.\n\nAll pixels in a region belong to that region, note that a pixel can belong to\nmultiple regions.\n\nYou need to calculate a 0-indexed `m x n` grid `result`, where `result[i][j]`\nis the average intensity of the region to which `image[i][j]` belongs, rounded\ndown to the nearest integer. If `image[i][j]` belongs to multiple regions,\n`result[i][j]` is the average of the rounded down average intensities of these\nregions, rounded down to the nearest integer. If `image[i][j]` does not belong\nto any region, `result[i][j]` is equal to `image[i][j]`.\n\nReturn the grid `result`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def resultGrid(self, image: List[List[int]], threshold: int) -> List[List[int]]:\n m = len(image)\n n = len(image[0])\n sums = [[0] * n for _ in range(m)]\n counts = [[0] * n for _ in range(m)]\n\n for i in range(m - 2):\n for j in range(n - 2):\n if self._isRegion(image, i, j, threshold):\n subgridSum = sum(image[x][y] for x in range(i, i + 3) for y in range(j, j + 3))\n for x in range(i, i + 3):\n for y in range(j, j + 3):\n sums[x][y] += subgridSum // 9\n counts[x][y] += 1\n\n for i in range(m):\n for j in range(n):\n if counts[i][j] > 0:\n image[i][j] = sums[i][j] // counts[i][j]\n\n return image\n\n def _isRegion(self, image: List[List[int]], i: int, j: int, threshold: int) -> bool:\n for x in range(i, i + 3):\n for y in range(j, j + 3):\n if x > i and abs(image[x][y] - image[x - 1][y]) > threshold:\n return False\n if y > j and abs(image[x][y] - image[x][y - 1]) > threshold:\n return False\n return True\n", "java_solution": "class Solution {\n public int[][] resultGrid(int[][] image, int threshold) {\n final int m = image.length;\n final int n = image[0].length;\n int[][] sums = new int[m][n];\n int[][] counts = new int[m][n];\n\n for (int i = 0; i < m - 2; ++i)\n for (int j = 0; j < n - 2; ++j)\n if (isRegion(image, i, j, threshold)) {\n final int subgridSum = getSubgridSum(image, i, j);\n for (int x = i; x < i + 3; ++x)\n for (int y = j; y < j + 3; ++y) {\n sums[x][y] += subgridSum / 9;\n counts[x][y] += 1;\n }\n }\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (counts[i][j] > 0)\n image[i][j] = sums[i][j] / counts[i][j];\n\n return image;\n }\n\n // Returns true if image[i..i + 2][j..j + 2] is a region.\n private boolean isRegion(int[][] image, int i, int j, int threshold) {\n for (int x = i; x < i + 3; ++x)\n for (int y = j; y < j + 3; ++y) {\n if (x > i && Math.abs(image[x][y] - image[x - 1][y]) > threshold)\n return false;\n if (y > j && Math.abs(image[x][y] - image[x][y - 1]) > threshold)\n return false;\n }\n return true;\n }\n\n // Returns the sum of image[i..i + 2][j..j + 2].\n private int getSubgridSum(int[][] image, int i, int j) {\n int subgridSum = 0;\n for (int x = i; x < i + 3; ++x)\n for (int y = j; y < j + 3; ++y)\n subgridSum += image[x][y];\n return subgridSum;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector> resultGrid(vector>& image, int threshold) {\n const int m = image.size();\n const int n = image[0].size();\n vector> sums(m, vector(n));\n vector> counts(m, vector(n));\n\n for (int i = 0; i < m - 2; ++i)\n for (int j = 0; j < n - 2; ++j)\n if (isRegion(image, i, j, threshold)) {\n const int subgridSum = getSubgridSum(image, i, j);\n for (int x = i; x < i + 3; ++x)\n for (int y = j; y < j + 3; ++y) {\n sums[x][y] += subgridSum / 9;\n counts[x][y] += 1;\n }\n }\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (counts[i][j] > 0)\n image[i][j] = sums[i][j] / counts[i][j];\n\n return image;\n }\n\n private:\n // Returns true if image[i..i + 2][j..j + 2] is a region.\n bool isRegion(const vector>& image, int i, int j, int threshold) {\n for (int x = i; x < i + 3; ++x)\n for (int y = j; y < j + 3; ++y) {\n if (x > i && abs(image[x][y] - image[x - 1][y]) > threshold)\n return false;\n if (y > j && abs(image[x][y] - image[x][y - 1]) > threshold)\n return false;\n }\n return true;\n }\n\n // Returns the sum of image[i..i + 2][j..j + 2].\n int getSubgridSum(const vector>& image, int i, int j) {\n int subgridSum = 0;\n for (int x = i; x < i + 3; ++x)\n for (int y = j; y < j + 3; ++y)\n subgridSum += image[x][y];\n return subgridSum;\n }\n};\n"} +{"task_num": 3043, "task_title": "Find the Length of the Longest Common Prefix", "difficulty": 2, "func_name": "longestCommonPrefix", "description": "You are given two arrays with positive integers `arr1` and `arr2`.\n\nA prefix of a positive integer is an integer formed by one or more of its\ndigits, starting from its leftmost digit. For example, `123` is a prefix of\nthe integer `12345`, while `234` is not.\n\nA common prefix of two integers `a` and `b` is an integer `c`, such that `c`\nis a prefix of both `a` and `b`. For example, `5655359` and `56554` have a\ncommon prefix `565` while `1223` and `43456` do not have a common prefix.\n\nYou need to find the length of the longest common prefix between all pairs of\nintegers `(x, y)` such that `x` belongs to `arr1` and `y` belongs to `arr2`.\n\nReturn the length of the longest common prefix among all pairs. If no common\nprefix exists among them, return `0`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass TrieNode:\n def __init__(self):\n self.children: Dict[str, TrieNode] = {}\n\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n\n def insert(self, word: str) -> None:\n node: TrieNode = self.root\n for c in word:\n node = node.children.setdefault(c, TrieNode())\n node.isWord = True\n\n def search(self, word: str) -> int:\n prefixLength = 0\n node = self.root\n for c in word:\n if c not in node.children:\n break\n node = node.children[c]\n prefixLength += 1\n return prefixLength\n\n\nclass Solution:\n def longestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int:\n trie = Trie()\n\n for num in arr1:\n trie.insert(str(num))\n\n return max(trie.search(str(num)) for num in arr2)\n", "java_solution": "class TrieNode {\n public TrieNode[] children = new TrieNode[10];\n}\n\nclass Trie {\n public void insert(final String word) {\n TrieNode node = root;\n for (final char c : word.toCharArray()) {\n final int i = c - '0';\n if (node.children[i] == null)\n node.children[i] = new TrieNode();\n node = node.children[i];\n }\n }\n\n public int search(final String word) {\n int prefixLength = 0;\n TrieNode node = root;\n for (final char c : word.toCharArray()) {\n final int i = c - '0';\n if (node.children[i] == null)\n break;\n node = node.children[i];\n ++prefixLength;\n }\n return prefixLength;\n }\n\n private TrieNode root = new TrieNode();\n}\n\nclass Solution {\n public int longestCommonPrefix(int[] arr1, int[] arr2) {\n int ans = 0;\n Trie trie = new Trie();\n\n for (final int num : arr1)\n trie.insert(Integer.toString(num));\n\n for (final int num : arr2)\n ans = Math.max(ans, trie.search(Integer.toString(num)));\n\n return ans;\n }\n}\n", "cpp_solution": "struct TrieNode {\n vector> children;\n TrieNode() : children(10) {}\n};\n\nclass Trie {\n public:\n void insert(const string& word) {\n shared_ptr node = root;\n for (const char c : word) {\n const int i = c - '0';\n if (node->children[i] == nullptr)\n node->children[i] = make_shared();\n node = node->children[i];\n }\n }\n\n int search(const string& word) {\n int prefixLength = 0;\n shared_ptr node = root;\n for (const char c : word) {\n const int i = c - '0';\n if (node->children[i] == nullptr)\n break;\n node = node->children[i];\n ++prefixLength;\n }\n return prefixLength;\n }\n\n private:\n shared_ptr root = make_shared();\n};\n\nclass Solution {\n public:\n int longestCommonPrefix(vector& arr1, vector& arr2) {\n int ans = 0;\n Trie trie;\n\n for (const int num : arr1)\n trie.insert(to_string(num));\n\n for (const int num : arr2)\n ans = max(ans, trie.search(to_string(num)));\n\n return ans;\n }\n};\n"} +{"task_num": 3044, "task_title": "Most Frequent Prime", "difficulty": 2, "func_name": "mostFrequentPrime", "description": "You are given a `m x n` 0-indexed 2D matrix `mat`. From every cell, you can\ncreate numbers in the following way:\n\n* There could be at most `8` paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east.\n* Select a path from them and append digits in this path to the number being formed by traveling in this direction.\n* Note that numbers are generated at every step, for example, if the digits along the path are `1, 9, 1`, then there will be three numbers generated along the way: `1, 19, 191`.\n\nReturn the most frequent prime number greater than `10` out of all the numbers\ncreated by traversing the matrix or `-1` if no such prime number exists. If\nthere are multiple prime numbers with the highest frequency, then return the\nlargest among them.\n\nNote: It is invalid to change the direction during the move.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def mostFrequentPrime(self, mat: List[List[int]]) -> int:\n dirs = ((1, 0), (1, -1), (0, -1), (-1, -1),\n (-1, 0), (-1, 1), (0, 1), (1, 1))\n m = len(mat)\n n = len(mat[0])\n count = collections.Counter()\n\n def isPrime(num: int) -> bool:\n return not any(num % i == 0 for i in range(2, int(num**0.5 + 1)))\n\n for i in range(m):\n for j in range(n):\n for dx, dy in dirs:\n num = 0\n x = i\n y = j\n while 0 <= x < m and 0 <= y < n:\n num = num * 10 + mat[x][y]\n if num > 10 and isPrime(num):\n count[num] += 1\n x += dx\n y += dy\n\n if not count.items():\n return -1\n return max(count.items(), key=lambda x: (x[1], x[0]))[0]\n", "java_solution": "class Solution {\n public int mostFrequentPrime(int[][] mat) {\n final int[][] DIRS = {{1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}};\n final int m = mat.length;\n final int n = mat[0].length;\n int ans = -1;\n int maxFreq = 0;\n Map count = new HashMap<>();\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n for (int[] dir : DIRS) {\n int num = 0;\n int x = i;\n int y = j;\n while (0 <= x && x < m && 0 <= y && y < n) {\n num = num * 10 + mat[x][y];\n if (num > 10 && isPrime(num))\n count.merge(num, 1, Integer::sum);\n x += dir[0];\n y += dir[1];\n }\n }\n\n for (Map.Entry entry : count.entrySet()) {\n final int prime = entry.getKey();\n final int freq = entry.getValue();\n if (freq > maxFreq) {\n ans = prime;\n maxFreq = freq;\n } else if (freq == maxFreq) {\n ans = Math.max(ans, prime);\n }\n }\n\n return ans;\n }\n\n private boolean isPrime(int num) {\n for (int i = 2; i < (int) Math.sqrt(num) + 1; ++i)\n if (num % i == 0)\n return false;\n return true;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int mostFrequentPrime(vector>& mat) {\n constexpr int kDirs[8][2] = {{1, 0}, {1, -1}, {0, -1}, {-1, -1},\n {-1, 0}, {-1, 1}, {0, 1}, {1, 1}};\n const int m = mat.size();\n const int n = mat[0].size();\n int ans = -1;\n int maxFreq = 0;\n unordered_map count;\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n for (const auto& [dx, dy] : kDirs) {\n int num = 0;\n for (int x = i, y = j; 0 <= x && x < m && 0 <= y && y < n;\n x += dx, y += dy) {\n num = num * 10 + mat[x][y];\n if (num > 10 && isPrime(num))\n ++count[num];\n }\n }\n\n for (const auto& [prime, freq] : count)\n if (freq > maxFreq) {\n ans = prime;\n maxFreq = freq;\n } else if (freq == maxFreq) {\n ans = max(ans, prime);\n }\n\n return ans;\n }\n\n private:\n bool isPrime(int num) {\n for (int i = 2; i < sqrt(num) + 1; ++i)\n if (num % i == 0)\n return false;\n return true;\n }\n};\n"} +{"task_num": 3072, "task_title": "Distribute Elements Into Two Arrays II", "difficulty": 3, "func_name": "resultArray", "description": "You are given a 1-indexed array of integers `nums` of length `n`.\n\nWe define a function `greaterCount` such that `greaterCount(arr, val)` returns\nthe number of elements in `arr` that are strictly greater than `val`.\n\nYou need to distribute all the elements of `nums` between two arrays `arr1`\nand `arr2` using `n` operations. In the first operation, append `nums[1]` to\n`arr1`. In the second operation, append `nums[2]` to `arr2`. Afterwards, in\nthe `ith` operation:\n\n* If `greaterCount(arr1, nums[i]) > greaterCount(arr2, nums[i])`, append `nums[i]` to `arr1`.\n* If `greaterCount(arr1, nums[i]) < greaterCount(arr2, nums[i])`, append `nums[i]` to `arr2`.\n* If `greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])`, append `nums[i]` to the array with a lesser number of elements.\n* If there is still a tie, append `nums[i]` to `arr1`.\n\nThe array `result` is formed by concatenating the arrays `arr1` and `arr2`.\nFor example, if `arr1 == [1,2,3]` and `arr2 == [4,5,6]`, then `result =\n[1,2,3,4,5,6]`.\n\nReturn the integer array `result`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass FenwickTree:\n def __init__(self, n: int):\n self.sums = [0] * (n + 1)\n\n def update(self, i: int, delta: int) -> None:\n while i < len(self.sums):\n self.sums[i] += delta\n i += FenwickTree.lowbit(i)\n\n def get(self, i: int) -> int:\n summ = 0\n while i > 0:\n summ += self.sums[i]\n i -= FenwickTree.lowbit(i)\n return summ\n\n @staticmethod\n def lowbit(i: int) -> int:\n return i & -i\n\n\nclass Solution:\n def resultArray(self, nums: List[int]) -> List[int]:\n arr1 = []\n arr2 = []\n ranks = self._getRanks(nums)\n tree1 = FenwickTree(len(ranks))\n tree2 = FenwickTree(len(ranks))\n\n def add(num: int, arr: List[int], tree: FenwickTree) -> None:\n arr.append(num)\n tree.update(ranks[num], 1)\n\n add(nums[0], arr1, tree1)\n add(nums[1], arr2, tree2)\n\n for i in range(2, len(nums)):\n greaterCount1 = len(arr1) - tree1.get(ranks[nums[i]])\n greaterCount2 = len(arr2) - tree2.get(ranks[nums[i]])\n if greaterCount1 > greaterCount2:\n add(nums[i], arr1, tree1)\n elif greaterCount1 < greaterCount2:\n add(nums[i], arr2, tree2)\n elif len(arr1) > len(arr2):\n add(nums[i], arr2, tree2)\n else:\n add(nums[i], arr1, tree1)\n\n return arr1 + arr2\n\n def _getRanks(self, nums: List[int]) -> Dict[int, int]:\n ranks = collections.Counter()\n rank = 0\n for num in sorted(set(nums)):\n rank += 1\n ranks[num] = rank\n return ranks\n", "java_solution": "class FenwickTree {\n public FenwickTree(int n) {\n sums = new int[n + 1];\n }\n\n public void add(int i, int delta) {\n while (i < sums.length) {\n sums[i] += delta;\n i += lowbit(i);\n }\n }\n\n public int get(int i) {\n int sum = 0;\n while (i > 0) {\n sum += sums[i];\n i -= lowbit(i);\n }\n return sum;\n }\n\n private int[] sums;\n\n private static int lowbit(int i) {\n return i & -i;\n }\n}\n\nclass Solution {\n public int[] resultArray(int[] nums) {\n List arr1 = new ArrayList<>();\n List arr2 = new ArrayList<>();\n Map ranks = getRanks(nums);\n FenwickTree tree1 = new FenwickTree(ranks.size());\n FenwickTree tree2 = new FenwickTree(ranks.size());\n\n add(nums[0], arr1, tree1, ranks);\n add(nums[1], arr2, tree2, ranks);\n\n for (int i = 2; i < nums.length; ++i) {\n final int greaterCount1 = arr1.size() - tree1.get(ranks.get(nums[i]));\n final int greaterCount2 = arr2.size() - tree2.get(ranks.get(nums[i]));\n if (greaterCount1 > greaterCount2)\n add(nums[i], arr1, tree1, ranks);\n else if (greaterCount1 < greaterCount2)\n add(nums[i], arr2, tree2, ranks);\n else if (arr1.size() > arr2.size())\n add(nums[i], arr2, tree2, ranks);\n else\n add(nums[i], arr1, tree1, ranks);\n }\n\n arr1.addAll(arr2);\n return arr1.stream().mapToInt(Integer::intValue).toArray();\n }\n\n private Map getRanks(int[] nums) {\n Map ranks = new HashMap<>();\n SortedSet sorted = new TreeSet<>();\n for (final int num : nums)\n sorted.add(num);\n int rank = 0;\n for (Iterator it = sorted.iterator(); it.hasNext();)\n ranks.put(it.next(), ++rank);\n return ranks;\n }\n\n private void add(int num, List arr, FenwickTree tree, Map ranks) {\n arr.add(num);\n tree.add(ranks.get(num), 1);\n };\n}\n", "cpp_solution": "class FenwickTree {\n public:\n FenwickTree(int n) : sums(n + 1) {}\n\n void add(int i, int delta) {\n while (i < sums.size()) {\n sums[i] += delta;\n i += lowbit(i);\n }\n }\n\n int get(int i) const {\n int sum = 0;\n while (i > 0) {\n sum += sums[i];\n i -= lowbit(i);\n }\n return sum;\n }\n\n private:\n vector sums;\n\n static inline int lowbit(int i) {\n return i & -i;\n }\n};\n\nclass Solution {\n public:\n vector resultArray(vector& nums) {\n vector arr1;\n vector arr2;\n const unordered_map ranks = getRanks(nums);\n FenwickTree tree1(ranks.size());\n FenwickTree tree2(ranks.size());\n\n add(nums[0], arr1, tree1, ranks);\n add(nums[1], arr2, tree2, ranks);\n\n for (int i = 2; i < nums.size(); ++i) {\n const int greaterCount1 = arr1.size() - tree1.get(ranks.at(nums[i]));\n const int greaterCount2 = arr2.size() - tree2.get(ranks.at(nums[i]));\n if (greaterCount1 > greaterCount2)\n add(nums[i], arr1, tree1, ranks);\n else if (greaterCount1 < greaterCount2)\n add(nums[i], arr2, tree2, ranks);\n else if (arr1.size() > arr2.size())\n add(nums[i], arr2, tree2, ranks);\n else\n add(nums[i], arr1, tree1, ranks);\n }\n\n arr1.insert(arr1.end(), arr2.begin(), arr2.end());\n return arr1;\n }\n\n private:\n unordered_map getRanks(const vector& nums) {\n unordered_map ranks;\n set sorted(nums.begin(), nums.end());\n int rank = 0;\n for (const int num : sorted)\n ranks[num] = ++rank;\n return ranks;\n }\n\n void add(int num, vector& arr, FenwickTree& tree,\n const unordered_map& ranks) {\n arr.push_back(num);\n tree.add(ranks.at(num), 1);\n };\n};\n"} +{"task_num": 3095, "task_title": "Shortest Subarray With OR at Least K I", "difficulty": 1, "func_name": "minimumSubarrayLength", "description": "You are given an array `nums` of non-negative integers and an integer `k`.\n\nAn array is called special if the bitwise `OR` of all of its elements is at\nleast `k`.\n\nReturn the length of the shortest special non-empty subarray of `nums`, or\nreturn `-1` if no special subarray exists.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumSubarrayLength(self, nums: List[int], k: int) -> int:\n ans = len(nums) + 1\n ors = 0\n count = collections.Counter()\n\n l = 0\n for r, num in enumerate(nums):\n ors = self._orNum(ors, num, count)\n while ors >= k and l <= r:\n ans = min(ans, r - l + 1)\n ors = self._undoOrNum(ors, nums[l], count)\n l += 1\n\n return -1 if ans == len(nums) + 1 else ans\n\n def _orNum(self, ors: int, num: int, count: Dict[int, int]) -> int:\n for i in range(30):\n if num >> i & 1:\n count[i] += 1\n if count[i] == 1:\n ors += 1 << i\n return ors\n\n def _undoOrNum(self, ors: int, num: int, count: Dict[int, int]) -> int:\n for i in range(30):\n if num >> i & 1:\n count[i] -= 1\n if count[i] == 0:\n ors -= 1 << i\n return ors\n", "java_solution": "class Solution {\n public int minimumSubarrayLength(int[] nums, int k) {\n final int MAX = 50;\n final int n = nums.length;\n int ans = n + 1;\n int ors = 0;\n int[] count = new int[MAX + 1];\n\n for (int l = 0, r = 0; r < n; ++r) {\n ors = orNum(ors, nums[r], count);\n while (ors >= k && l <= r) {\n ans = Math.min(ans, r - l + 1);\n ors = undoOrNum(ors, nums[l], count);\n ++l;\n }\n }\n\n return (ans == n + 1) ? -1 : ans;\n }\n\n private static final int MAX_BIT = 30;\n\n private int orNum(int ors, int num, int[] count) {\n for (int i = 0; i < MAX_BIT; ++i)\n if ((num >> i & 1) == 1 && ++count[i] == 1)\n ors += 1 << i;\n return ors;\n }\n\n private int undoOrNum(int ors, int num, int[] count) {\n for (int i = 0; i < MAX_BIT; ++i)\n if ((num >> i & 1) == 1 && --count[i] == 0)\n ors -= 1 << i;\n return ors;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minimumSubarrayLength(vector& nums, int k) {\n constexpr int kMax = 50;\n const int n = nums.size();\n int ans = n + 1;\n int ors = 0;\n vector count(kMax + 1);\n\n for (int l = 0, r = 0; r < n; r++) {\n ors = orNum(ors, nums[r], count);\n while (ors >= k && l <= r) {\n ans = min(ans, r - l + 1);\n ors = undoOrNum(ors, nums[l], count);\n ++l;\n }\n }\n\n return (ans == n + 1) ? -1 : ans;\n }\n\n private:\n static constexpr int kMaxBit = 30;\n\n int orNum(int ors, int num, vector& count) {\n for (int i = 0; i < kMaxBit; ++i)\n if (num >> i & 1 && ++count[i] == 1)\n ors += 1 << i;\n return ors;\n }\n\n int undoOrNum(int ors, int num, vector& count) {\n for (int i = 0; i < kMaxBit; ++i)\n if (num >> i & 1 && --count[i] == 0)\n ors -= 1 << i;\n return ors;\n }\n};\n"} +{"task_num": 3102, "task_title": "Minimize Manhattan Distances", "difficulty": 3, "func_name": "minimumDistance", "description": "You are given a array `points` representing integer coordinates of some points\non a 2D plane, where `points[i] = [xi, yi]`.\n\nThe distance between two points is defined as their Manhattan distance.\n\nReturn the minimum possible value for maximum distance between any two points\nby removing exactly one point.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumDistance(self, points: List[List[int]]) -> int:\n i, j = self._maxManhattanDistance(points, -1)\n xi, yi = self._maxManhattanDistance(points, i)\n xj, yj = self._maxManhattanDistance(points, j)\n return min(self._manhattan(points, xi, yi), self._manhattan(points, xj, yj))\n\n def _maxManhattanDistance(self, points: List[List[int]], excludedIndex: int) -> int:\n minSum = math.inf\n maxSum = -math.inf\n minDiff = math.inf\n maxDiff = -math.inf\n minSumIndex = -1\n maxSumIndex = -1\n minDiffIndex = -1\n maxDiffIndex = -1\n\n for i, (x, y) in enumerate(points):\n if i == excludedIndex:\n continue\n summ = x + y\n diff = x - y\n if summ < minSum:\n minSum = summ\n minSumIndex = i\n if summ > maxSum:\n maxSum = summ\n maxSumIndex = i\n if diff < minDiff:\n minDiff = diff\n minDiffIndex = i\n if diff > maxDiff:\n maxDiff = diff\n maxDiffIndex = i\n\n if maxSum - minSum >= maxDiff - minDiff:\n return [minSumIndex, maxSumIndex]\n else:\n return [minDiffIndex, maxDiffIndex]\n\n def _manhattan(self, points: List[List[int]], i: int, j: int) -> int:\n return abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])\n", "java_solution": "class Solution {\n public int minimumDistance(int[][] points) {\n final int[] maxIndices = maxManhattanDistance(points, -1);\n final int[] xiyi = maxManhattanDistance(points, maxIndices[0]);\n final int[] xjyj = maxManhattanDistance(points, maxIndices[1]);\n return Math.min(manhattan(points, xiyi[0], xiyi[1]), //\n manhattan(points, xjyj[0], xjyj[1]));\n }\n\n // Returns the pair of indices a and b where points[a] and points[b] have the\n // maximum Manhattan distance and a != excludedIndex and b != excludedIndex.\n private int[] maxManhattanDistance(int[][] points, int excludedIndex) {\n int minSum = Integer.MAX_VALUE;\n int maxSum = Integer.MIN_VALUE;\n int minDiff = Integer.MAX_VALUE;\n int maxDiff = Integer.MIN_VALUE;\n int minSumIndex = -1;\n int maxSumIndex = -1;\n int minDiffIndex = -1;\n int maxDiffIndex = -1;\n\n for (int i = 0; i < points.length; ++i) {\n if (i == excludedIndex)\n continue;\n final int x = points[i][0];\n final int y = points[i][1];\n final int sum = x + y;\n final int diff = x - y;\n if (sum < minSum) {\n minSum = sum;\n minSumIndex = i;\n }\n if (sum > maxSum) {\n maxSum = sum;\n maxSumIndex = i;\n }\n if (diff < minDiff) {\n minDiff = diff;\n minDiffIndex = i;\n }\n if (diff > maxDiff) {\n maxDiff = diff;\n maxDiffIndex = i;\n }\n }\n\n return maxSum - minSum >= maxDiff - minDiff ? new int[] {minSumIndex, maxSumIndex}\n : new int[] {minDiffIndex, maxDiffIndex};\n }\n\n private int manhattan(int[][] points, int i, int j) {\n return Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]);\n }\n}\n", "cpp_solution": "class Solution {\n public:\n int minimumDistance(vector>& points) {\n const auto [i, j] = maxManhattanDistance(points, -1);\n const auto [xi, yi] = maxManhattanDistance(points, i);\n const auto [xj, yj] = maxManhattanDistance(points, j);\n return min(manhattan(points, xi, yi), manhattan(points, xj, yj));\n }\n\n private:\n // Returns the pair of indices a and b where points[a] and points[b] have the\n // maximum Manhattan distance and a != excludedIndex and b != excludedIndex.\n pair maxManhattanDistance(const vector>& points,\n int excludedIndex) {\n int minSum = INT_MAX;\n int maxSum = INT_MIN;\n int minDiff = INT_MAX;\n int maxDiff = INT_MIN;\n int minSumIndex = -1;\n int maxSumIndex = -1;\n int minDiffIndex = -1;\n int maxDiffIndex = -1;\n\n for (int i = 0; i < points.size(); ++i) {\n if (i == excludedIndex)\n continue;\n const int x = points[i][0];\n const int y = points[i][1];\n const int sum = x + y;\n const int diff = x - y;\n if (sum < minSum)\n minSum = sum, minSumIndex = i;\n if (sum > maxSum)\n maxSum = sum, maxSumIndex = i;\n if (diff < minDiff)\n minDiff = diff, minDiffIndex = i;\n if (diff > maxDiff)\n maxDiff = diff, maxDiffIndex = i;\n }\n\n return maxSum - minSum >= maxDiff - minDiff\n ? pair(minSumIndex, maxSumIndex)\n : pair(minDiffIndex, maxDiffIndex);\n }\n\n int manhattan(const vector>& points, int i, int j) {\n return abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]);\n }\n};\n"} +{"task_num": 3108, "task_title": "Minimum Cost Walk in Weighted Graph", "difficulty": 3, "func_name": "minimumCost", "description": "There is an undirected weighted graph with `n` vertices labeled from `0` to `n\n- 1`.\n\nYou are given the integer `n` and an array `edges`, where `edges[i] = [ui, vi,\nwi]` indicates that there is an edge between vertices `ui` and `vi` with a\nweight of `wi`.\n\nA walk on a graph is a sequence of vertices and edges. The walk starts and\nends with a vertex, and each edge connects the vertex that comes before it and\nthe vertex that comes after it. It's important to note that a walk may visit\nthe same edge or vertex more than once.\n\nThe cost of a walk starting at node `u` and ending at node `v` is defined as\nthe bitwise `AND` of the weights of the edges traversed during the walk. In\nother words, if the sequence of edge weights encountered during the walk is\n`w0, w1, w2, ..., wk`, then the cost is calculated as `w0 & w1 & w2 & ... &\nwk`, where `&` denotes the bitwise `AND` operator.\n\nYou are also given a 2D array `query`, where `query[i] = [si, ti]`. For each\nquery, you need to find the minimum cost of the walk starting at vertex `si`\nand ending at vertex `ti`. If there exists no such walk, the answer is `-1`.\n\nReturn the array `answer`, where `answer[i]` denotes the minimum cost of a\nwalk for query `i`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass UnionFind:\n def __init__(self, n: int):\n self.id = list(range(n))\n self.rank = [0] * n\n self.weight = [(1 << 17) - 1] * n\n\n def unionByRank(self, u: int, v: int, w: int) -> None:\n i = self._find(u)\n j = self._find(v)\n newWeight = self.weight[i] & self.weight[j] & w\n self.weight[i] = newWeight\n self.weight[j] = newWeight\n if i == j:\n return\n if self.rank[i] < self.rank[j]:\n self.id[i] = j\n elif self.rank[i] > self.rank[j]:\n self.id[j] = i\n else:\n self.id[i] = j\n self.rank[j] += 1\n\n def getMinCost(self, u: int, v: int) -> int:\n if u == v:\n return 0\n i = self._find(u)\n j = self._find(v)\n if i == j:\n return self.weight[i]\n else:\n return -1\n\n def _find(self, u: int) -> int:\n if self.id[u] != u:\n self.id[u] = self._find(self.id[u])\n return self.id[u]\n\n\nclass Solution:\n def minimumCost(self, n: int, edges: List[List[int]], query: List[List[int]]) -> List[int]:\n uf = UnionFind(n)\n\n for u, v, w in edges:\n uf.unionByRank(u, v, w)\n\n return [uf.getMinCost(u, v) for u, v in query]\n", "java_solution": "class UnionFind {\n public UnionFind(int n) {\n id = new int[n];\n rank = new int[n];\n weight = new int[n];\n for (int i = 0; i < n; ++i)\n id[i] = i;\n // 2^17 - 1 is the minimum number in the form 2^x - 1 > 10^5.\n Arrays.fill(weight, (1 << 17) - 1);\n }\n\n public void unionByRank(int u, int v, int w) {\n final int i = find(u);\n final int j = find(v);\n final int newWeight = weight[i] & weight[j] & w;\n weight[i] = newWeight;\n weight[j] = newWeight;\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n public int getMinCost(int u, int v) {\n if (u == v)\n return 0;\n final int i = find(u);\n final int j = find(v);\n return i == j ? weight[i] : -1;\n }\n\n private int[] id;\n private int[] rank;\n private int[] weight;\n\n private int find(int u) {\n return id[u] == u ? u : (id[u] = find(id[u]));\n }\n}\n\nclass Solution {\n public int[] minimumCost(int n, int[][] edges, int[][] query) {\n int[] ans = new int[query.length];\n UnionFind uf = new UnionFind(n);\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n final int w = edge[2];\n uf.unionByRank(u, v, w);\n }\n\n for (int i = 0; i < query.length; ++i) {\n final int u = query[i][0];\n final int v = query[i][1];\n ans[i] = uf.getMinCost(u, v);\n }\n\n return ans;\n }\n}\n", "cpp_solution": "class UnionFind {\n public:\n // 2^17 - 1 is the minimum number in the form 2^x - 1 > 10^5.\n UnionFind(int n) : id(n), rank(n), weight(n, (1 << 17) - 1) {\n iota(id.begin(), id.end(), 0);\n }\n\n void unionByRank(int u, int v, int w) {\n const int i = find(u);\n const int j = find(v);\n const int newWeight = weight[i] & weight[j] & w;\n weight[i] = newWeight;\n weight[j] = newWeight;\n if (i == j)\n return;\n if (rank[i] < rank[j]) {\n id[i] = j;\n } else if (rank[i] > rank[j]) {\n id[j] = i;\n } else {\n id[i] = j;\n ++rank[j];\n }\n }\n\n int getMinCost(int u, int v) {\n if (u == v)\n return 0;\n const int i = find(u);\n const int j = find(v);\n return i == j ? weight[i] : -1;\n }\n\n private:\n vector id;\n vector rank;\n vector weight;\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n};\n\nclass Solution {\n public:\n vector minimumCost(int n, vector>& edges,\n vector>& query) {\n vector ans;\n UnionFind uf(n);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n const int w = edge[2];\n uf.unionByRank(u, v, w);\n }\n\n for (const vector& query : queries) {\n const int u = query[0];\n const int v = query[1];\n ans.push_back(uf.getMinCost(u, v));\n }\n\n return ans;\n }\n};\n"} +{"task_num": 3112, "task_title": "Minimum Time to Visit Disappearing Nodes", "difficulty": 2, "func_name": "minimumTime", "description": "There is an undirected graph of `n` nodes. You are given a 2D array `edges`,\nwhere `edges[i] = [ui, vi, lengthi]` describes an edge between node `ui` and\nnode `vi` with a traversal time of `lengthi` units.\n\nAdditionally, you are given an array `disappear`, where `disappear[i]` denotes\nthe time when the node `i` disappears from the graph and you won't be able to\nvisit it.\n\nNotice that the graph might be disconnected and might contain multiple edges.\n\nReturn the array `answer`, with `answer[i]` denoting the minimum units of time\nrequired to reach node `i` from node 0. If node `i` is unreachable from node 0\nthen `answer[i]` is `-1`.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def minimumTime(self, n: int, edges: List[List[int]], disappear: List[int]) -> List[int]:\n graph = [[] for _ in range(n)]\n\n for u, v, w in edges:\n graph[u].append((v, w))\n graph[v].append((u, w))\n\n return self._dijkstra(graph, 0, disappear)\n\n def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, disappear: List[int]) -> List[int]:\n dist = [math.inf] * len(graph)\n\n dist[src] = 0\n minHeap = [(dist[src], src)]\n\n while minHeap:\n d, u = heapq.heappop(minHeap)\n if d > dist[u]:\n continue\n for v, w in graph[u]:\n if d + w < disappear[v] and d + w < dist[v]:\n dist[v] = d + w\n heapq.heappush(minHeap, (dist[v], v))\n\n res=[]\n for d in dist:\n if d != math.inf:\n res.append(d)\n else:\n res.append(-1)\n return res\n", "java_solution": "class Solution {\n public int[] minimumTime(int n, int[][] edges, int[] disappear) {\n List>[] graph = new List[n];\n\n for (int i = 0; i < n; i++)\n graph[i] = new ArrayList<>();\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n final int w = edge[2];\n graph[u].add(new Pair<>(v, w));\n graph[v].add(new Pair<>(u, w));\n }\n\n return dijkstra(graph, 0, disappear);\n }\n\n private int[] dijkstra(List>[] graph, int src, int[] disappear) {\n int[] dist = new int[graph.length];\n Arrays.fill(dist, Integer.MAX_VALUE);\n\n dist[src] = 0;\n Queue> minHeap =\n new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) {\n { offer(new Pair<>(dist[src], src)); } // (d, u)\n };\n\n while (!minHeap.isEmpty()) {\n final int d = minHeap.peek().getKey();\n final int u = minHeap.poll().getValue();\n if (d > dist[u])\n continue;\n for (Pair pair : graph[u]) {\n final int v = pair.getKey();\n final int w = pair.getValue();\n if (d + w < disappear[v] && d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.offer(new Pair<>(dist[v], v));\n }\n }\n }\n\n for (int i = 0; i < dist.length; ++i)\n if (dist[i] == Integer.MAX_VALUE)\n dist[i] = -1;\n\n return dist;\n }\n}\n", "cpp_solution": "class Solution {\n public:\n vector minimumTime(int n, vector>& edges,\n vector& disappear) {\n vector>> graph(n);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n const int w = edge[2];\n graph[u].emplace_back(v, w);\n graph[v].emplace_back(u, w);\n }\n\n return dijkstra(graph, 0, disappear);\n }\n\n private:\n vector dijkstra(const vector>>& graph, int src,\n const vector& disappear) {\n vector dist(graph.size(), INT_MAX);\n\n dist[src] = 0;\n using P = pair; // (d, u)\n priority_queue, greater<>> minHeap;\n minHeap.emplace(dist[src], src);\n\n while (!minHeap.empty()) {\n const auto [d, u] = minHeap.top();\n minHeap.pop();\n if (d > dist[u])\n continue;\n for (const auto& [v, w] : graph[u])\n if (d + w < disappear[v] && d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.push({dist[v], v});\n }\n }\n\n for (int& d : dist)\n if (d == INT_MAX)\n d = -1;\n\n return dist;\n }\n};\n"} +{"task_num": 3123, "task_title": "Find Edges in Shortest Paths", "difficulty": 3, "func_name": "findAnswer", "description": "You are given an undirected weighted graph of `n` nodes numbered from 0 to `n\n- 1`. The graph consists of `m` edges represented by a 2D array `edges`, where\n`edges[i] = [ai, bi, wi]` indicates that there is an edge between nodes `ai`\nand `bi` with weight `wi`.\n\nConsider all the shortest paths from node 0 to node `n - 1` in the graph. You\nneed to find a boolean array `answer` where `answer[i]` is `true` if the edge\n`edges[i]` is part of at least one shortest path. Otherwise, `answer[i]` is\n`false`.\n\nReturn the array `answer`.\n\nNote that the graph may not be connected.\n\n", "python_solution": "import math\nimport itertools\nimport bisect\nimport collections\nimport string\nimport heapq\nimport functools\nimport sortedcontainers\nfrom typing import List, Dict, Tuple, Iterator\n\nclass Solution:\n def findAnswer(self, n: int, edges: List[List[int]]) -> List[bool]:\n graph = [[] for _ in range(n)]\n\n for u, v, w in edges:\n graph[u].append((v, w))\n graph[v].append((u, w))\n\n from0 = self._dijkstra(graph, 0)\n from1 = self._dijkstra(graph, n - 1)\n return [from0[u] + w + from1[v] == from0[-1] or from0[v] + w + from1[u] == from0[-1] for u, v, w in edges]\n\n def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int) -> List[int]:\n dist = [10**9] * len(graph)\n\n dist[src] = 0\n minHeap = [(dist[src], src)]\n\n while minHeap:\n d, u = heapq.heappop(minHeap)\n if d > dist[u]:\n continue\n for v, w in graph[u]:\n if d + w < dist[v]:\n dist[v] = d + w\n heapq.heappush(minHeap, (dist[v], v))\n\n return dist\n", "java_solution": "class Solution {\n // Similar to 2203. Minimum Weighted Subgraph With the Required Paths\n public boolean[] findAnswer(int n, int[][] edges) {\n boolean[] ans = new boolean[edges.length];\n List>[] graph = new List[n];\n Arrays.setAll(graph, i -> new ArrayList<>());\n\n for (int[] edge : edges) {\n final int u = edge[0];\n final int v = edge[1];\n final int w = edge[2];\n graph[u].add(new Pair<>(v, w));\n graph[v].add(new Pair<>(u, w));\n }\n\n int[] from0 = dijkstra(graph, 0);\n int[] from1 = dijkstra(graph, n - 1);\n\n for (int i = 0; i < edges.length; ++i) {\n final int u = edges[i][0];\n final int v = edges[i][1];\n final int w = edges[i][2];\n ans[i] = from0[u] + w + from1[v] == from0[n - 1] || //\n from0[v] + w + from1[u] == from0[n - 1];\n }\n\n return ans;\n }\n\n private static int MAX = 1_000_000_000;\n\n private int[] dijkstra(List>[] graph, int src) {\n int[] dist = new int[graph.length];\n Arrays.fill(dist, MAX);\n\n dist[src] = 0;\n Queue> minHeap =\n new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) {\n { offer(new Pair<>(dist[src], src)); } // (d, u)\n };\n\n while (!minHeap.isEmpty()) {\n final int d = minHeap.peek().getKey();\n final int u = minHeap.poll().getValue();\n if (d > dist[u])\n continue;\n for (Pair pair : graph[u]) {\n final int v = pair.getKey();\n final int w = pair.getValue();\n if (d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.offer(new Pair<>(dist[v], v));\n }\n }\n }\n\n return dist;\n }\n};\n", "cpp_solution": "class Solution {\n public:\n // Similar to 2203. Minimum Weighted Subgraph With the Required Paths\n vector findAnswer(int n, vector>& edges) {\n vector ans;\n vector>> graph(n);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n const int w = edge[2];\n graph[u].emplace_back(v, w);\n graph[v].emplace_back(u, w);\n }\n\n const vector from0 = dijkstra(graph, 0);\n const vector from1 = dijkstra(graph, n - 1);\n\n for (const vector& edge : edges) {\n const int u = edge[0];\n const int v = edge[1];\n const int w = edge[2];\n ans.push_back(from0[u] + w + from1[v] == from0[n - 1] ||\n from0[v] + w + from1[u] == from0[n - 1]);\n }\n\n return ans;\n }\n\n private:\n static constexpr int kMax = 1'000'000'000;\n\n vector dijkstra(const vector>>& graph, int src) {\n vector dist(graph.size(), kMax);\n\n dist[src] = 0;\n using P = pair; // (d, u)\n priority_queue, greater<>> minHeap;\n minHeap.emplace(dist[src], src);\n\n while (!minHeap.empty()) {\n const auto [d, u] = minHeap.top();\n minHeap.pop();\n if (d > dist[u])\n continue;\n for (const auto& [v, w] : graph[u])\n if (d + w < dist[v]) {\n dist[v] = d + w;\n minHeap.emplace(dist[v], v);\n }\n }\n\n return dist;\n }\n};\n"}