Leetcode Hard: Python3 Benchmark

pull/8/head
Beck LaBash 1 year ago
parent 95a7a9cad6
commit b5aec9618f

4
.gitignore vendored

@ -131,4 +131,6 @@ dmypy.json
scratch/
scratch/
.vscode/
.vscode/
.DS_Store/

BIN
benchmarks/.DS_Store vendored

Binary file not shown.

@ -1,296 +1,296 @@
{"tast_id": "median-of-two-sorted-arrays", "prompt": "# Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return the median of the two sorted arrays.\n# \n# \n# Example 1:\n# Input: nums1 = [1,3], nums2 = [2]\n# Output: 2.00000\n# Explanation: merged array = [1,2,3] and median is 2.\n# \n# \n# Example 2:\n# Input: nums1 = [1,2], nums2 = [3,4]\n# Output: 2.50000\n# Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.\n# \n# \n# Example 3:\n# Input: nums1 = [0,0], nums2 = [0,0]\n# Output: 0.00000\n# \n# Example 4:\n# Input: nums1 = [], nums2 = [1]\n# Output: 1.00000\n# \n# Example 5:\n# Input: nums1 = [2], nums2 = []\n# Output: 2.00000\n# \n# Constraints:\n# `nums1.length == m`\n# `nums2.length == n`\n# `0 <= m <= 1000`\n# `0 <= n <= 1000`\n# `1 <= m + n <= 2000`\n# `-106 <= nums1[i], nums2[i] <= 106`\n# Follow up: The overall run time complexity should be `O(log (m+n))`.\nclass Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n ", "entry_point": "findMedianSortedArrays", "cannonical_solution": "", "test": ""}
{"tast_id": "regular-expression-matching", "prompt": "# Given an input string (`s`) and a pattern (`p`), implement regular expression matching with support for `'.'` and `'*'` where:` `\n# `'.'` Matches any single character.\u200b\u200b\u200b\u200b\n# `'*'` Matches zero or more of the preceding element.\n# \n# The matching should cover the entire input string (not partial).\n# \n# \n# Example 1:\n# Input: s = \"aa\", p = \"a\"\n# Output: false\n# Explanation: \"a\" does not match the entire string \"aa\".\n# \n# \n# Example 2:\n# Input: s = \"aa\", p = \"a*\"\n# Output: true\n# Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes \"aa\".\n# \n# \n# Example 3:\n# Input: s = \"ab\", p = \".*\"\n# Output: true\n# Explanation: \".*\" means \"zero or more (*) of any character (.)\".\n# \n# \n# Example 4:\n# Input: s = \"aab\", p = \"c*a*b\"\n# Output: true\n# Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches \"aab\".\n# \n# \n# Example 5:\n# Input: s = \"mississippi\", p = \"mis*is*p*.\"\n# Output: false\n# \n# Constraints:\n# `0 <= s.length <= 20`\n# `0 <= p.length <= 30`\n# `s` contains only lowercase English letters.\n# \n# `p` contains only lowercase English letters, `'.'`, and `'*'`.\n# \n# It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match.\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n ", "entry_point": "isMatch", "cannonical_solution": "", "test": ""}
{"tast_id": "substring-with-concatenation-of-all-words", "prompt": "# You are given a string `s` and an array of strings `words` of the same length. Return all starting indices of substring(s) in `s` that is a concatenation of each word in `words` exactly once, in any order, and without any intervening characters.\n# \n# You can return the answer in any order.\n# \n# \n# Example 1:\n# Input: s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"]\n# Output: [0,9]\n# Explanation: Substrings starting at index 0 and 9 are \"barfoo\" and \"foobar\" respectively.\n# \n# The output order does not matter, returning [9,0] is fine too.\n# \n# \n# Example 2:\n# Input: s = \"wordgoodgoodgoodbestword\", words = [\"word\",\"good\",\"best\",\"word\"]\n# Output: []\n# \n# Example 3:\n# Input: s = \"barfoofoobarthefoobarman\", words = [\"bar\",\"foo\",\"the\"]\n# Output: [6,9,12]\n# \n# Constraints:\n# `1 <= s.length <= 104`\n# `s` consists of lower-case English letters.\n# \n# `1 <= words.length <= 5000`\n# `1 <= words[i].length <= 30`\n# `words[i]` consists of lower-case English letters.\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n ", "entry_point": "findSubstring", "cannonical_solution": "", "test": ""}
{"tast_id": "longest-valid-parentheses", "prompt": "# Given a string containing just the characters `'('` and `')'`, find the length of the longest valid (well-formed) parentheses substring.\n# \n# \n# Example 1:\n# Input: s = \"(()\"\n# Output: 2\n# Explanation: The longest valid parentheses substring is \"()\".\n# \n# \n# Example 2:\n# Input: s = \")()())\"\n# Output: 4\n# Explanation: The longest valid parentheses substring is \"()()\".\n# \n# \n# Example 3:\n# Input: s = \"\"\n# Output: 0\n# \n# Constraints:\n# `0 <= s.length <= 3 * 104`\n# `s[i]` is `'('`, or `')'`.\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n ", "entry_point": "longestValidParentheses", "cannonical_solution": "", "test": ""}
{"tast_id": "first-missing-positive", "prompt": "# Given an unsorted integer array `nums`, find the smallest missing positive integer.\n# \n# \n# Example 1:\n# Input: nums = [1,2,0]\n# Output: 3\n# \n# Example 2:\n# Input: nums = [3,4,-1,1]\n# Output: 2\n# \n# Example 3:\n# Input: nums = [7,8,9,11,12]\n# Output: 1\n# \n# Constraints:\n# `0 <= nums.length <= 300`\n# `-231 <= nums[i] <= 231 - 1`\n# Follow up: Could you implement an algorithm that runs in `O(n)` time and uses constant extra space?\nclass Solution:\n def firstMissingPositive(self, nums: List[int]) -> int:\n ", "entry_point": "firstMissingPositive", "cannonical_solution": "", "test": ""}
{"tast_id": "trapping-rain-water", "prompt": "# Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining.\n# \n# \n# Example 1:\n# Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]\n# Output: 6\n# Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.\n# \n# \n# Example 2:\n# Input: height = [4,2,0,3,2,5]\n# Output: 9\n# \n# Constraints:\n# `n == height.length`\n# `0 <= n <= 3 * 104`\n# `0 <= height[i] <= 105`\nclass Solution:\n def trap(self, height: List[int]) -> int:\n ", "entry_point": "trap", "cannonical_solution": "", "test": ""}
{"tast_id": "wildcard-matching", "prompt": "# Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where:\n# `'?'` Matches any single character.\n# \n# `'*'` Matches any sequence of characters (including the empty sequence).\n# \n# The matching should cover the entire input string (not partial).\n# \n# \n# Example 1:\n# Input: s = \"aa\", p = \"a\"\n# Output: false\n# Explanation: \"a\" does not match the entire string \"aa\".\n# \n# \n# Example 2:\n# Input: s = \"aa\", p = \"*\"\n# Output: true\n# Explanation: '*' matches any sequence.\n# \n# \n# Example 3:\n# Input: s = \"cb\", p = \"?a\"\n# Output: false\n# Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.\n# \n# \n# Example 4:\n# Input: s = \"adceb\", p = \"*a*b\"\n# Output: true\n# Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring \"dce\".\n# \n# \n# Example 5:\n# Input: s = \"acdcb\", p = \"a*c?b\"\n# Output: false\n# \n# Constraints:\n# `0 <= s.length, p.length <= 2000`\n# `s` contains only lowercase English letters.\n# \n# `p` contains only lowercase English letters, `'?'` or `'*'`.\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n ", "entry_point": "isMatch", "cannonical_solution": "", "test": ""}
{"tast_id": "n-queens", "prompt": "# The n-queens puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.\n# \n# Given an integer `n`, return all distinct solutions to the n-queens puzzle.\n# \n# Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.\n# \n# \n# Example 1:\n# Input: n = 4\n# Output: [[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]\n# Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above\n# \n# Example 2:\n# Input: n = 1\n# Output: [[\"Q\"]]\n# \n# Constraints:\n# `1 <= n <= 9`\nclass Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n ", "entry_point": "solveNQueens", "cannonical_solution": "", "test": ""}
{"tast_id": "n-queens-ii", "prompt": "# The n-queens puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.\n# \n# Given an integer `n`, return the number of distinct solutions to the n-queens puzzle.\n# \n# \n# Example 1:\n# Input: n = 4\n# Output: 2\n# Explanation: There are two distinct solutions to the 4-queens puzzle as shown.\n# \n# \n# Example 2:\n# Input: n = 1\n# Output: 1\n# \n# Constraints:\n# `1 <= n <= 9`\nclass Solution:\n def totalNQueens(self, n: int) -> int:\n ", "entry_point": "totalNQueens", "cannonical_solution": "", "test": ""}
{"tast_id": "permutation-sequence", "prompt": "# The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations.\n# \n# By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`:\n# `\"123\"`\n# `\"132\"`\n# `\"213\"`\n# `\"231\"`\n# `\"312\"`\n# `\"321\"`\n# Given `n` and `k`, return the `kth` permutation sequence.\n# \n# \n# Example 1:\n# Input: n = 3, k = 3\n# Output: \"213\"\n# \n# Example 2:\n# Input: n = 4, k = 9\n# Output: \"2314\"\n# \n# Example 3:\n# Input: n = 3, k = 1\n# Output: \"123\"\n# \n# Constraints:\n# `1 <= n <= 9`\n# `1 <= k <= n!`\nclass Solution:\n def getPermutation(self, n: int, k: int) -> str:\n ", "entry_point": "getPermutation", "cannonical_solution": "", "test": ""}
{"tast_id": "valid-number", "prompt": "# A valid number can be split up into these components (in order):\n# A decimal number or an integer.\n# \n# (Optional) An `'e'` or `'E'`, followed by an integer.\n# \n# A decimal number can be split up into these components (in order):\n# (Optional) A sign character (either `'+'` or `'-'`).\n# \n# One of the following formats:\n# \t\n# At least one digit, followed by a dot `'.'`.\n# \n# At least one digit, followed by a dot `'.'`, followed by at least one digit.\n# \n# A dot `'.'`, followed by at least one digit.\n# \n# An integer can be split up into these components (in order):\n# (Optional) A sign character (either `'+'` or `'-'`).\n# \n# At least one digit.\n# \n# For example, all the following are valid numbers: `[\"2\", \"0089\", \"-0.1\", \"+3.14\", \"4.\", \"-.9\", \"2e10\", \"-90E3\", \"3e+7\", \"+6e-1\", \"53.5e93\", \"-123.456e789\"]`, while the following are not valid numbers: `[\"abc\", \"1a\", \"1e\", \"e3\", \"99e2.5\", \"--6\", \"-+3\", \"95a54e53\"]`.\n# \n# Given a string `s`, return `true` if `s` is a valid number.\n# \n# \n# Example 1:\n# Input: s = \"0\"\n# Output: true\n# \n# Example 2:\n# Input: s = \"e\"\n# Output: false\n# \n# Example 3:\n# Input: s = \".\"\n# Output: false\n# \n# Example 4:\n# Input: s = \".1\"\n# Output: true\n# \n# Constraints:\n# `1 <= s.length <= 20`\n# `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.\nclass Solution:\n def isNumber(self, s: str) -> bool:\n ", "entry_point": "isNumber", "cannonical_solution": "", "test": ""}
{"tast_id": "text-justification", "prompt": "# Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.\n# \n# You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly maxWidth characters.\n# \n# Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.\n# \n# For the last line of text, it should be left justified and no extra space is inserted between words.\n# \n# Note:\n# A word is defined as a character sequence consisting of non-space characters only.\n# \n# Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.\n# \n# The input array `words` contains at least one word.\n# \n# \n# Example 1:\n# Input: words = [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"], maxWidth = 16\n# Output:\n# [\n# \"This is an\",\n# \"example of text\",\n# \"justification. \"\n# ]\n# \n# Example 2:\n# Input: words = [\"What\",\"must\",\"be\",\"acknowledgment\",\"shall\",\"be\"], maxWidth = 16\n# Output:\n# [\n# \"What must be\",\n# \"acknowledgment \",\n# \"shall be \"\n# ]\n# Explanation: Note that the last line is \"shall be \" instead of \"shall be\", because the last line must be left-justified instead of fully-justified.\n# \n# Note that the second line is also left-justified becase it contains only one word.\n# \n# \n# Example 3:\n# Input: words = [\"Science\",\"is\",\"what\",\"we\",\"understand\",\"well\",\"enough\",\"to\",\"explain\",\"to\",\"a\",\"computer.\",\"Art\",\"is\",\"everything\",\"else\",\"we\",\"do\"], maxWidth = 20\n# Output:\n# [\n# \"Science is what we\",\n# \"understand well\",\n# \"enough to explain to\",\n# \"a computer. Art is\",\n# \"everything else we\",\n# \"do \"\n# ]\n# \n# Constraints:\n# `1 <= words.length <= 300`\n# `1 <= words[i].length <= 20`\n# `words[i]` consists of only English letters and symbols.\n# \n# `1 <= maxWidth <= 100`\n# `words[i].length <= maxWidth`\nclass Solution:\n def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:\n ", "entry_point": "fullJustify", "cannonical_solution": "", "test": ""}
{"tast_id": "edit-distance", "prompt": "# Given two strings `word1` and `word2`, return the minimum number of operations required to convert `word1` to `word2`.\n# \n# You have the following three operations permitted on a word:\n# Insert a character\n# Delete a character\n# Replace a character\n# \n# Example 1:\n# Input: word1 = \"horse\", word2 = \"ros\"\n# Output: 3\n# Explanation: \n# horse -> rorse (replace 'h' with 'r')\n# rorse -> rose (remove 'r')\n# rose -> ros (remove 'e')\n# \n# Example 2:\n# Input: word1 = \"intention\", word2 = \"execution\"\n# Output: 5\n# Explanation: \n# intention -> inention (remove 't')\n# inention -> enention (replace 'i' with 'e')\n# enention -> exention (replace 'n' with 'x')\n# exention -> exection (replace 'n' with 'c')\n# exection -> execution (insert 'u')\n# \n# Constraints:\n# `0 <= word1.length, word2.length <= 500`\n# `word1` and `word2` consist of lowercase English letters.\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n ", "entry_point": "minDistance", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-window-substring", "prompt": "# Given two strings `s` and `t`, return the minimum window in `s` which will contain all the characters in `t`. If there is no such window in `s` that covers all characters in `t`, return the empty string `\"\"`.\n# \n# Note that If there is such a window, it is guaranteed that there will always be only one unique minimum window in `s`.\n# \n# \n# Example 1:\n# Input: s = \"ADOBECODEBANC\", t = \"ABC\"\n# Output: \"BANC\"\n# \n# Example 2:\n# Input: s = \"a\", t = \"a\"\n# Output: \"a\"\n# \n# Constraints:\n# `1 <= s.length, t.length <= 105`\n# `s` and `t` consist of English letters.\n# \n# Follow up: Could you find an algorithm that runs in `O(n)` time?\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n ", "entry_point": "minWindow", "cannonical_solution": "", "test": ""}
{"tast_id": "largest-rectangle-in-histogram", "prompt": "# Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return the area of the largest rectangle in the histogram.\n# \n# \n# Example 1:\n# Input: heights = [2,1,5,6,2,3]\n# Output: 10\n# Explanation: The above is a histogram where width of each bar is 1.\n# \n# The largest rectangle is shown in the red area, which has an area = 10 units.\n# \n# \n# Example 2:\n# Input: heights = [2,4]\n# Output: 4\n# \n# Constraints:\n# `1 <= heights.length <= 105`\n# `0 <= heights[i] <= 104`\nclass Solution:\n def largestRectangleArea(self, heights: List[int]) -> int:\n ", "entry_point": "largestRectangleArea", "cannonical_solution": "", "test": ""}
{"tast_id": "maximal-rectangle", "prompt": "# Given a `rows x cols` binary `matrix` filled with `0`'s and `1`'s, find the largest rectangle containing only `1`'s and return its area.\n# \n# \n# Example 1:\n# Input: matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\n# Output: 6\n# Explanation: The maximal rectangle is shown in the above picture.\n# \n# \n# Example 2:\n# Input: matrix = []\n# Output: 0\n# \n# Example 3:\n# Input: matrix = [[\"0\"]]\n# Output: 0\n# \n# Example 4:\n# Input: matrix = [[\"1\"]]\n# Output: 1\n# \n# Example 5:\n# Input: matrix = [[\"0\",\"0\"]]\n# Output: 0\n# \n# Constraints:\n# `rows == matrix.length`\n# `cols == matrix[i].length`\n# `0 <= row, cols <= 200`\n# `matrix[i][j]` is `'0'` or `'1'`.\nclass Solution:\n def maximalRectangle(self, matrix: List[List[str]]) -> int:\n ", "entry_point": "maximalRectangle", "cannonical_solution": "", "test": ""}
{"tast_id": "scramble-string", "prompt": "# We can scramble a string s to get a string t using the following algorithm:\n# If the length of the string is 1, stop.\n# \n# If the length of the string is > 1, do the following:\n# \t\n# Split the string into two non-empty substrings at a random index, i.e., if the string is `s`, divide it to `x` and `y` where `s = x + y`.\n# \n# Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, `s` may become `s = x + y` or `s = y + x`.\n# \n# Apply step 1 recursively on each of the two substrings `x` and `y`.\n# \n# Given two strings `s1` and `s2` of the same length, return `true` if `s2` is a scrambled string of `s1`, otherwise, return `false`.\n# \n# \n# Example 1:\n# Input: s1 = \"great\", s2 = \"rgeat\"\n# Output: true\n# Explanation: One possible scenario applied on s1 is:\n# \"great\" --> \"gr/eat\" // divide at random index.\n# \n# \"gr/eat\" --> \"gr/eat\" // random decision is not to swap the two substrings and keep them in order.\n# \n# \"gr/eat\" --> \"g/r / e/at\" // apply the same algorithm recursively on both substrings. divide at ranom index each of them.\n# \n# \"g/r / e/at\" --> \"r/g / e/at\" // random decision was to swap the first substring and to keep the second substring in the same order.\n# \n# \"r/g / e/at\" --> \"r/g / e/ a/t\" // again apply the algorithm recursively, divide \"at\" to \"a/t\".\n# \n# \"r/g / e/ a/t\" --> \"r/g / e/ a/t\" // random decision is to keep both substrings in the same order.\n# \n# The algorithm stops now and the result string is \"rgeat\" which is s2.\n# \n# As there is one possible scenario that led s1 to be scrambled to s2, we return true.\n# \n# \n# Example 2:\n# Input: s1 = \"abcde\", s2 = \"caebd\"\n# Output: false\n# \n# Example 3:\n# Input: s1 = \"a\", s2 = \"a\"\n# Output: true\n# \n# Constraints:\n# `s1.length == s2.length`\n# `1 <= s1.length <= 30`\n# `s1` and `s2` consist of lower-case English letters.\nclass Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n ", "entry_point": "isScramble", "cannonical_solution": "", "test": ""}
{"tast_id": "distinct-subsequences", "prompt": "# Given two strings `s` and `t`, return the number of distinct subsequences of `s` which equals `t`.\n# \n# A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., `\"ACE\"` is a subsequence of `\"ABCDE\"` while `\"AEC\"` is not).\n# \n# It is guaranteed the answer fits on a 32-bit signed integer.\n# \n# \n# Example 1:\n# Input: s = \"rabbbit\", t = \"rabbit\"\n# Output: 3\n# Explanation:\n# As shown below, there are 3 ways you can generate \"rabbit\" from S.\n# \n# `rabbbit`\n# `rabbbit`\n# `rabbbit`\n# \n# Example 2:\n# Input: s = \"babgbag\", t = \"bag\"\n# Output: 5\n# Explanation:\n# As shown below, there are 5 ways you can generate \"bag\" from S.\n# \n# `babgbag`\n# `babgbag`\n# `babgbag`\n# `babgbag`\n# `babgbag`\n# \n# Constraints:\n# `1 <= s.length, t.length <= 1000`\n# `s` and `t` consist of English letters.\nclass Solution:\n def numDistinct(self, s: str, t: str) -> int:\n ", "entry_point": "numDistinct", "cannonical_solution": "", "test": ""}
{"tast_id": "best-time-to-buy-and-sell-stock-iii", "prompt": "# You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.\n# \n# Find the maximum profit you can achieve. You may complete at most two transactions.\n# \n# Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n# \n# \n# Example 1:\n# Input: prices = [3,3,5,0,0,3,1,4]\n# Output: 6\n# Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n# \n# Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.\n# \n# \n# Example 2:\n# Input: prices = [1,2,3,4,5]\n# Output: 4\n# Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\n# \n# Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.\n# \n# \n# Example 3:\n# Input: prices = [7,6,4,3,1]\n# Output: 0\n# Explanation: In this case, no transaction is done, i.e. max profit = 0.\n# \n# \n# Example 4:\n# Input: prices = [1]\n# Output: 0\n# \n# Constraints:\n# `1 <= prices.length <= 105`\n# `0 <= prices[i] <= 105`\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n ", "entry_point": "maxProfit", "cannonical_solution": "", "test": ""}
{"tast_id": "word-ladder-ii", "prompt": "# A transformation sequence from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:\n# Every adjacent pair of words differs by a single letter.\n# \n# Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.\n# \n# `sk == endWord`\n# Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return all the shortest transformation sequences from `beginWord` to `endWord`, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words `[beginWord, s1, s2, ..., sk]`.\n# \n# \n# Example 1:\n# Input: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\n# Output: [[\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],[\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]]\n# Explanation: There are 2 shortest transformation sequences:\n# \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> \"cog\"\n# \"hit\" -> \"hot\" -> \"lot\" -> \"log\" -> \"cog\"\n# \n# Example 2:\n# Input: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n# Output: []\n# Explanation: The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.\n# \n# \n# Constraints:\n# `1 <= beginWord.length <= 10`\n# `endWord.length == beginWord.length`\n# `1 <= wordList.length <= 5000`\n# `wordList[i].length == beginWord.length`\n# `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.\n# \n# `beginWord != endWord`\n# All the words in `wordList` are unique.\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n ", "entry_point": "findLadders", "cannonical_solution": "", "test": ""}
{"tast_id": "word-ladder", "prompt": "# A transformation sequence from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:\n# Every adjacent pair of words differs by a single letter.\n# \n# Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.\n# \n# `sk == endWord`\n# Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return the number of words in the shortest transformation sequence from `beginWord` to `endWord`, or `0` if no such sequence exists.\n# \n# \n# Example 1:\n# Input: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\n# Output: 5\n# Explanation: One shortest transformation sequence is \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> cog\", which is 5 words long.\n# \n# \n# Example 2:\n# Input: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n# Output: 0\n# Explanation: The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.\n# \n# \n# Constraints:\n# `1 <= beginWord.length <= 10`\n# `endWord.length == beginWord.length`\n# `1 <= wordList.length <= 5000`\n# `wordList[i].length == beginWord.length`\n# `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.\n# \n# `beginWord != endWord`\n# All the words in `wordList` are unique.\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n ", "entry_point": "ladderLength", "cannonical_solution": "", "test": ""}
{"tast_id": "longest-consecutive-sequence", "prompt": "# Given an unsorted array of integers `nums`, return the length of the longest consecutive elements sequence.\n# \n# \n# Example 1:\n# Input: nums = [100,4,200,1,3,2]\n# Output: 4\n# Explanation: The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4.\n# \n# \n# Example 2:\n# Input: nums = [0,3,7,2,5,8,4,6,0,1]\n# Output: 9\n# \n# Constraints:\n# `0 <= nums.length <= 104`\n# `-109 <= nums[i] <= 109`\n# Follow up: Could you implement the `O(n)` solution?\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n ", "entry_point": "longestConsecutive", "cannonical_solution": "", "test": ""}
{"tast_id": "palindrome-partitioning-ii", "prompt": "# Given a string `s`, partition `s` such that every substring of the partition is a palindrome.\n# \n# Return the minimum cuts needed for a palindrome partitioning of `s`.\n# \n# \n# Example 1:\n# Input: s = \"aab\"\n# Output: 1\n# Explanation: The palindrome partitioning [\"aa\",\"b\"] could be produced using 1 cut.\n# \n# \n# Example 2:\n# Input: s = \"a\"\n# Output: 0\n# \n# Example 3:\n# Input: s = \"ab\"\n# Output: 1\n# \n# Constraints:\n# `1 <= s.length <= 2000`\n# `s` consists of lower-case English letters only.\nclass Solution:\n def minCut(self, s: str) -> int:\n ", "entry_point": "minCut", "cannonical_solution": "", "test": ""}
{"tast_id": "candy", "prompt": "# There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`.\n# \n# You are giving candies to these children subjected to the following requirements:\n# Each child must have at least one candy.\n# \n# Children with a higher rating get more candies than their neighbors.\n# \n# Return the minimum number of candies you need to have to distribute the candies to the children.\n# \n# \n# Example 1:\n# Input: ratings = [1,0,2]\n# Output: 5\n# Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.\n# \n# \n# Example 2:\n# Input: ratings = [1,2,2]\n# Output: 4\n# Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.\n# \n# The third child gets 1 candy because it satisfies the above two conditions.\n# \n# \n# Constraints:\n# `n == ratings.length`\n# `1 <= n <= 2 * 104`\n# `0 <= ratings[i] <= 2 * 104`\nclass Solution:\n def candy(self, ratings: List[int]) -> int:\n ", "entry_point": "candy", "cannonical_solution": "", "test": ""}
{"tast_id": "word-break-ii", "prompt": "# Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.\n# \n# Note that the same word in the dictionary may be reused multiple times in the segmentation.\n# \n# \n# Example 1:\n# Input: s = \"catsanddog\", wordDict = [\"cat\",\"cats\",\"and\",\"sand\",\"dog\"]\n# Output: [\"cats and dog\",\"cat sand dog\"]\n# \n# Example 2:\n# Input: s = \"pineapplepenapple\", wordDict = [\"apple\",\"pen\",\"applepen\",\"pine\",\"pineapple\"]\n# Output: [\"pine apple pen apple\",\"pineapple pen apple\",\"pine applepen apple\"]\n# Explanation: Note that you are allowed to reuse a dictionary word.\n# \n# \n# Example 3:\n# Input: s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]\n# Output: []\n# \n# Constraints:\n# `1 <= s.length <= 20`\n# `1 <= wordDict.length <= 1000`\n# `1 <= wordDict[i].length <= 10`\n# `s` and `wordDict[i]` consist of only lowercase English letters.\n# \n# All the strings of `wordDict` are unique.\nclass Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:\n ", "entry_point": "wordBreak", "cannonical_solution": "", "test": ""}
{"tast_id": "max-points-on-a-line", "prompt": "# Given an array of `points` where `points[i] = [xi, yi]` represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.\n# \n# \n# Example 1:\n# Input: points = [[1,1],[2,2],[3,3]]\n# Output: 3\n# \n# Example 2:\n# Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\n# Output: 4\n# \n# Constraints:\n# `1 <= points.length <= 300`\n# `points[i].length == 2`\n# `-104 <= xi, yi <= 104`\n# All the `points` are unique.\nclass Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n ", "entry_point": "maxPoints", "cannonical_solution": "", "test": ""}
{"tast_id": "find-minimum-in-rotated-sorted-array-ii", "prompt": "# Suppose an array of length `n` sorted in ascending order is rotated between `1` and `n` times. For example, the array `nums = [0,1,4,4,5,6,7]` might become:\n# `[4,5,6,7,0,1,4]` if it was rotated `4` times.\n# \n# `[0,1,4,4,5,6,7]` if it was rotated `7` times.\n# \n# Notice that rotating an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.\n# \n# Given the sorted rotated array `nums` that may contain duplicates, return the minimum element of this array.\n# \n# \n# Example 1:\n# Input: nums = [1,3,5]\n# Output: 1\n# \n# Example 2:\n# Input: nums = [2,2,2,0,1]\n# Output: 0\n# \n# Constraints:\n# `n == nums.length`\n# `1 <= n <= 5000`\n# `-5000 <= nums[i] <= 5000`\n# `nums` is sorted and rotated between `1` and `n` times.\n# \n# Follow up: This is the same as Find Minimum in Rotated Sorted Array but with duplicates. Would allow duplicates affect the run-time complexity? How and why?\nclass Solution:\n def findMin(self, nums: List[int]) -> int:\n ", "entry_point": "findMin", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-gap", "prompt": "# Given an integer array `nums`, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return `0`.\n# \n# \n# Example 1:\n# Input: nums = [3,6,9,1]\n# Output: 3\n# Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.\n# \n# \n# Example 2:\n# Input: nums = [10]\n# Output: 0\n# Explanation: The array contains less than 2 elements, therefore return 0.\n# \n# \n# Constraints:\n# `1 <= nums.length <= 104`\n# `0 <= nums[i] <= 109`\n# Follow up: Could you solve it in linear time/space?\nclass Solution:\n def maximumGap(self, nums: List[int]) -> int:\n ", "entry_point": "maximumGap", "cannonical_solution": "", "test": ""}
{"tast_id": "dungeon-game", "prompt": "# The demons had captured the princess and imprisoned her in the bottom-right corner of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through `dungeon` to rescue the princess.\n# \n# The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately.\n# \n# Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).\n# \n# To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.\n# \n# Return the knight's minimum initial health so that he can rescue the princess.\n# \n# Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.\n# \n# \n# Example 1:\n# Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]\n# Output: 7\n# Explanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.\n# \n# \n# Example 2:\n# Input: dungeon = [[0]]\n# Output: 1\n# \n# Constraints:\n# `m == dungeon.length`\n# `n == dungeon[i].length`\n# `1 <= m, n <= 200`\n# `-1000 <= dungeon[i][j] <= 1000`\nclass Solution:\n def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:\n ", "entry_point": "calculateMinimumHP", "cannonical_solution": "", "test": ""}
{"tast_id": "best-time-to-buy-and-sell-stock-iv", "prompt": "# You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `k`.\n# \n# Find the maximum profit you can achieve. You may complete at most `k` transactions.\n# \n# Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n# \n# \n# Example 1:\n# Input: k = 2, prices = [2,4,1]\n# Output: 2\n# Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.\n# \n# \n# Example 2:\n# Input: k = 2, prices = [3,2,6,5,0,3]\n# Output: 7\n# Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n# \n# \n# Constraints:\n# `0 <= k <= 100`\n# `0 <= prices.length <= 1000`\n# `0 <= prices[i] <= 1000`\nclass Solution:\n def maxProfit(self, k: int, prices: List[int]) -> int:\n ", "entry_point": "maxProfit", "cannonical_solution": "", "test": ""}
{"tast_id": "word-search-ii", "prompt": "# Given an `m x n` `board` of characters and a list of strings `words`, return all words on the board.\n# \n# Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.\n# \n# \n# Example 1:\n# Input: board = [[\"o\",\"a\",\"a\",\"n\"],[\"e\",\"t\",\"a\",\"e\"],[\"i\",\"h\",\"k\",\"r\"],[\"i\",\"f\",\"l\",\"v\"]], words = [\"oath\",\"pea\",\"eat\",\"rain\"]\n# Output: [\"eat\",\"oath\"]\n# \n# Example 2:\n# Input: board = [[\"a\",\"b\"],[\"c\",\"d\"]], words = [\"abcb\"]\n# Output: []\n# \n# Constraints:\n# `m == board.length`\n# `n == board[i].length`\n# `1 <= m, n <= 12`\n# `board[i][j]` is a lowercase English letter.\n# \n# `1 <= words.length <= 3 * 104`\n# `1 <= words[i].length <= 10`\n# `words[i]` consists of lowercase English letters.\n# \n# All the strings of `words` are unique.\nclass Solution:\n def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n ", "entry_point": "findWords", "cannonical_solution": "", "test": ""}
{"tast_id": "shortest-palindrome", "prompt": "# You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it.\n# \n# Return the shortest palindrome you can find by performing this transformation.\n# \n# \n# Example 1:\n# Input: s = \"aacecaaa\"\n# Output: \"aaacecaaa\"\n# \n# Example 2:\n# Input: s = \"abcd\"\n# Output: \"dcbabcd\"\n# \n# Constraints:\n# `0 <= s.length <= 5 * 104`\n# `s` consists of lowercase English letters only.\nclass Solution:\n def shortestPalindrome(self, s: str) -> str:\n ", "entry_point": "shortestPalindrome", "cannonical_solution": "", "test": ""}
{"tast_id": "the-skyline-problem", "prompt": "# A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.\n# \n# The geometric information of each building is given in the array `buildings` where `buildings[i] = [lefti, righti, heighti]`:\n# `lefti` is the x coordinate of the left edge of the `ith` building.\n# \n# `righti` is the x coordinate of the right edge of the `ith` building.\n# \n# `heighti` is the height of the `ith` building.\n# \n# You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height `0`.\n# \n# The skyline should be represented as a list of \"key points\" sorted by their x-coordinate in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate `0` and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.\n# \n# Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is not acceptable; the three lines of height 5 should be merged into one in the final output as such: `[...,[2 3],[4 5],[12 7],...]`\n# \n# Example 1:\n# Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]\n# Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]\n# Explanation:\n# Figure A shows the buildings of the input.\n# \n# Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.\n# \n# \n# Example 2:\n# Input: buildings = [[0,2,3],[2,5,3]]\n# Output: [[0,3],[5,0]]\n# \n# Constraints:\n# `1 <= buildings.length <= 104`\n# `0 <= lefti < righti <= 231 - 1`\n# `1 <= heighti <= 231 - 1`\n# `buildings` is sorted by `lefti` in non-decreasing order.\nclass Solution:\n def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:\n ", "entry_point": "getSkyline", "cannonical_solution": "", "test": ""}
{"tast_id": "basic-calculator", "prompt": "# Given a string `s` representing an expression, implement a basic calculator to evaluate it.\n# \n# \n# Example 1:\n# Input: s = \"1 + 1\"\n# Output: 2\n# \n# Example 2:\n# Input: s = \" 2-1 + 2 \"\n# Output: 3\n# \n# Example 3:\n# Input: s = \"(1+(4+5+2)-3)+(6+8)\"\n# Output: 23\n# \n# Constraints:\n# `1 <= s.length <= 3 * 105`\n# `s` consists of digits, `'+'`, `'-'`, `'('`, `')'`, and `' '`.\n# \n# `s` represents a valid expression.\nclass Solution:\n def calculate(self, s: str) -> int:\n ", "entry_point": "calculate", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-digit-one", "prompt": "# Given an integer `n`, count the total number of digit `1` appearing in all non-negative integers less than or equal to `n`.\n# \n# \n# Example 1:\n# Input: n = 13\n# Output: 6\n# \n# Example 2:\n# Input: n = 0\n# Output: 0\n# \n# Constraints:\n# `0 <= n <= 2 * 109`\nclass Solution:\n def countDigitOne(self, n: int) -> int:\n ", "entry_point": "countDigitOne", "cannonical_solution": "", "test": ""}
{"tast_id": "sliding-window-maximum", "prompt": "# You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.\n# \n# Return the max sliding window.\n# \n# \n# Example 1:\n# Input: nums = [1,3,-1,-3,5,3,6,7], k = 3\n# Output: [3,3,5,5,6,7]\n# Explanation: \n# Window position Max\n# --------------- -----\n# [1 3 -1] -3 5 3 6 7 3\n# 1 [3 -1 -3] 5 3 6 7 3\n# 1 3 [-1 -3 5] 3 6 7 5\n# 1 3 -1 [-3 5 3] 6 7 5\n# 1 3 -1 -3 [5 3 6] 7 6\n# 1 3 -1 -3 5 [3 6 7] 7\n# \n# Example 2:\n# Input: nums = [1], k = 1\n# Output: [1]\n# \n# Example 3:\n# Input: nums = [1,-1], k = 1\n# Output: [1,-1]\n# \n# Example 4:\n# Input: nums = [9,11], k = 2\n# Output: [11]\n# \n# Example 5:\n# Input: nums = [4,-2], k = 2\n# Output: [4]\n# \n# Constraints:\n# `1 <= nums.length <= 105`\n# `-104 <= nums[i] <= 104`\n# `1 <= k <= nums.length`\nclass Solution:\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n ", "entry_point": "maxSlidingWindow", "cannonical_solution": "", "test": ""}
{"tast_id": "integer-to-english-words", "prompt": "# Convert a non-negative integer `num` to its English words representation.\n# \n# \n# Example 1:\n# Input: num = 123\n# Output: \"One Hundred Twenty Three\"\n# \n# Example 2:\n# Input: num = 12345\n# Output: \"Twelve Thousand Three Hundred Forty Five\"\n# \n# Example 3:\n# Input: num = 1234567\n# Output: \"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven\"\n# \n# Example 4:\n# Input: num = 1234567891\n# Output: \"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One\"\n# \n# Constraints:\n# `0 <= num <= 231 - 1`\nclass Solution:\n def numberToWords(self, num: int) -> str:\n ", "entry_point": "numberToWords", "cannonical_solution": "", "test": ""}
{"tast_id": "expression-add-operators", "prompt": "# Given a string `num` that contains only digits and an integer `target`, return all possibilities to add the binary operators `'+'`, `'-'`, or `'*'` between the digits of `num` so that the resultant expression evaluates to the `target` value.\n# \n# \n# Example 1:\n# Input: num = \"123\", target = 6\n# Output: [\"1*2*3\",\"1+2+3\"]\n# \n# Example 2:\n# Input: num = \"232\", target = 8\n# Output: [\"2*3+2\",\"2+3*2\"]\n# \n# Example 3:\n# Input: num = \"105\", target = 5\n# Output: [\"1*0+5\",\"10-5\"]\n# \n# Example 4:\n# Input: num = \"00\", target = 0\n# Output: [\"0*0\",\"0+0\",\"0-0\"]\n# \n# Example 5:\n# Input: num = \"3456237490\", target = 9191\n# Output: []\n# \n# Constraints:\n# `1 <= num.length <= 10`\n# `num` consists of only digits.\n# \n# `-231 <= target <= 231 - 1`\nclass Solution:\n def addOperators(self, num: str, target: int) -> List[str]:\n ", "entry_point": "addOperators", "cannonical_solution": "", "test": ""}
{"tast_id": "find-median-from-data-stream", "prompt": "# The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.\n# \n# For example, for `arr = [2,3,4]`, the median is `3`.\n# \n# For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`.\n# \n# Implement the MedianFinder class:\n# `MedianFinder()` initializes the `MedianFinder` object.\n# \n# `void addNum(int num)` adds the integer `num` from the data stream to the data structure.\n# \n# `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted.\n# \n# \n# Example 1:\n# Input\n# [\"MedianFinder\", \"addNum\", \"addNum\", \"findMedian\", \"addNum\", \"findMedian\"]\n# [[], [1], [2], [], [3], []]\n# Output\n# [null, null, null, 1.5, null, 2.0]\n# Explanation\n# MedianFinder medianFinder = new MedianFinder();\n# medianFinder.addNum(1); // arr = [1]\n# medianFinder.addNum(2); // arr = [1, 2]\n# medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\n# medianFinder.addNum(3); // arr[1, 2, 3]\n# medianFinder.findMedian(); // return 2.0\n# \n# Constraints:\n# `-105 <= num <= 105`\n# There will be at least one element in the data structure before calling `findMedian`.\n# \n# At most `5 * 104` calls will be made to `addNum` and `findMedian`.\n# \n# Follow up:\n# If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?\n# If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?\nclass MedianFinder:\n\n def __init__(self):\n \n\n def addNum(self, num: int) -> None:\n \n\n def findMedian(self) -> float:\n \n\n\n# Your MedianFinder object will be instantiated and called as such:\n# obj = MedianFinder()\n# obj.addNum(num)\n# param_2 = obj.findMedian()", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "remove-invalid-parentheses", "prompt": "# Given a string `s` that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.\n# \n# Return all the possible results. You may return the answer in any order.\n# \n# \n# Example 1:\n# Input: s = \"()())()\"\n# Output: [\"(())()\",\"()()()\"]\n# \n# Example 2:\n# Input: s = \"(a)())()\"\n# Output: [\"(a())()\",\"(a)()()\"]\n# \n# Example 3:\n# Input: s = \")(\"\n# Output: [\"\"]\n# \n# Constraints:\n# `1 <= s.length <= 25`\n# `s` consists of lowercase English letters and parentheses `'('` and `')'`.\n# \n# There will be at most `20` parentheses in `s`.\nclass Solution:\n def removeInvalidParentheses(self, s: str) -> List[str]:\n ", "entry_point": "removeInvalidParentheses", "cannonical_solution": "", "test": ""}
{"tast_id": "burst-balloons", "prompt": "# You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons.\n# \n# If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, then treat it as if there is a balloon with a `1` painted on it.\n# \n# Return the maximum coins you can collect by bursting the balloons wisely.\n# \n# \n# Example 1:\n# Input: nums = [3,1,5,8]\n# Output: 167\n# Explanation:\n# nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []\n# coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167\n# \n# Example 2:\n# Input: nums = [1,5]\n# Output: 10\n# \n# Constraints:\n# `n == nums.length`\n# `1 <= n <= 500`\n# `0 <= nums[i] <= 100`\nclass Solution:\n def maxCoins(self, nums: List[int]) -> int:\n ", "entry_point": "maxCoins", "cannonical_solution": "", "test": ""}
{"tast_id": "count-of-smaller-numbers-after-self", "prompt": "# You are given an integer array `nums` and you have to return a new `counts` array. The `counts` array has the property where `counts[i]` is the number of smaller elements to the right of `nums[i]`.\n# \n# \n# Example 1:\n# Input: nums = [5,2,6,1]\n# Output: [2,1,1,0]\n# Explanation:\n# To the right of 5 there are 2 smaller elements (2 and 1).\n# \n# To the right of 2 there is only 1 smaller element (1).\n# \n# To the right of 6 there is 1 smaller element (1).\n# \n# To the right of 1 there is 0 smaller element.\n# \n# \n# Example 2:\n# Input: nums = [-1]\n# Output: [0]\n# \n# Example 3:\n# Input: nums = [-1,-1]\n# Output: [0,0]\n# \n# Constraints:\n# `1 <= nums.length <= 105`\n# `-104 <= nums[i] <= 104`\nclass Solution:\n def countSmaller(self, nums: List[int]) -> List[int]:\n ", "entry_point": "countSmaller", "cannonical_solution": "", "test": ""}
{"tast_id": "create-maximum-number", "prompt": "# You are given two integer arrays `nums1` and `nums2` of lengths `m` and `n` respectively. `nums1` and `nums2` represent the digits of two numbers. You are also given an integer `k`.\n# \n# Create the maximum number of length `k <= m + n` from digits of the two numbers. The relative order of the digits from the same array must be preserved.\n# \n# Return an array of the `k` digits representing the answer.\n# \n# \n# Example 1:\n# Input: nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5\n# Output: [9,8,6,5,3]\n# \n# Example 2:\n# Input: nums1 = [6,7], nums2 = [6,0,4], k = 5\n# Output: [6,7,6,0,4]\n# \n# Example 3:\n# Input: nums1 = [3,9], nums2 = [8,9], k = 3\n# Output: [9,8,9]\n# \n# Constraints:\n# `m == nums1.length`\n# `n == nums2.length`\n# `1 <= m, n <= 500`\n# `0 <= nums1[i], nums2[i] <= 9`\n# `1 <= k <= m + n`\n# Follow up: Try to optimize your time and space complexity.\nclass Solution:\n def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:\n ", "entry_point": "maxNumber", "cannonical_solution": "", "test": ""}
{"tast_id": "count-of-range-sum", "prompt": "# Given an integer array `nums` and two integers `lower` and `upper`, return the number of range sums that lie in `[lower, upper]` inclusive.\n# \n# Range sum `S(i, j)` is defined as the sum of the elements in `nums` between indices `i` and `j` inclusive, where `i <= j`.\n# \n# \n# Example 1:\n# Input: nums = [-2,5,-1], lower = -2, upper = 2\n# Output: 3\n# Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.\n# \n# \n# Example 2:\n# Input: nums = [0], lower = 0, upper = 0\n# Output: 1\n# \n# Constraints:\n# `1 <= nums.length <= 104`\n# `-231 <= nums[i] <= 231 - 1`\n# `-3 * 104 <= lower <= upper <= 3 * 104`\n# Follow up: A naive algorithm of `O(n2)` is trivial, Could you do better than that?\nclass Solution:\n def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:\n ", "entry_point": "countRangeSum", "cannonical_solution": "", "test": ""}
{"tast_id": "longest-increasing-path-in-a-matrix", "prompt": "# Given an `m x n` integers `matrix`, return the length of the longest increasing path in `matrix`.\n# \n# From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).\n# \n# \n# Example 1:\n# Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]\n# Output: 4\n# Explanation: The longest increasing path is `[1, 2, 6, 9]`.\n# \n# \n# Example 2:\n# Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]\n# Output: 4\n# Explanation: The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed.\n# \n# \n# Example 3:\n# Input: matrix = [[1]]\n# Output: 1\n# \n# Constraints:\n# `m == matrix.length`\n# `n == matrix[i].length`\n# `1 <= m, n <= 200`\n# `0 <= matrix[i][j] <= 231 - 1`\nclass Solution:\n def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n ", "entry_point": "longestIncreasingPath", "cannonical_solution": "", "test": ""}
{"tast_id": "patching-array", "prompt": "# Given a sorted integer array `nums` and an integer `n`, add/patch elements to the array such that any number in the range `[1, n]` inclusive can be formed by the sum of some elements in the array.\n# \n# Return the minimum number of patches required.\n# \n# \n# Example 1:\n# Input: nums = [1,3], n = 6\n# Output: 1\n# Explanation:\n# Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\n# \n# Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\n# \n# Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\n# \n# So we only need 1 patch.\n# \n# \n# Example 2:\n# Input: nums = [1,5,10], n = 20\n# Output: 2\n# Explanation: The two patches can be [2, 4].\n# \n# \n# Example 3:\n# Input: nums = [1,2,2], n = 5\n# Output: 0\n# \n# Constraints:\n# `1 <= nums.length <= 1000`\n# `1 <= nums[i] <= 104`\n# `nums` is sorted in ascending order.\n# \n# `1 <= n <= 231 - 1`\nclass Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n ", "entry_point": "minPatches", "cannonical_solution": "", "test": ""}
{"tast_id": "self-crossing", "prompt": "# You are given an array of integers `distance`.\n# \n# You start at point `(0,0)` on an X-Y plane and you move `distance[0]` meters to the north, then `distance[1]` meters to the west, `distance[2]` meters to the south, `distance[3]` meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.\n# \n# Return `true` if your path crosses itself, and `false` if it does not.\n# \n# \n# Example 1:\n# Input: distance = [2,1,1,2]\n# Output: true\n# \n# Example 2:\n# Input: distance = [1,2,3,4]\n# Output: false\n# \n# Example 3:\n# Input: distance = [1,1,1,1]\n# Output: true\n# \n# Constraints:\n# `1 <= distance.length <= 500`\n# `1 <= distance[i] <= 500`\n# Follow up: Could you write a one-pass algorithm with `O(1)` extra space?\nclass Solution:\n def isSelfCrossing(self, distance: List[int]) -> bool:\n ", "entry_point": "isSelfCrossing", "cannonical_solution": "", "test": ""}
{"tast_id": "palindrome-pairs", "prompt": "# Given a list of unique words, return all the pairs of the distinct indices `(i, j)` in the given list, so that the concatenation of the two words `words[i] + words[j]` is a palindrome.\n# \n# \n# Example 1:\n# Input: words = [\"abcd\",\"dcba\",\"lls\",\"s\",\"sssll\"]\n# Output: [[0,1],[1,0],[3,2],[2,4]]\n# Explanation: The palindromes are [\"dcbaabcd\",\"abcddcba\",\"slls\",\"llssssll\"]\n# \n# Example 2:\n# Input: words = [\"bat\",\"tab\",\"cat\"]\n# Output: [[0,1],[1,0]]\n# Explanation: The palindromes are [\"battab\",\"tabbat\"]\n# \n# Example 3:\n# Input: words = [\"a\",\"\"]\n# Output: [[0,1],[1,0]]\n# \n# Constraints:\n# `1 <= words.length <= 5000`\n# `0 <= words[i].length <= 300`\n# `words[i]` consists of lower-case English letters.\nclass Solution:\n def palindromePairs(self, words: List[str]) -> List[List[int]]:\n ", "entry_point": "palindromePairs", "cannonical_solution": "", "test": ""}
{"tast_id": "data-stream-as-disjoint-intervals", "prompt": "# Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals.\n# \n# Implement the `SummaryRanges` class:\n# `SummaryRanges()` Initializes the object with an empty stream.\n# \n# `void addNum(int val)` Adds the integer `val` to the stream.\n# \n# `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`.\n# \n# \n# Example 1:\n# Input\n# [\"SummaryRanges\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\"]\n# [[], [1], [], [3], [], [7], [], [2], [], [6], []]\n# Output\n# [null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]\n# Explanation\n# SummaryRanges summaryRanges = new SummaryRanges();\n# summaryRanges.addNum(1); // arr = [1]\n# summaryRanges.getIntervals(); // return [[1, 1]]\n# summaryRanges.addNum(3); // arr = [1, 3]\n# summaryRanges.getIntervals(); // return [[1, 1], [3, 3]]\n# summaryRanges.addNum(7); // arr = [1, 3, 7]\n# summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]\n# summaryRanges.addNum(2); // arr = [1, 2, 3, 7]\n# summaryRanges.getIntervals(); // return [[1, 3], [7, 7]]\n# summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]\n# summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]\n# \n# Constraints:\n# `0 <= val <= 104`\n# At most `3 * 104` calls will be made to `addNum` and `getIntervals`.\n# \n# Follow up: What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?\nclass SummaryRanges:\n\n def __init__(self):\n \n\n def addNum(self, value: int) -> None:\n \n\n def getIntervals(self) -> List[List[int]]:\n \n\n\n# Your SummaryRanges object will be instantiated and called as such:\n# obj = SummaryRanges()\n# obj.addNum(value)\n# param_2 = obj.getIntervals()", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "russian-doll-envelopes", "prompt": "# You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope.\n# \n# One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.\n# \n# Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).\n# \n# Note: You cannot rotate an envelope.\n# \n# \n# Example 1:\n# Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]\n# Output: 3\n# Explanation: The maximum number of envelopes you can Russian doll is `3` ([2,3] => [5,4] => [6,7]).\n# \n# \n# Example 2:\n# Input: envelopes = [[1,1],[1,1],[1,1]]\n# Output: 1\n# \n# Constraints:\n# `1 <= envelopes.length <= 5000`\n# `envelopes[i].length == 2`\n# `1 <= wi, hi <= 104`\nclass Solution:\n def maxEnvelopes(self, envelopes: List[List[int]]) -> int:\n ", "entry_point": "maxEnvelopes", "cannonical_solution": "", "test": ""}
{"tast_id": "max-sum-of-rectangle-no-larger-than-k", "prompt": "# Given an `m x n` matrix `matrix` and an integer `k`, return the max sum of a rectangle in the matrix such that its sum is no larger than `k`.\n# \n# It is guaranteed that there will be a rectangle with a sum no larger than `k`.\n# \n# \n# Example 1:\n# Input: matrix = [[1,0,1],[0,-2,3]], k = 2\n# Output: 2\n# Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).\n# \n# \n# Example 2:\n# Input: matrix = [[2,2,-1]], k = 3\n# Output: 3\n# \n# Constraints:\n# `m == matrix.length`\n# `n == matrix[i].length`\n# `1 <= m, n <= 100`\n# `-100 <= matrix[i][j] <= 100`\n# `-105 <= k <= 105`\n# Follow up: What if the number of rows is much larger than the number of columns?\nclass Solution:\n def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:\n ", "entry_point": "maxSumSubmatrix", "cannonical_solution": "", "test": ""}
{"tast_id": "perfect-rectangle", "prompt": "# Given an array `rectangles` where `rectangles[i] = [xi, yi, ai, bi]` represents an axis-aligned rectangle. The bottom-left point of the rectangle is `(xi, yi)` and the top-right point of it is `(ai, bi)`.\n# \n# Return `true` if all the rectangles together form an exact cover of a rectangular region.\n# \n# \n# Example 1:\n# Input: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]\n# Output: true\n# Explanation: All 5 rectangles together form an exact cover of a rectangular region.\n# \n# \n# Example 2:\n# Input: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]\n# Output: false\n# Explanation: Because there is a gap between the two rectangular regions.\n# \n# \n# Example 3:\n# Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[3,2,4,4]]\n# Output: false\n# Explanation: Because there is a gap in the top center.\n# \n# \n# Example 4:\n# Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]\n# Output: false\n# Explanation: Because two of the rectangles overlap with each other.\n# \n# \n# Constraints:\n# `1 <= rectangles.length <= 2 * 104`\n# `rectangles[i].length == 4`\n# `-105 <= xi, yi, ai, bi <= 105`\nclass Solution:\n def isRectangleCover(self, rectangles: List[List[int]]) -> bool:\n ", "entry_point": "isRectangleCover", "cannonical_solution": "", "test": ""}
{"tast_id": "frog-jump", "prompt": "# A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.\n# \n# Given a list of `stones`' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be `1` unit.\n# \n# If the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units. The frog can only jump in the forward direction.\n# \n# \n# Example 1:\n# Input: stones = [0,1,3,5,6,8,12,17]\n# Output: true\n# Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.\n# \n# \n# Example 2:\n# Input: stones = [0,1,2,3,4,8,9,11]\n# Output: false\n# Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.\n# \n# \n# Constraints:\n# `2 <= stones.length <= 2000`\n# `0 <= stones[i] <= 231 - 1`\n# `stones[0] == 0`\nclass Solution:\n def canCross(self, stones: List[int]) -> bool:\n ", "entry_point": "canCross", "cannonical_solution": "", "test": ""}
{"tast_id": "trapping-rain-water-ii", "prompt": "# Given an `m x n` matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.\n# \n# \n# Example:\n# Given the following 3x6 height map:\n# [\n# [1,4,3,1,3,2],\n# [3,2,1,3,2,4],\n# [2,3,3,2,3,1]\n# ]\n# Return 4.\n# \n# The above image represents the elevation map `[[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]` before the rain.\n# \n# After the rain, water is trapped between the blocks. The total volume of water trapped is 4.\n# \n# \n# Constraints:\n# `1 <= m, n <= 110`\n# `0 <= heightMap[i][j] <= 20000`\nclass Solution:\n def trapRainWater(self, heightMap: List[List[int]]) -> int:\n ", "entry_point": "trapRainWater", "cannonical_solution": "", "test": ""}
{"tast_id": "split-array-largest-sum", "prompt": "# Given an array `nums` which consists of non-negative integers and an integer `m`, you can split the array into `m` non-empty continuous subarrays.\n# \n# Write an algorithm to minimize the largest sum among these `m` subarrays.\n# \n# \n# Example 1:\n# Input: nums = [7,2,5,10,8], m = 2\n# Output: 18\n# Explanation:\n# There are four ways to split nums into two subarrays.\n# \n# The best way is to split it into [7,2,5] and [10,8],\n# where the largest sum among the two subarrays is only 18.\n# \n# \n# Example 2:\n# Input: nums = [1,2,3,4,5], m = 2\n# Output: 9\n# \n# Example 3:\n# Input: nums = [1,4,4], m = 3\n# Output: 4\n# \n# Constraints:\n# `1 <= nums.length <= 1000`\n# `0 <= nums[i] <= 106`\n# `1 <= m <= min(50, nums.length)`\nclass Solution:\n def splitArray(self, nums: List[int], k: int) -> int:\n ", "entry_point": "splitArray", "cannonical_solution": "", "test": ""}
{"tast_id": "strong-password-checker", "prompt": "# A password is considered strong if the below conditions are all met:\n# It has at least `6` characters and at most `20` characters.\n# \n# It contains at least one lowercase letter, at least one uppercase letter, and at least one digit.\n# \n# It does not contain three repeating characters in a row (i.e., `\"...aaa...\"` is weak, but `\"...aa...a...\"` is strong, assuming other conditions are met).\n# \n# Given a string `password`, return the minimum number of steps required to make `password` strong. if `password` is already strong, return `0`.\n# \n# In one step, you can:\n# Insert one character to `password`,\n# Delete one character from `password`, or\n# Replace one character of `password` with another character.\n# \n# \n# Example 1:\n# Input: password = \"a\"\n# Output: 5\n# \n# Example 2:\n# Input: password = \"aA1\"\n# Output: 3\n# \n# Example 3:\n# Input: password = \"1337C0d3\"\n# Output: 0\n# \n# Constraints:\n# `1 <= password.length <= 50`\n# `password` consists of letters, digits, dot `'.'` or exclamation mark `'!'`.\nclass Solution:\n def strongPasswordChecker(self, password: str) -> int:\n ", "entry_point": "strongPasswordChecker", "cannonical_solution": "", "test": ""}
{"tast_id": "k-th-smallest-in-lexicographical-order", "prompt": "# Given integers `n` and `k`, find the lexicographically k-th smallest integer in the range from `1` to `n`.\n# \n# Note: 1 \u2264 k \u2264 n \u2264 109.\n# \n# \n# Example:\n# Input:\n# n: 13 k: 2\n# Output:\n# 10\n# Explanation:\n# The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.\nclass Solution:\n def findKthNumber(self, n: int, k: int) -> int:\n ", "entry_point": "findKthNumber", "cannonical_solution": "", "test": ""}
{"tast_id": "poor-pigs", "prompt": "# There are `buckets` buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have `minutesToTest` minutes to determine which bucket is poisonous.\n# \n# You can feed the pigs according to these steps:\n# Choose some live pigs to feed.\n# \n# For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.\n# \n# Wait for `minutesToDie` minutes. You may not feed any other pigs during this time.\n# \n# After `minutesToDie` minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.\n# \n# Repeat this process until you run out of time.\n# \n# Given `buckets`, `minutesToDie`, and `minutesToTest`, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.\n# \n# \n# Example 1:\n# Input: buckets = 1000, minutesToDie = 15, minutesToTest = 60\n# Output: 5\n# \n# Example 2:\n# Input: buckets = 4, minutesToDie = 15, minutesToTest = 15\n# Output: 2\n# \n# Example 3:\n# Input: buckets = 4, minutesToDie = 15, minutesToTest = 30\n# Output: 2\n# \n# Constraints:\n# `1 <= buckets <= 1000`\n# `1 <= minutesToDie <= minutesToTest <= 100`\nclass Solution:\n def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:\n ", "entry_point": "poorPigs", "cannonical_solution": "", "test": ""}
{"tast_id": "lfu-cache", "prompt": "# Design and implement a data structure for a Least Frequently Used (LFU) cache.\n# \n# Implement the `LFUCache` class:\n# `LFUCache(int capacity)` Initializes the object with the `capacity` of the data structure.\n# \n# `int get(int key)` Gets the value of the `key` if the `key` exists in the cache. Otherwise, returns `-1`.\n# \n# `void put(int key, int value)` Update the value of the `key` if present, or inserts the `key` if not already present. When the cache reaches its `capacity`, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used `key` would be invalidated.\n# \n# To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.\n# \n# When a key is first inserted into the cache, its use counter is set to `1` (due to the `put` operation). The use counter for a key in the cache is incremented either a `get` or `put` operation is called on it.\n# \n# \n# Example 1:\n# Input\n# [\"LFUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n# [[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]\n# Output\n# [null, null, null, 1, null, -1, 3, null, -1, 3, 4]\n# Explanation\n# // cnt(x) = the use counter for key x\n# // cache=[] will show the last used order for tiebreakers (leftmost element is most recent)\n# LFUCache lfu = new LFUCache(2);\n# lfu.put(1, 1); // cache=[1,_], cnt(1)=1\n# lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1\n# lfu.get(1); // return 1\n# // cache=[1,2], cnt(2)=1, cnt(1)=2\n# lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n# \n# // cache=[3,1], cnt(3)=1, cnt(1)=2\n# lfu.get(2); // return -1 (not found)\n# lfu.get(3); // return 3\n# // cache=[3,1], cnt(3)=2, cnt(1)=2\n# lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n# \n# // cache=[4,3], cnt(4)=1, cnt(3)=2\n# lfu.get(1); // return -1 (not found)\n# lfu.get(3); // return 3\n# // cache=[3,4], cnt(4)=1, cnt(3)=3\n# lfu.get(4); // return 4\n# // cache=[3,4], cnt(4)=2, cnt(3)=3\n# \n# Constraints:\n# `0 <= capacity, key, value <= 104`\n# At most `105` calls will be made to `get` and `put`.\n# \n# Follow up: Could you do both operations in `O(1)` time complexity?\nclass LFUCache:\n\n def __init__(self, capacity: int):\n \n\n def get(self, key: int) -> int:\n \n\n def put(self, key: int, value: int) -> None:\n \n\n\n# Your LFUCache object will be instantiated and called as such:\n# obj = LFUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "count-the-repetitions", "prompt": "# Define `S = [s,n]` as the string S which consists of n connected strings s. For example, `[\"abc\", 3]` =\"abcabcabc\". \n# On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, \u201cabc\u201d can be obtained from \u201cabdbec\u201d based on our definition, but it can not be obtained from \u201cacbbe\u201d.\n# \n# You are given two non-empty strings s1 and s2 (each at most 100 characters long) and two integers 0 \u2264 n1 \u2264 106 and 1 \u2264 n2 \u2264 106. Now consider the strings S1 and S2, where `S1=[s1,n1]` and `S2=[s2,n2]`. Find the maximum integer M such that `[S2,M]` can be obtained from `S1`.\n# \n# \n# Example:\n# Input:\n# s1=\"acb\", n1=4\n# s2=\"ab\", n2=2\n# Return:\n# 2\nclass Solution:\n def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:\n ", "entry_point": "getMaxRepetitions", "cannonical_solution": "", "test": ""}
{"tast_id": "concatenated-words", "prompt": "# Given an array of strings `words` (without duplicates), return all the concatenated words in the given list of `words`.\n# \n# A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.\n# \n# \n# Example 1:\n# Input: words = [\"cat\",\"cats\",\"catsdogcats\",\"dog\",\"dogcatsdog\",\"hippopotamuses\",\"rat\",\"ratcatdogcat\"]\n# Output: [\"catsdogcats\",\"dogcatsdog\",\"ratcatdogcat\"]\n# Explanation: \"catsdogcats\" can be concatenated by \"cats\", \"dog\" and \"cats\"; \n# \"dogcatsdog\" can be concatenated by \"dog\", \"cats\" and \"dog\"; \n# \"ratcatdogcat\" can be concatenated by \"rat\", \"cat\", \"dog\" and \"cat\".\n# \n# \n# Example 2:\n# Input: words = [\"cat\",\"dog\",\"catdog\"]\n# Output: [\"catdog\"]\n# \n# Constraints:\n# `1 <= words.length <= 104`\n# `0 <= words[i].length <= 1000`\n# `words[i]` consists of only lowercase English letters.\n# \n# `0 <= sum(words[i].length) <= 6 * 105`\nclass Solution:\n def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:\n ", "entry_point": "findAllConcatenatedWordsInADict", "cannonical_solution": "", "test": ""}
{"tast_id": "largest-palindrome-product", "prompt": "# Find the largest palindrome made from the product of two n-digit numbers.\n# \n# Since the result could be very large, you should return the largest palindrome mod 1337.\n# \n# \n# Example:\n# Input: 2\n# Output: 987\n# Explanation: 99 x 91 = 9009, 9009 % 1337 = 987\n# Note:\n# The range of n is [1,8].\nclass Solution:\n def largestPalindrome(self, n: int) -> int:\n ", "entry_point": "largestPalindrome", "cannonical_solution": "", "test": ""}
{"tast_id": "sliding-window-median", "prompt": "# Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.\n# \n# \n# Examples:\n# `[2,3,4]` , the median is `3`\n# `[2,3]`, the median is `(2 + 3) / 2 = 2.5`\n# Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Your job is to output the median array for each window in the original array.\n# \n# For example,\n# Given nums = `[1,3,-1,-3,5,3,6,7]`, and k = 3.\n# \n# Window position Median\n# --------------- -----\n# [1 3 -1] -3 5 3 6 7 1\n# 1 [3 -1 -3] 5 3 6 7 -1\n# 1 3 [-1 -3 5] 3 6 7 -1\n# 1 3 -1 [-3 5 3] 6 7 3\n# 1 3 -1 -3 [5 3 6] 7 5\n# 1 3 -1 -3 5 [3 6 7] 6\n# Therefore, return the median sliding window as `[1,-1,-1,3,5,6]`.\n# \n# Note: \n# You may assume `k` is always valid, ie: `k` is always smaller than input array's size for non-empty array.\n# \n# Answers within `10^-5` of the actual value will be accepted as correct.\nclass Solution:\n def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n ", "entry_point": "medianSlidingWindow", "cannonical_solution": "", "test": ""}
{"tast_id": "smallest-good-base", "prompt": "# For an integer n, we call k>=2 a good base of n, if all digits of n base k are 1.\n# \n# Now given a string representing n, you should return the smallest good base of n in string format.\n# \n# \n# Example 1:\n# Input: \"13\"\n# Output: \"3\"\n# Explanation: 13 base 3 is 111.\n# \n# \n# Example 2:\n# Input: \"4681\"\n# Output: \"8\"\n# Explanation: 4681 base 8 is 11111.\n# \n# \n# Example 3:\n# Input: \"1000000000000000000\"\n# Output: \"999999999999999999\"\n# Explanation: 1000000000000000000 base 999999999999999999 is 11.\n# \n# Note:\n# The range of n is [3, 10^18].\n# \n# The string representing n is always valid and will not have leading zeros.\nclass Solution:\n def smallestGoodBase(self, n: str) -> str:\n ", "entry_point": "smallestGoodBase", "cannonical_solution": "", "test": ""}
{"tast_id": "zuma-game", "prompt": "# Think about Zuma Game. You have a row of balls on the table, colored red(R), yellow(Y), blue(B), green(G), and white(W). You also have several balls in your hand.\n# \n# Each time, you may choose a ball in your hand, and insert it into the row (including the leftmost place and rightmost place). Then, if there is a group of 3 or more balls in the same color touching, remove these balls. Keep doing this until no more balls can be removed.\n# \n# Find the minimal balls you have to insert to remove all the balls on the table. If you cannot remove all the balls, output -1.\n# \n# \n# Example 1:\n# Input: board = \"WRRBBW\", hand = \"RB\"\n# Output: -1\n# Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW\n# \n# Example 2:\n# Input: board = \"WWRRBBWW\", hand = \"WRBRW\"\n# Output: 2\n# Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> empty\n# \n# Example 3:\n# Input: board = \"G\", hand = \"GGGGG\"\n# Output: 2\n# Explanation: G -> G[G] -> GG[G] -> empty \n# \n# Example 4:\n# Input: board = \"RBYYBBRRB\", hand = \"YRBGB\"\n# Output: 3\n# Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty \n# \n# Constraints:\n# You may assume that the initial row of balls on the table won\u2019t have any 3 or more consecutive balls with the same color.\n# \n# `1 <= board.length <= 16`\n# `1 <= hand.length <= 5`\n# Both input strings will be non-empty and only contain characters 'R','Y','B','G','W'.\nclass Solution:\n def findMinStep(self, board: str, hand: str) -> int:\n ", "entry_point": "findMinStep", "cannonical_solution": "", "test": ""}
{"tast_id": "reverse-pairs", "prompt": "# Given an array `nums`, we call `(i, j)` an important reverse pair if `i < j` and `nums[i] > 2*nums[j]`.\n# \n# You need to return the number of important reverse pairs in the given array.\n# \n# \n# Example1:\n# Input: [1,3,2,3,1]\n# Output: 2\n# \n# Example2:\n# Input: [2,4,3,5,1]\n# Output: 3\n# Note:\n# The length of the given array will not exceed `50,000`.\n# \n# All the numbers in the input array are in the range of 32-bit integer.\nclass Solution:\n def reversePairs(self, nums: List[int]) -> int:\n ", "entry_point": "reversePairs", "cannonical_solution": "", "test": ""}
{"tast_id": "ipo", "prompt": "# Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. \n# You are given several projects. For each project i, it has a pure profit Pi and a minimum capital of Ci is needed to start the corresponding project. Initially, you have W capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.\n# \n# To sum up, pick a list of at most k distinct projects from given projects to maximize your final capital, and output your final maximized capital.\n# \n# \n# Example 1:\n# Input: k=2, W=0, Profits=[1,2,3], Capital=[0,1,1].\n# Output: 4\n# Explanation: Since your initial capital is 0, you can only start the project indexed 0.\n# \n# After finishing it you will obtain profit 1 and your capital becomes 1.\n# \n# With capital 1, you can either start the project indexed 1 or the project indexed 2.\n# \n# Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\n# \n# Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.\n# \n# Note:\n# You may assume all numbers in the input are non-negative integers.\n# \n# The length of Profits array and Capital array will not exceed 50,000.\n# \n# The answer is guaranteed to fit in a 32-bit signed integer.\nclass Solution:\n def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:\n ", "entry_point": "findMaximizedCapital", "cannonical_solution": "", "test": ""}
{"tast_id": "freedom-trail", "prompt": "# In the video game Fallout 4, the quest \"Road to Freedom\" requires players to reach a metal dial called the \"Freedom Trail Ring\", and use the dial to spell a specific keyword in order to open the door.\n# \n# Given a string ring, which represents the code engraved on the outer ring and another string key, which represents the keyword needs to be spelled. You need to find the minimum number of steps in order to spell all the characters in the keyword.\n# \n# Initially, the first character of the ring is aligned at 12:00 direction. You need to spell all the characters in the string key one by one by rotating the ring clockwise or anticlockwise to make each character of the string key aligned at 12:00 direction and then by pressing the center button.\n# \n# At the stage of rotating the ring to spell the key character key[i]:\n# You can rotate the ring clockwise or anticlockwise one place, which counts as 1 step. The final purpose of the rotation is to align one of the string ring's characters at the 12:00 direction, where this character must equal to the character key[i].\n# \n# If the character key[i] has been aligned at the 12:00 direction, you need to press the center button to spell, which also counts as 1 step. After the pressing, you could begin to spell the next character in the key (next stage), otherwise, you've finished all the spelling.\n# \n# \n# Example:\n# Input: ring = \"godding\", key = \"gd\"\n# Output: 4\n# Explanation:\n# For the first key character 'g', since it is already in place, we just need 1 step to spell this character. \n# For the second key character 'd', we need to rotate the ring \"godding\" anticlockwise by two steps to make it become \"ddinggo\".\n# \n# Also, we need 1 more step for spelling.\n# \n# So the final output is 4.\n# \n# Note:\n# Length of both ring and key will be in range 1 to 100.\n# \n# There are only lowercase letters in both strings and might be some duplcate characters in both strings.\n# \n# It's guaranteed that string key could always be spelled by rotating the string ring.\nclass Solution:\n def findRotateSteps(self, ring: str, key: str) -> int:\n ", "entry_point": "findRotateSteps", "cannonical_solution": "", "test": ""}
{"tast_id": "super-washing-machines", "prompt": "# You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty. \n# For each move, you could choose any m (1 \u2264 m \u2264 n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time . \n# Given an integer array representing the number of dresses in each washing machine from left to right on the line, you should find the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1.\n# \n# \n# Example1\n# Input: [1,0,5]\n# Output: 3\n# Explanation: \n# 1st move: 1 0 <-- 5 => 1 1 4\n# 2nd move: 1 <-- 1 <-- 4 => 2 1 3 \n# 3rd move: 2 1 <-- 3 => 2 2 2 \n# \n# Example2\n# Input: [0,3,0]\n# Output: 2\n# Explanation: \n# 1st move: 0 <-- 3 0 => 1 2 0 \n# 2nd move: 1 2 --> 0 => 1 1 1 \n# \n# Example3\n# Input: [0,2,0]\n# Output: -1\n# Explanation: \n# It's impossible to make all the three washing machines have the same number of dresses. \n# Note:\n# The range of n is [1, 10000].\n# \n# The range of dresses number in a super washing machine is [0, 1e5].\nclass Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n ", "entry_point": "findMinMoves", "cannonical_solution": "", "test": ""}
{"tast_id": "remove-boxes", "prompt": "# You are given several `boxes` with different colors represented by different positive numbers.\n# \n# You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points.\n# \n# Return the maximum points you can get.\n# \n# \n# Example 1:\n# Input: boxes = [1,3,2,2,2,3,4,3,1]\n# Output: 23\n# Explanation:\n# [1, 3, 2, 2, 2, 3, 4, 3, 1] \n# ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) \n# ----> [1, 3, 3, 3, 1] (1*1=1 points) \n# ----> [1, 1] (3*3=9 points) \n# ----> [] (2*2=4 points)\n# \n# Example 2:\n# Input: boxes = [1,1,1]\n# Output: 9\n# \n# Example 3:\n# Input: boxes = [1]\n# Output: 1\n# \n# Constraints:\n# `1 <= boxes.length <= 100`\n# `1 <= boxes[i] <= 100`\nclass Solution:\n def removeBoxes(self, boxes: List[int]) -> int:\n ", "entry_point": "removeBoxes", "cannonical_solution": "", "test": ""}
{"tast_id": "student-attendance-record-ii", "prompt": "# An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:\n# `'A'`: Absent.\n# \n# `'L'`: Late.\n# \n# `'P'`: Present.\n# \n# Any student is eligible for an attendance award if they meet both of the following criteria:\n# The student was absent (`'A'`) for strictly fewer than 2 days total.\n# \n# The student was never late (`'L'`) for 3 or more consecutive days.\n# \n# Given an integer `n`, return the number of possible attendance records of length `n` that make a student eligible for an attendance award. The answer may be very large, so return it modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: n = 2\n# Output: 8\n# Explanation: There are 8 records with length 2 that are eligible for an award:\n# \"PP\", \"AP\", \"PA\", \"LP\", \"PL\", \"AL\", \"LA\", \"LL\"\n# Only \"AA\" is not eligible because there are 2 absences (there need to be fewer than 2).\n# \n# \n# Example 2:\n# Input: n = 1\n# Output: 3\n# \n# Example 3:\n# Input: n = 10101\n# Output: 183236316\n# \n# Constraints:\n# `1 <= n <= 105`\nclass Solution:\n def checkRecord(self, n: int) -> int:\n ", "entry_point": "checkRecord", "cannonical_solution": "", "test": ""}
{"tast_id": "find-the-closest-palindrome", "prompt": "# Given an integer n, find the closest integer (not including itself), which is a palindrome. \n# The 'closest' is defined as absolute difference minimized between two integers.\n# \n# \n# Example 1:\n# Input: \"123\"\n# Output: \"121\"\n# Note:\n# The input n is a positive integer represented by string, whose length will not exceed 18.\n# \n# If there is a tie, return the smaller one as answer.\nclass Solution:\n def nearestPalindromic(self, n: str) -> str:\n ", "entry_point": "nearestPalindromic", "cannonical_solution": "", "test": ""}
{"tast_id": "erect-the-fence", "prompt": "# There are some trees, where each tree is represented by (x,y) coordinate in a two-dimensional garden. Your job is to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed. Your task is to help find the coordinates of trees which are exactly located on the fence perimeter.\n# \n# \n# Example 1:\n# Input: [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]\n# Output: [[1,1],[2,0],[4,2],[3,3],[2,4]]\n# Explanation:\n# \n# Example 2:\n# Input: [[1,2],[2,2],[4,2]]\n# Output: [[1,2],[2,2],[4,2]]\n# Explanation:\n# Even you only have trees in a line, you need to use rope to enclose them. \n# Note:\n# All trees should be enclosed together. You cannot cut the rope to enclose trees that will separate them in more than one group.\n# \n# All input integers will range from 0 to 100.\n# \n# The garden has at least one tree.\n# \n# All coordinates are distinct.\n# \n# Input points have NO order. No order required for output.\n# input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.\nclass Solution:\n def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:\n ", "entry_point": "outerTrees", "cannonical_solution": "", "test": ""}
{"tast_id": "tag-validator", "prompt": "# Given a string representing a code snippet, you need to implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold:\n# The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.\n# \n# A closed tag (not necessarily valid) has exactly the following format : `<TAG_NAME>TAG_CONTENT</TAG_NAME>`. Among them, `<TAG_NAME>` is the start tag, and `</TAG_NAME>` 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.\n# \n# A valid `TAG_NAME` only contain upper-case letters, and has length in range [1,9]. Otherwise, the `TAG_NAME` is invalid.\n# \n# 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.\n# \n# 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.\n# \n# A `<` is unmatched if you cannot find a subsequent `>`. And when you find a `<` or `</`, all the subsequent characters until the next `>` should be parsed as TAG_NAME (not necessarily valid).\n# \n# The cdata has the following format : `<![CDATA[CDATA_CONTENT]]>`. The range of `CDATA_CONTENT` is defined as the characters between `<![CDATA[` and the first subsequent `]]>`. \n# `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# Valid Code Examples:\n# Input: \"<DIV>This is the first line <![CDATA[<div>]]></DIV>\"\n# Output: True\n# Explanation: \n# The code is wrapped in a closed tag : <DIV> and </DIV>. \n# The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. \n# Although CDATA_CONTENT has unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as tag.\n# \n# So TAG_CONTENT is valid, and then the code is valid. Thus return true.\n# \n# Input: \"<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>\"\n# Output: True\n# Explanation:\n# We first separate the code into : start_tag|tag_content|end_tag.\n# \n# start_tag -> \"<DIV>\"\n# end_tag -> \"</DIV>\"\n# tag_content could also be separated into : text1|cdata|text2.\n# \n# text1 -> \">> ![cdata[]] \"\n# cdata -> \"<![CDATA[<div>]>]]>\", where the CDATA_CONTENT is \"<div>]>\"\n# text2 -> \"]]>>]\"\n# The reason why start_tag is NOT \"<DIV>>>\" is because of the rule 6.\n# \n# The reason why cdata is NOT \"<![CDATA[<div>]>]]>]]>\" is because of the rule 7.\n# \n# \n# Invalid Code Examples:\n# Input: \"<A> <B> </A> </B>\"\n# Output: False\n# Explanation: Unbalanced. If \"<A>\" is closed, then \"<B>\" must be unmatched, and vice versa.\n# \n# Input: \"<DIV> div tag is not closed <DIV>\"\n# Output: False\n# Input: \"<DIV> unmatched < </DIV>\"\n# Output: False\n# Input: \"<DIV> closed tags with invalid tag name <b>123</b> </DIV>\"\n# Output: False\n# Input: \"<DIV> unmatched tags with invalid tag name </1234567890> and <CDATA[[]]> </DIV>\"\n# Output: False\n# Input: \"<DIV> unmatched start tag <B> and unmatched end tag </C> </DIV>\"\n# Output: False\n# Note:\n# For simplicity, you could assume the input code (including the any characters mentioned above) only contain `letters`, `digits`, `'<'`,`'>'`,`'/'`,`'!'`,`'['`,`']'` and `' '`.\nclass Solution:\n def isValid(self, code: str) -> bool:\n ", "entry_point": "isValid", "cannonical_solution": "", "test": ""}
{"tast_id": "non-negative-integers-without-consecutive-ones", "prompt": "# Given a positive integer n, find the number of non-negative integers less than or equal to n, whose binary representations do NOT contain consecutive ones.\n# \n# \n# Example 1:\n# Input: 5\n# Output: 5\n# Explanation: \n# Here are the non-negative integers <= 5 with their corresponding binary representations:\n# 0 : 0\n# 1 : 1\n# 2 : 10\n# 3 : 11\n# 4 : 100\n# 5 : 101\n# Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. \n# Note:\n# 1 <= n <= 109\nclass Solution:\n def findIntegers(self, n: int) -> int:\n ", "entry_point": "findIntegers", "cannonical_solution": "", "test": ""}
{"tast_id": "k-inverse-pairs-array", "prompt": "# Given two integers `n` and `k`, find how many different arrays consist of numbers from `1` to `n` such that there are exactly `k` inverse pairs.\n# \n# We define an inverse pair as following: For `ith` and `jth` element in the array, if `i` < `j` and `a[i]` > `a[j]` then it's an inverse pair; Otherwise, it's not.\n# \n# Since the answer may be very large, the answer should be modulo 109 + 7.\n# \n# \n# Example 1:\n# Input: n = 3, k = 0\n# Output: 1\n# Explanation: \n# Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pair.\n# \n# \n# Example 2:\n# Input: n = 3, k = 1\n# Output: 2\n# Explanation: \n# The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.\n# \n# Note:\n# The integer `n` is in the range [1, 1000] and `k` is in the range [0, 1000].\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n ", "entry_point": "kInversePairs", "cannonical_solution": "", "test": ""}
{"tast_id": "course-schedule-iii", "prompt": "# There are `n` different online courses numbered from `1` to `n`. Each course has some duration(course length) `t` and closed on `dth` day. A course should be taken continuously for `t` days and must be finished before or on the `dth` day. You will start at the `1st` day.\n# \n# Given `n` online courses represented by pairs `(t,d)`, your task is to find the maximal number of courses that can be taken.\n# \n# \n# Example:\n# Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]\n# Output: 3\n# Explanation: \n# There're totally 4 courses, but you can take 3 courses at most:\n# First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.\n# \n# Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. \n# Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. \n# The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.\n# \n# Note:\n# The integer 1 <= d, t, n <= 10,000.\n# \n# You can't take two courses simultaneously.\nclass Solution:\n def scheduleCourse(self, courses: List[List[int]]) -> int:\n ", "entry_point": "scheduleCourse", "cannonical_solution": "", "test": ""}
{"tast_id": "smallest-range-covering-elements-from-k-lists", "prompt": "# You have `k` lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the `k` lists.\n# \n# We define the range `[a, b]` is smaller than range `[c, d]` if `b - a < d - c` or `a < c` if `b - a == d - c`.\n# \n# \n# Example 1:\n# Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]\n# Output: [20,24]\n# Explanation: \n# List 1: [4, 10, 15, 24,26], 24 is in range [20,24].\n# \n# List 2: [0, 9, 12, 20], 20 is in range [20,24].\n# \n# List 3: [5, 18, 22, 30], 22 is in range [20,24].\n# \n# \n# Example 2:\n# Input: nums = [[1,2,3],[1,2,3],[1,2,3]]\n# Output: [1,1]\n# \n# Example 3:\n# Input: nums = [[10,10],[11,11]]\n# Output: [10,11]\n# \n# Example 4:\n# Input: nums = [[10],[11]]\n# Output: [10,11]\n# \n# Example 5:\n# Input: nums = [[1],[2],[3],[4],[5],[6],[7]]\n# Output: [1,7]\n# \n# Constraints:\n# `nums.length == k`\n# `1 <= k <= 3500`\n# `1 <= nums[i].length <= 50`\n# `-105 <= nums[i][j] <= 105`\n# `nums[i]` is sorted in non-decreasing order.\nclass Solution:\n def smallestRange(self, nums: List[List[int]]) -> List[int]:\n ", "entry_point": "smallestRange", "cannonical_solution": "", "test": ""}
{"tast_id": "decode-ways-ii", "prompt": "# A message containing letters from `A-Z` can be encoded into numbers using the following mapping:\n# 'A' -> \"1\"\n# 'B' -> \"2\"\n# ...\n# \n# 'Z' -> \"26\"\n# To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `\"11106\"` can be mapped into:\n# `\"AAJF\"` with the grouping `(1 1 10 6)`\n# `\"KJF\"` with the grouping `(11 10 6)`\n# Note that the grouping `(1 11 06)` is invalid because `\"06\"` cannot be mapped into `'F'` since `\"6\"` is different from `\"06\"`.\n# \n# In addition to the mapping above, an encoded message may contain the `'*'` character, which can represent any digit from `'1'` to `'9'` (`'0'` is excluded). For example, the encoded message `\"1*\"` may represent any of the encoded messages `\"11\"`, `\"12\"`, `\"13\"`, `\"14\"`, `\"15\"`, `\"16\"`, `\"17\"`, `\"18\"`, or `\"19\"`. Decoding `\"1*\"` is equivalent to decoding any of the encoded messages it can represent.\n# \n# Given a string `s` containing digits and the `'*'` character, return the number of ways to decode it.\n# \n# Since the answer may be very large, return it modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: s = \"*\"\n# Output: 9\n# Explanation: The encoded message can represent any of the encoded messages \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", or \"9\".\n# \n# Each of these can be decoded to the strings \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", and \"I\" respectively.\n# \n# Hence, there are a total of 9 ways to decode \"*\".\n# \n# \n# Example 2:\n# Input: s = \"1*\"\n# Output: 18\n# Explanation: The encoded message can represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\".\n# \n# Each of these encoded messages have 2 ways to be decoded (e.g. \"11\" can be decoded to \"AA\" or \"K\").\n# \n# Hence, there are a total of 9 * 2 = 18 ways to decode \"1*\".\n# \n# \n# Example 3:\n# Input: s = \"2*\"\n# Output: 15\n# Explanation: The encoded message can represent any of the encoded messages \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", or \"29\".\n# \n# \"21\", \"22\", \"23\", \"24\", \"25\", and \"26\" have 2 ways of being decoded, but \"27\", \"28\", and \"29\" only have 1 way.\n# \n# Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode \"2*\".\n# \n# \n# Constraints:\n# `1 <= s.length <= 105`\n# `s[i]` is a digit or `'*'`.\nclass Solution:\n def numDecodings(self, s: str) -> int:\n ", "entry_point": "numDecodings", "cannonical_solution": "", "test": ""}
{"tast_id": "strange-printer", "prompt": "# There is a strange printer with the following two special requirements:\n# The printer can only print a sequence of the same character each time.\n# \n# At each turn, the printer can print new characters starting from and ending at any places, and will cover the original existing characters.\n# \n# Given a string consists of lower English letters only, your job is to count the minimum number of turns the printer needed in order to print it.\n# \n# \n# Example 1:\n# Input: \"aaabbb\"\n# Output: 2\n# Explanation: Print \"aaa\" first and then print \"bbb\".\n# \n# \n# Example 2:\n# Input: \"aba\"\n# Output: 2\n# Explanation: Print \"aaa\" first and then print \"b\" from the second place of the string, which will cover the existing character 'a'.\n# \n# Hint: Length of the given string will not exceed 100.\nclass Solution:\n def strangePrinter(self, s: str) -> int:\n ", "entry_point": "strangePrinter", "cannonical_solution": "", "test": ""}
{"tast_id": "kth-smallest-number-in-multiplication-table", "prompt": "# Nearly every one have used the Multiplication Table. But could you find out the `k-th` smallest number quickly from the multiplication table?\n# Given the height `m` and the length `n` of a `m * n` Multiplication Table, and a positive integer `k`, you need to return the `k-th` smallest number in this table.\n# \n# \n# Example 1:\n# Input: m = 3, n = 3, k = 5\n# Output: \n# Explanation: \n# The Multiplication Table:\n# 1\t2\t3\n# 2\t4\t6\n# 3\t6\t9\n# The 5-th smallest number is 3 (1, 2, 2, 3, 3).\n# \n# \n# Example 2:\n# Input: m = 2, n = 3, k = 6\n# Output: \n# Explanation: \n# The Multiplication Table:\n# 1\t2\t3\n# 2\t4\t6\n# The 6-th smallest number is 6 (1, 2, 2, 3, 4, 6).\n# \n# Note:\n# The `m` and `n` will be in the range [1, 30000].\n# \n# The `k` will be in the range [1, m * n]\nclass Solution:\n def findKthNumber(self, m: int, n: int, k: int) -> int:\n ", "entry_point": "findKthNumber", "cannonical_solution": "", "test": ""}
{"tast_id": "cut-off-trees-for-golf-event", "prompt": "# You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an `m x n` matrix. In this matrix:\n# `0` means the cell cannot be walked through.\n# \n# `1` represents an empty cell that can be walked through.\n# \n# A number greater than `1` represents a tree in a cell that can be walked through, and this number is the tree's height.\n# \n# In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.\n# \n# You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes `1` (an empty cell).\n# \n# Starting from the point `(0, 0)`, return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return `-1`.\n# \n# You are guaranteed that no two trees have the same height, and there is at least one tree needs to be cut off.\n# \n# \n# Example 1:\n# Input: forest = [[1,2,3],[0,0,4],[7,6,5]]\n# Output: 6\n# Explanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.\n# \n# \n# Example 2:\n# Input: forest = [[1,2,3],[0,0,0],[7,6,5]]\n# Output: -1\n# Explanation: The trees in the bottom row cannot be accessed as the middle row is blocked.\n# \n# \n# Example 3:\n# Input: forest = [[2,3,4],[0,0,5],[8,7,6]]\n# Output: 6\n# \n# Explanation: You can follow the same path as Example 1 to cut off all the trees.\n# \n# Note that you can cut off the first tree at (0, 0) before making any steps.\n# \n# \n# Constraints:\n# `m == forest.length`\n# `n == forest[i].length`\n# `1 <= m, n <= 50`\n# `0 <= forest[i][j] <= 109`\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n ", "entry_point": "cutOffTree", "cannonical_solution": "", "test": ""}
{"tast_id": "24-game", "prompt": "# You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through `*`, `/`, `+`, `-`, `(`, `)` to get the value of 24.\n# \n# \n# Example 1:\n# Input: [4, 1, 8, 7]\n# Output: True\n# Explanation: (8-4) * (7-1) = 24\n# \n# Example 2:\n# Input: [1, 2, 1, 2]\n# Output: False\n# Note:\n# The division operator `/` represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.\n# \n# Every operation done is between two numbers. In particular, we cannot use `-` as a unary operator. For example, with `[1, 1, 1, 1]` as input, the expression `-1 - 1 - 1 - 1` is not allowed.\n# \n# You cannot concatenate numbers together. For example, if the input is `[1, 2, 1, 2]`, we cannot write this as 12 + 12.\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n ", "entry_point": "judgePoint24", "cannonical_solution": "", "test": ""}
{"tast_id": "redundant-connection-ii", "prompt": "# In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.\n# \n# The given input is a directed graph that started as a rooted tree with `n` nodes (with distinct values from `1` to `n`), with one additional directed edge added. The added edge has two different vertices chosen from `1` to `n`, and was not an edge that already existed.\n# \n# The resulting graph is given as a 2D-array of `edges`. Each element of `edges` is a pair `[ui, vi]` that represents a directed edge connecting nodes `ui` and `vi`, where `ui` is a parent of child `vi`.\n# \n# Return an edge that can be removed so that the resulting graph is a rooted tree of `n` nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.\n# \n# \n# Example 1:\n# Input: edges = [[1,2],[1,3],[2,3]]\n# Output: [2,3]\n# \n# Example 2:\n# Input: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]\n# Output: [4,1]\n# \n# Constraints:\n# `n == edges.length`\n# `3 <= n <= 1000`\n# `edges[i].length == 2`\n# `1 <= ui, vi <= n`\nclass Solution:\n def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:\n ", "entry_point": "findRedundantDirectedConnection", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-sum-of-3-non-overlapping-subarrays", "prompt": "# In a given array `nums` of positive integers, find three non-overlapping subarrays with maximum sum.\n# \n# Each subarray will be of size `k`, and we want to maximize the sum of all `3*k` entries.\n# \n# Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.\n# \n# \n# Example:\n# Input: [1,2,1,2,6,7,5,1], 2\n# Output: [0, 3, 5]\n# Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\n# \n# We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.\n# \n# Note:\n# `nums.length` will be between 1 and 20000.\n# \n# `nums[i]` will be between 1 and 65535.\n# \n# `k` will be between 1 and floor(nums.length / 3).\nclass Solution:\n def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:\n ", "entry_point": "maxSumOfThreeSubarrays", "cannonical_solution": "", "test": ""}
{"tast_id": "stickers-to-spell-word", "prompt": "# We are given N different types of stickers. Each sticker has a lowercase English word on it.\n# \n# You would like to spell out the given `target` string by cutting individual letters from your collection of stickers and rearranging them.\n# \n# You can use each sticker more than once if you want, and you have infinite quantities of each sticker.\n# \n# What is the minimum number of stickers that you need to spell out the `target`? If the task is impossible, return -1.\n# \n# \n# Example 1:\n# Input:[\"with\", \"example\", \"science\"], \"thehat\"\n# Output:3\n# Explanation:We can use 2 \"with\" stickers, and 1 \"example\" sticker.\n# \n# After cutting and rearrange the letters of those stickers, we can form the target \"thehat\".\n# \n# Also, this is the minimum number of stickers necessary to form the target string.\n# \n# \n# Example 2:\n# Input:[\"notice\", \"possible\"], \"basicbasic\"\n# Output:-1\n# Explanation:We can't form the target \"basicbasic\" from cutting letters from the given stickers.\n# \n# Note:\n# `stickers` has length in the range `[1, 50]`.\n# \n# `stickers` consists of lowercase English words (without apostrophes).\n# \n# `target` has length in the range `[1, 15]`, and consists of lowercase English letters.\n# \n# In all test cases, all words were chosen randomly from the 1000 most common US English words, and the target was chosen as a concatenation of two random words.\n# \n# The time limit may be more challenging than usual. It is expected that a 50 sticker test case can be solved within 35ms on average.\nclass Solution:\n def minStickers(self, stickers: List[str], target: str) -> int:\n ", "entry_point": "minStickers", "cannonical_solution": "", "test": ""}
{"tast_id": "falling-squares", "prompt": "# On an infinite number line (x-axis), we drop given squares in the order they are given.\n# \n# The `i`-th square dropped (`positions[i] = (left, side_length)`) is a square with the left-most point being `positions[i][0]` and sidelength `positions[i][1]`.\n# \n# The square is dropped with the bottom edge parallel to the number line, and from a higher height than all currently landed squares. We wait for each square to stick before dropping the next.\n# \n# The squares are infinitely sticky on their bottom edge, and will remain fixed to any positive length surface they touch (either the number line or another square). Squares dropped adjacent to each other will not stick together prematurely.\n# \n# Return a list `ans` of heights. Each height `ans[i]` represents the current highest height of any square we have dropped, after dropping squares represented by `positions[0], positions[1], ..., positions[i]`.\n# \n# \n# Example 1:\n# Input: [[1, 2], [2, 3], [6, 1]]\n# Output: [2, 5, 5]\n# Explanation:\n# After the first drop of `positions[0] = [1, 2]: _aa _aa ------- `The maximum height of any square is 2.\n# \n# After the second drop of `positions[1] = [2, 3]: __aaa __aaa __aaa _aa__ _aa__ -------------- `The maximum height of any square is 5. The larger square stays on top of the smaller square despite where its center of gravity is, because squares are infinitely sticky on their bottom edge.\n# \n# After the third drop of `positions[1] = [6, 1]: __aaa __aaa __aaa _aa _aa___a -------------- `The maximum height of any square is still 5. Thus, we return an answer of `[2, 5, 5]`.\n# \n# \n# Example 2:\n# Input: [[100, 100], [200, 100]]\n# Output: [100, 100]\n# Explanation: Adjacent squares don't get stuck prematurely - only their bottom edge can stick to surfaces.\n# \n# Note:\n# `1 <= positions.length <= 1000`.\n# \n# `1 <= positions[i][0] <= 10^8`.\n# \n# `1 <= positions[i][1] <= 10^6`.\nclass Solution:\n def fallingSquares(self, positions: List[List[int]]) -> List[int]:\n ", "entry_point": "fallingSquares", "cannonical_solution": "", "test": ""}
{"tast_id": "random-pick-with-blacklist", "prompt": "# Given a blacklist `B` containing unique integers from `[0, N)`, write a function to return a uniform random integer from `[0, N)` which is NOT in `B`.\n# \n# Optimize it such that it minimizes the call to system\u2019s `Math.random()`.\n# \n# Note:\n# `1 <= N <= 1000000000`\n# `0 <= B.length < min(100000, N)`\n# `[0, N)` does NOT include N. See interval notation.\n# \n# \n# Example 1:\n# Input: \n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[1,[]],[],[],[]]\n# Output: [null,0,0,0]\n# \n# Example 2:\n# Input: \n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[2,[]],[],[],[]]\n# Output: [null,1,1,1]\n# \n# Example 3:\n# Input: \n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[3,[1]],[],[],[]]\n# Output: [null,0,0,2]\n# \n# Example 4:\n# Input: \n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[4,[2]],[],[],[]]\n# Output: [null,1,3,1]\n# Explanation of Input Syntax:\n# The input is two lists: the subroutines called and their arguments. `Solution`'s constructor has two arguments, `N` and the blacklist `B`. `pick` has no arguments. Arguments are always wrapped with a list, even if there aren't any.\nclass Solution:\n\n def __init__(self, n: int, blacklist: List[int]):\n \n\n def pick(self) -> int:\n \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(n, blacklist)\n# param_1 = obj.pick()", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "range-module", "prompt": "# A Range Module is a module that tracks ranges of numbers. Your task is to design and implement the following interfaces in an efficient manner.\n# \n# `addRange(int left, int right)` Adds the half-open interval `[left, right)`, tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval `[left, right)` that are not already tracked.\n# \n# `queryRange(int left, int right)` Returns true if and only if every real number in the interval `[left, right)`\n# is currently being tracked.\n# \n# `removeRange(int left, int right)` Stops tracking every real number currently being tracked in the interval `[left, right)`.\n# \n# \n# Example 1:\n# addRange(10, 20): null\n# removeRange(14, 16): null\n# queryRange(10, 14): true (Every number in [10, 14) is being tracked)\n# queryRange(13, 15): false (Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)\n# queryRange(16, 17): true (The number 16 in [16, 17) is still being tracked, despite the remove operation)\n# Note:\n# A half open interval `[left, right)` denotes all real numbers `left <= x < right`.\n# \n# `0 < left < right < 10^9` in all calls to `addRange, queryRange, removeRange`.\n# \n# The total number of calls to `addRange` in a single test case is at most `1000`.\n# \n# The total number of calls to `queryRange` in a single test case is at most `5000`.\n# \n# The total number of calls to `removeRange` in a single test case is at most `1000`.\nclass RangeModule:\n\n def __init__(self):\n \n\n def addRange(self, left: int, right: int) -> None:\n \n\n def queryRange(self, left: int, right: int) -> bool:\n \n\n def removeRange(self, left: int, right: int) -> None:\n \n\n\n# Your RangeModule object will be instantiated and called as such:\n# obj = RangeModule()\n# obj.addRange(left,right)\n# param_2 = obj.queryRange(left,right)\n# obj.removeRange(left,right)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "find-k-th-smallest-pair-distance", "prompt": "# Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B. \n# \n# Example 1:\n# Input:\n# nums = [1,3,1]\n# k = 1\n# Output: 0 \n# Explanation:\n# Here are all the pairs:\n# (1,3) -> 2\n# (1,1) -> 0\n# (3,1) -> 2\n# Then the 1st smallest distance pair is (1,1), and its distance is 0.\n# \n# Note:\n# `2 <= len(nums) <= 10000`.\n# \n# `0 <= nums[i] < 1000000`.\n# \n# `1 <= k <= len(nums) * (len(nums) - 1) / 2`.\nclass Solution:\n def smallestDistancePair(self, nums: List[int], k: int) -> int:\n ", "entry_point": "smallestDistancePair", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-atoms", "prompt": "# Given a chemical `formula` (given as a string), return the count of each atom.\n# \n# The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.\n# \n# One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow. For example, H2O and H2O2 are possible, but H1O2 is impossible.\n# \n# Two formulas concatenated together to produce another formula. For example, H2O2He3Mg4 is also a formula.\n# \n# A formula placed in parentheses, and a count (optionally added) is also a formula. For example, (H2O2) and (H2O2)3 are formulas.\n# \n# Given a `formula`, return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.\n# \n# \n# Example 1:\n# Input: formula = \"H2O\"\n# Output: \"H2O\"\n# Explanation: The count of elements are {'H': 2, 'O': 1}.\n# \n# \n# Example 2:\n# Input: formula = \"Mg(OH)2\"\n# Output: \"H2MgO2\"\n# Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.\n# \n# \n# Example 3:\n# Input: formula = \"K4(ON(SO3)2)2\"\n# Output: \"K4N2O14S4\"\n# Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.\n# \n# \n# Example 4:\n# Input: formula = \"Be32\"\n# Output: \"Be32\"\n# \n# Constraints:\n# `1 <= formula.length <= 1000`\n# `formula` consists of English letters, digits, `'('`, and `')'`.\n# \n# `formula` is always valid.\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n ", "entry_point": "countOfAtoms", "cannonical_solution": "", "test": ""}
{"tast_id": "count-different-palindromic-subsequences", "prompt": "# Given a string S, find the number of different non-empty palindromic subsequences in S, and return that number modulo `10^9 + 7`.\n# \n# A subsequence of a string S is obtained by deleting 0 or more characters from S.\n# \n# A sequence is palindromic if it is equal to the sequence reversed.\n# \n# Two sequences `A_1, A_2, ...` and `B_1, B_2, ...` are different if there is some `i` for which `A_i != B_i`.\n# \n# \n# Example 1:\n# Input: \n# S = 'bccb'\n# Output: 6\n# Explanation: \n# The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.\n# \n# Note that 'bcb' is counted only once, even though it occurs twice.\n# \n# \n# Example 2:\n# Input: \n# S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba'\n# Output: 104860361\n# Explanation: \n# There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.\n# \n# Note:\n# The length of `S` will be in the range `[1, 1000]`.\n# \n# Each character `S[i]` will be in the set `{'a', 'b', 'c', 'd'}`.\nclass Solution:\n def countPalindromicSubsequences(self, s: str) -> int:\n ", "entry_point": "countPalindromicSubsequences", "cannonical_solution": "", "test": ""}
{"tast_id": "my-calendar-iii", "prompt": "# A `k`-booking happens when `k` events have some non-empty intersection (i.e., there is some time that is common to all `k` events.)\n# You are given some events `[start, end)`, after each given event, return an integer `k` representing the maximum `k`-booking between all the previous events.\n# \n# Implement the `MyCalendarThree` class:\n# `MyCalendarThree()` Initializes the object.\n# \n# `int book(int start, int end)` Returns an integer `k` representing the largest integer such that there exists a `k`-booking in the calendar.\n# \n# \n# Example 1:\n# Input\n# [\"MyCalendarThree\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n# [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]\n# Output\n# [null, 1, 1, 2, 3, 3, 3]\n# Explanation\n# MyCalendarThree myCalendarThree = new MyCalendarThree();\n# myCalendarThree.book(10, 20); // return 1, The first event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\n# \n# myCalendarThree.book(50, 60); // return 1, The second event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\n# \n# myCalendarThree.book(10, 40); // return 2, The third event [10, 40) intersects the first event, and the maximum k-booking is a 2-booking.\n# \n# myCalendarThree.book(5, 15); // return 3, The remaining events cause the maximum K-booking to be only a 3-booking.\n# \n# myCalendarThree.book(5, 10); // return 3\n# myCalendarThree.book(25, 55); // return 3\n# \n# Constraints:\n# `0 <= start < end <= 109`\n# At most `400` calls will be made to `book`.\nclass MyCalendarThree:\n\n def __init__(self):\n \n\n def book(self, startTime: int, endTime: int) -> int:\n \n\n\n# Your MyCalendarThree object will be instantiated and called as such:\n# obj = MyCalendarThree()\n# param_1 = obj.book(startTime,endTime)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "parse-lisp-expression", "prompt": "# You are given a string `expression` representing a Lisp-like expression to return the integer value of.\n# \n# The syntax for these expressions is given as follows.\n# \n# An expression is either an integer, a let-expression, an add-expression, a mult-expression, or an assigned variable. Expressions always evaluate to a single integer.\n# \n# (An integer could be positive or negative.)\n# A let-expression takes the form `(let v1 e1 v2 e2 ... vn en expr)`, where `let` is always the string `\"let\"`, then there are 1 or more pairs of alternating variables and expressions, meaning that the first variable `v1` is assigned the value of the expression `e1`, the second variable `v2` is assigned the value of the expression `e2`, and so on sequentially; and then the value of this let-expression is the value of the expression `expr`.\n# \n# An add-expression takes the form `(add e1 e2)` where `add` is always the string `\"add\"`, there are always two expressions `e1, e2`, and this expression evaluates to the addition of the evaluation of `e1` and the evaluation of `e2`.\n# \n# A mult-expression takes the form `(mult e1 e2)` where `mult` is always the string `\"mult\"`, there are always two expressions `e1, e2`, and this expression evaluates to the multiplication of the evaluation of `e1` and the evaluation of `e2`.\n# \n# For the purposes of this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally for your convenience, the names \"add\", \"let\", or \"mult\" are protected and will never be used as variable names.\n# \n# Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on scope.\n# \n# \n# Evaluation Examples:\n# Input: (add 1 2)\n# Output: 3\n# Input: (mult 3 (add 2 3))\n# Output: 15\n# Input: (let x 2 (mult x 5))\n# Output: 10\n# Input: (let x 2 (mult x (let x 3 y 4 (add x y))))\n# Output: 14\n# Explanation: In the expression (add x y), when checking for the value of the variable x,\n# we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\n# \n# Since x = 3 is found first, the value of x is 3.\n# \n# Input: (let x 3 x 2 x)\n# Output: 2\n# Explanation: Assignment in let statements is processed sequentially.\n# \n# Input: (let x 1 y 2 x (add x y) (add x y))\n# Output: 5\n# Explanation: The first (add x y) evaluates as 3, and is assigned to x.\n# \n# The second (add x y) evaluates as 3+2 = 5.\n# \n# Input: (let x 2 (add (let x 3 (let x 4 x)) x))\n# Output: 6\n# Explanation: Even though (let x 4 x) has a deeper scope, it is outside the context\n# of the final x in the add-expression. That final x will equal 2.\n# \n# Input: (let a1 3 b2 (add a1 1) b2) \n# Output 4\n# Explanation: Variable names can contain digits after the first character.\n# \n# Note:\n# The given string `expression` is well formatted: There are no leading or trailing spaces, there is only a single space separating different components of the string, and no space between adjacent parentheses. The expression is guaranteed to be legal and evaluate to an integer.\n# \n# The length of `expression` is at most 2000. (It is also non-empty, as that would not be a legal expression.)\n# The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.\nclass Solution:\n def evaluate(self, expression: str) -> int:\n ", "entry_point": "evaluate", "cannonical_solution": "", "test": ""}
{"tast_id": "cherry-pickup", "prompt": "# You are given an `n x n` `grid` representing a field of cherries, each cell is one of three possible integers.\n# \n# `0` means the cell is empty, so you can pass through,\n# `1` means the cell contains a cherry that you can pick up and pass through, or\n# `-1` means the cell contains a thorn that blocks your way.\n# \n# Return the maximum number of cherries you can collect by following the rules below:\n# Starting at the position `(0, 0)` and reaching `(n - 1, n - 1)` by moving right or down through valid path cells (cells with value `0` or `1`).\n# \n# After reaching `(n - 1, n - 1)`, returning to `(0, 0)` by moving left or up through valid path cells.\n# \n# When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell `0`.\n# \n# If there is no valid path between `(0, 0)` and `(n - 1, n - 1)`, then no cherries can be collected.\n# \n# \n# Example 1:\n# Input: grid = [[0,1,-1],[1,0,-1],[1,1,1]]\n# Output: 5\n# Explanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).\n# \n# 4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].\n# \n# Then, the player went left, up, up, left to return home, picking up one more cherry.\n# \n# The total number of cherries picked up is 5, and this is the maximum possible.\n# \n# \n# Example 2:\n# Input: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]\n# Output: 0\n# \n# Constraints:\n# `n == grid.length`\n# `n == grid[i].length`\n# `1 <= n <= 50`\n# `grid[i][j]` is `-1`, `0`, or `1`.\n# \n# `grid[0][0] != -1`\n# `grid[n - 1][n - 1] != -1`\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n ", "entry_point": "cherryPickup", "cannonical_solution": "", "test": ""}
{"tast_id": "prefix-and-suffix-search", "prompt": "# Design a special dictionary which has some words and allows you to search the words in it by a prefix and a suffix.\n# \n# Implement the `WordFilter` class:\n# `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.\n# \n# `f(string prefix, string suffix)` Returns the index of the word in the dictionary which has the prefix `prefix` and the suffix `suffix`. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return `-1`.\n# \n# \n# Example 1:\n# Input\n# [\"WordFilter\", \"f\"]\n# [[[\"apple\"]], [\"a\", \"e\"]]\n# Output\n# [null, 0]\n# Explanation\n# WordFilter wordFilter = new WordFilter([\"apple\"]);\n# wordFilter.f(\"a\", \"e\"); // return 0, because the word at index 0 has prefix = \"a\" and suffix = 'e\".\n# \n# \n# Constraints:\n# `1 <= words.length <= 15000`\n# `1 <= words[i].length <= 10`\n# `1 <= prefix.length, suffix.length <= 10`\n# `words[i]`, `prefix` and `suffix` consist of lower-case English letters only.\n# \n# At most `15000` calls will be made to the function `f`.\nclass WordFilter:\n\n def __init__(self, words: List[str]):\n \n\n def f(self, pref: str, suff: str) -> int:\n \n\n\n# Your WordFilter object will be instantiated and called as such:\n# obj = WordFilter(words)\n# param_1 = obj.f(pref,suff)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "contain-virus", "prompt": "# A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.\n# \n# The world is modeled as a 2-D array of cells, where `0` represents uninfected cells, and `1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary.\n# \n# Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall.\n# \n# Resources are limited. Each day, you can install walls around only one region -- the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night. There will never be a tie.\n# \n# Can you save the day? If so, what is the number of walls required? If not, and the world becomes fully infected, return the number of walls used.\n# \n# \n# Example 1:\n# Input: grid = \n# [[0,1,0,0,0,0,0,1],\n# [0,1,0,0,0,0,0,1],\n# [0,0,0,0,0,0,0,1],\n# [0,0,0,0,0,0,0,0]]\n# Output: 10\n# Explanation:\n# There are 2 contaminated regions.\n# \n# On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:\n# [[0,1,0,0,0,0,1,1],\n# [0,1,0,0,0,0,1,1],\n# [0,0,0,0,0,0,1,1],\n# [0,0,0,0,0,0,0,1]]\n# On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.\n# \n# \n# Example 2:\n# Input: grid = \n# [[1,1,1],\n# [1,0,1],\n# [1,1,1]]\n# Output: 4\n# Explanation: Even though there is only one cell saved, there are 4 walls built.\n# \n# Notice that walls are only built on the shared boundary of two different cells.\n# \n# \n# Example 3:\n# Input: grid = \n# [[1,1,1,0,0,0,0,0,0],\n# [1,0,1,0,1,1,1,1,1],\n# [1,1,1,0,0,0,0,0,0]]\n# Output: 13\n# Explanation: The region on the left only builds two new walls.\n# \n# Note:\n# The number of rows and columns of `grid` will each be in the range `[1, 50]`.\n# \n# Each `grid[i][j]` will be either `0` or `1`.\n# \n# Throughout the described process, there is always a contiguous viral region that will infect strictly more uncontaminated squares in the next round.\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n ", "entry_point": "containVirus", "cannonical_solution": "", "test": ""}
{"tast_id": "cracking-the-safe", "prompt": "# There is a box protected by a password. The password is a sequence of `n` digits where each digit can be one of the first `k` digits `0, 1, ..., k-1`.\n# \n# While entering a password, the last `n` digits entered will automatically be matched against the correct password.\n# \n# For example, assuming the correct password is `\"345\"`, if you type `\"012345\"`, the box will open because the correct password matches the suffix of the entered password.\n# \n# Return any password of minimum length that is guaranteed to open the box at some point of entering it.\n# \n# \n# Example 1:\n# Input: n = 1, k = 2\n# Output: \"01\"\n# Note: \"10\" will be accepted too.\n# \n# \n# Example 2:\n# Input: n = 2, k = 2\n# Output: \"00110\"\n# Note: \"01100\", \"10011\", \"11001\" will be accepted too.\n# \n# Note:\n# `n` will be in the range `[1, 4]`.\n# \n# `k` will be in the range `[1, 10]`.\n# \n# `k^n` will be at most `4096`.\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n ", "entry_point": "crackSafe", "cannonical_solution": "", "test": ""}
{"tast_id": "set-intersection-size-at-least-two", "prompt": "# An integer interval `[a, b]` (for integers `a < b`) is a set of all consecutive integers from `a` to `b`, including `a` and `b`.\n# \n# Find the minimum size of a set S such that for every integer interval A in `intervals`, the intersection of S with A has a size of at least two.\n# \n# \n# Example 1:\n# Input: intervals = [[1,3],[1,4],[2,5],[3,5]]\n# Output: 3\n# Explanation: Consider the set S = {2, 3, 4}. For each interval, there are at least 2 elements from S in the interval.\n# \n# Also, there isn't a smaller size set that fulfills the above condition.\n# \n# Thus, we output the size of this set, which is 3.\n# \n# \n# Example 2:\n# Input: intervals = [[1,2],[2,3],[2,4],[4,5]]\n# Output: 5\n# Explanation: An example of a minimum sized set is {1, 2, 3, 4, 5}.\n# \n# \n# Constraints:\n# `1 <= intervals.length <= 3000`\n# `intervals[i].length == 2`\n# `0 <= ai < bi <= 108`\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n ", "entry_point": "intersectionSizeTwo", "cannonical_solution": "", "test": ""}
{"tast_id": "special-binary-string", "prompt": "# Special binary strings are binary strings with the following two properties:\n# The number of 0's is equal to the number of 1's.\n# \n# Every prefix of the binary string has at least as many 1's as 0's.\n# \n# Given a special string `S`, a move consists of choosing two consecutive, non-empty, special substrings of `S`, and swapping them. (Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.)\n# At the end of any number of moves, what is the lexicographically largest resulting string possible?\n# \n# Example 1:\n# Input: S = \"11011000\"\n# Output: \"11100100\"\n# Explanation:\n# The strings \"10\" [occuring at S[1]] and \"1100\" [at S[3]] are swapped.\n# \n# This is the lexicographically largest string possible after some number of swaps.\n# \n# Note:\n# `S` has length at most `50`.\n# \n# `S` is guaranteed to be a special binary string as defined above.\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n ", "entry_point": "makeLargestSpecial", "cannonical_solution": "", "test": ""}
{"tast_id": "couples-holding-hands", "prompt": "# N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats. \n# The people and seats are represented by an integer from `0` to `2N-1`, the couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, and so on with the last couple being `(2N-2, 2N-1)`.\n# \n# The couples' initial seating is given by `row[i]` being the value of the person who is initially sitting in the i-th seat.\n# \n# \n# Example 1:Input: row = [0, 2, 1, 3]\n# Output: 1\n# Explanation: We only need to swap the second (row[1]) and third (row[2]) person.\n# \n# \n# Example 2:Input: row = [3, 2, 0, 1]\n# Output: 0\n# Explanation: All couples are already seated side by side.\n# \n# Note:\n# `len(row)` is even and in the range of `[4, 60]`.\n# \n# `row` is guaranteed to be a permutation of `0...len(row)-1`.\nclass Solution:\n def minSwapsCouples(self, row: List[int]) -> int:\n ", "entry_point": "minSwapsCouples", "cannonical_solution": "", "test": ""}
{"tast_id": "max-chunks-to-make-sorted-ii", "prompt": "# This question is the same as \"Max Chunks to Make Sorted\" except the integers of the given array are not necessarily distinct, the input array could be up to length `2000`, and the elements could be up to `10**8`.\n# \n# Given an array `arr` of integers (not necessarily distinct), we split the array into some number of \"chunks\" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.\n# \n# What is the most number of chunks we could have made?\n# \n# Example 1:\n# Input: arr = [5,4,3,2,1]\n# Output: 1\n# Explanation:\n# Splitting into two or more chunks will not return the required result.\n# \n# For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.\n# \n# \n# Example 2:\n# Input: arr = [2,1,3,4,4]\n# Output: 4\n# Explanation:\n# We can split into two chunks, such as [2, 1], [3, 4, 4].\n# \n# However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.\n# \n# Note:\n# `arr` will have length in range `[1, 2000]`.\n# \n# `arr[i]` will be an integer in range `[0, 10**8]`.\nclass Solution:\n def maxChunksToSorted(self, arr: List[int]) -> int:\n ", "entry_point": "maxChunksToSorted", "cannonical_solution": "", "test": ""}
{"tast_id": "basic-calculator-iv", "prompt": "# Given an `expression` such as `expression = \"e + 8 - a + 5\"` and an evaluation map such as `{\"e\": 1}` (given in terms of `evalvars = [\"e\"]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `[\"-1*a\",\"14\"]`\n# An expression alternates chunks and symbols, with a space separating each chunk and symbol.\n# \n# A chunk is either an expression in parentheses, a variable, or a non-negative integer.\n# \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# \n# Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. For example, `expression = \"1 + 2 * 3\"` has an answer of `[\"7\"]`.\n# \n# The format of the output is as follows:\n# For each term of free variables with non-zero coefficient, we write the free variables within a term in sorted order lexicographically. For example, we would never write a term like `\"b*a*c\"`, only `\"a*b*c\"`.\n# \n# Terms have degree equal to the number of free variables being multiplied, counting multiplicity. (For example, `\"a*a*b*c\"` has degree 4.) We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.\n# \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# \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. For example, an expression of \"0\" has an output of [].\n# \n# \n# Examples:\n# Input: expression = \"e + 8 - a + 5\", evalvars = [\"e\"], evalints = [1]\n# Output: [\"-1*a\",\"14\"]\n# Input: expression = \"e - 8 + temperature - pressure\",\n# evalvars = [\"e\", \"temperature\"], evalints = [1, 12]\n# Output: [\"-1*pressure\",\"5\"]\n# Input: expression = \"(e + 8) * (e - 8)\", evalvars = [], evalints = []\n# Output: [\"1*e*e\",\"-64\"]\n# Input: expression = \"7 - 7\", evalvars = [], evalints = []\n# Output: []\n# Input: expression = \"a * b * c + b * a * c * 4\", evalvars = [], evalints = []\n# Output: [\"5*a*b*c\"]\n# Input: expression = \"((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))\",\n# evalvars = [], evalints = []\n# Output: [\"-1*a*a*b*b\",\"2*a*a*b*c\",\"-1*a*a*c*c\",\"1*a*b*b*b\",\"-1*a*b*b*c\",\"-1*a*b*c*c\",\"1*a*c*c*c\",\"-1*b*b*b*c\",\"2*b*b*c*c\",\"-1*b*c*c*c\",\"2*a*a*b\",\"-2*a*a*c\",\"-2*a*b*b\",\"2*a*c*c\",\"1*b*b*b\",\"-1*b*b*c\",\"1*b*c*c\",\"-1*c*c*c\",\"-1*a*a\",\"1*a*b\",\"1*a*c\",\"-1*b*c\"]\n# Note:\n# `expression` will have length in range `[1, 250]`.\n# \n# `evalvars, evalints` will have equal lengths in range `[0, 100]`.\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n ", "entry_point": "basicCalculatorIV", "cannonical_solution": "", "test": ""}
{"tast_id": "sliding-puzzle", "prompt": "# On a 2x3 `board`, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0.\n# \n# A move consists of choosing `0` and a 4-directionally adjacent number and swapping it.\n# \n# The state of the board is solved if and only if the `board` is `[[1,2,3],[4,5,0]].`\n# Given a puzzle board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.\n# \n# \n# Examples:\n# Input: board = [[1,2,3],[4,0,5]]\n# Output: 1\n# Explanation: Swap the 0 and the 5 in one move.\n# \n# Input: board = [[1,2,3],[5,4,0]]\n# Output: -1\n# Explanation: No number of moves will make the board solved.\n# \n# Input: board = [[4,1,2],[5,0,3]]\n# Output: 5\n# Explanation: 5 is the smallest number of moves that solves the board.\n# \n# An example path:\n# After move 0: [[4,1,2],[5,0,3]]\n# After move 1: [[4,1,2],[0,5,3]]\n# After move 2: [[0,1,2],[4,5,3]]\n# After move 3: [[1,0,2],[4,5,3]]\n# After move 4: [[1,2,0],[4,5,3]]\n# After move 5: [[1,2,3],[4,5,0]]\n# Input: board = [[3,2,4],[1,5,0]]\n# Output: 14\n# Note:\n# `board` will be a 2 x 3 array as described above.\n# \n# `board[i][j]` will be a permutation of `[0, 1, 2, 3, 4, 5]`.\nclass Solution:\n def slidingPuzzle(self, board: List[List[int]]) -> int:\n ", "entry_point": "slidingPuzzle", "cannonical_solution": "", "test": ""}
{"tast_id": "swim-in-rising-water", "prompt": "# On an N x N `grid`, each square `grid[i][j]` represents the elevation at that point `(i,j)`.\n# \n# Now rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distance in zero time. Of course, you must stay within the boundaries of the grid during your swim.\n# \n# You start at the top left square `(0, 0)`. What is the least time until you can reach the bottom right square `(N-1, N-1)`?\n# \n# Example 1:\n# Input: [[0,2],[1,3]]\n# Output: 3\n# Explanation:\n# At time `0`, you are in grid location `(0, 0)`.\n# \n# You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\n# \n# You cannot reach point `(1, 1)` until time `3`.\n# \n# When the depth of water is `3`, we can swim anywhere inside the grid.\n# \n# \n# Example 2:\n# Input: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]\n# Output: 16\n# Explanation:\n# 0 1 2 3 4\n# 24 23 22 21 5\n# 12 13 14 15 16\n# 11 17 18 19 20\n# 10 9 8 7 6\n# The final route is marked in bold.\n# \n# We need to wait until time 16 so that (0, 0) and (4, 4) are connected.\n# \n# Note:\n# `2 <= N <= 50`.\n# \n# grid[i][j] is a permutation of [0, ..., N*N - 1].\nclass Solution:\n def swimInWater(self, grid: List[List[int]]) -> int:\n ", "entry_point": "swimInWater", "cannonical_solution": "", "test": ""}
{"tast_id": "reaching-points", "prompt": "# A move consists of taking a point `(x, y)` and transforming it to either `(x, x+y)` or `(x+y, y)`.\n# \n# Given a starting point `(sx, sy)` and a target point `(tx, ty)`, return `True` if and only if a sequence of moves exists to transform the point `(sx, sy)` to `(tx, ty)`. Otherwise, return `False`.\n# \n# \n# Examples:\n# Input: sx = 1, sy = 1, tx = 3, ty = 5\n# Output: True\n# Explanation:\n# One series of moves that transforms the starting point to the target is:\n# (1, 1) -> (1, 2)\n# (1, 2) -> (3, 2)\n# (3, 2) -> (3, 5)\n# Input: sx = 1, sy = 1, tx = 2, ty = 2\n# Output: False\n# Input: sx = 1, sy = 1, tx = 1, ty = 1\n# Output: True\n# Note:\n# `sx, sy, tx, ty` will all be integers in the range `[1, 10^9]`.\nclass Solution:\n def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:\n ", "entry_point": "reachingPoints", "cannonical_solution": "", "test": ""}
{"tast_id": "transform-to-chessboard", "prompt": "# An N x N `board` contains only `0`s and `1`s. In each move, you can swap any 2 rows with each other, or any 2 columns with each other.\n# \n# What is the minimum number of moves to transform the board into a \"chessboard\" - a board where no `0`s and no `1`s are 4-directionally adjacent? If the task is impossible, return -1.\n# \n# \n# Examples:\n# Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]\n# Output: 2\n# Explanation:\n# One potential sequence of moves is shown below, from left to right:\n# 0110 1010 1010\n# 0110 --> 1010 --> 0101\n# 1001 0101 1010\n# 1001 0101 0101\n# The first move swaps the first and second column.\n# \n# The second move swaps the second and third row.\n# \n# Input: board = [[0, 1], [1, 0]]\n# Output: 0\n# Explanation:\n# Also note that the board with 0 in the top left corner,\n# 01\n# 10\n# is also a valid chessboard.\n# \n# Input: board = [[1, 0], [1, 0]]\n# Output: -1\n# Explanation:\n# No matter what sequence of moves you make, you cannot end with a valid chessboard.\n# \n# Note:\n# `board` will have the same number of rows and columns, a number in the range `[2, 30]`.\n# \n# `board[i][j]` will be only `0`s or `1`s.\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n ", "entry_point": "movesToChessboard", "cannonical_solution": "", "test": ""}
{"tast_id": "k-th-smallest-prime-fraction", "prompt": "# You are given a sorted integer array `arr` containing `1` and prime numbers, where all the integers of `arr` are unique. You are also given an integer `k`.\n# \n# For every `i` and `j` where `0 <= i < j < arr.length`, we consider the fraction `arr[i] / arr[j]`.\n# \n# Return the `kth` smallest fraction considered. Return your answer as an array of integers of size `2`, where `answer[0] == arr[i]` and `answer[1] == arr[j]`.\n# \n# \n# Example 1:\n# Input: arr = [1,2,3,5], k = 3\n# Output: [2,5]\n# Explanation: The fractions to be considered in sorted order are:\n# 1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.\n# \n# The third fraction is 2/5.\n# \n# \n# Example 2:\n# Input: arr = [1,7], k = 1\n# Output: [1,7]\n# \n# Constraints:\n# `2 <= arr.length <= 1000`\n# `1 <= arr[i] <= 3 * 104`\n# `arr[0] == 1`\n# `arr[i]` is a prime number for `i > 0`.\n# \n# All the numbers of `arr` are unique and sorted in strictly increasing order.\n# \n# `1 <= k <= arr.length * (arr.length - 1) / 2`\nclass Solution:\n def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]:\n ", "entry_point": "kthSmallestPrimeFraction", "cannonical_solution": "", "test": ""}
{"tast_id": "preimage-size-of-factorial-zeroes-function", "prompt": "# Let `f(x)` be the number of zeroes at the end of `x!`. (Recall that `x! = 1 * 2 * 3 * ... * x`, and by convention, `0! = 1`.)\n# For example, `f(3) = 0` because 3! = 6 has no zeroes at the end, while `f(11) = 2` because 11! = 39916800 has 2 zeroes at the end. Given `K`, find how many non-negative integers `x` have the property that `f(x) = K`.\n# \n# \n# Example 1:\n# Input: K = 0\n# Output: 5\n# Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes.\n# \n# \n# Example 2:\n# Input: K = 5\n# Output: 0\n# Explanation: There is no x such that x! ends in K = 5 zeroes.\n# \n# Note:\n# `K` will be an integer in the range `[0, 10^9]`.\nclass Solution:\n def preimageSizeFZF(self, k: int) -> int:\n ", "entry_point": "preimageSizeFZF", "cannonical_solution": "", "test": ""}
{"tast_id": "smallest-rotation-with-highest-score", "prompt": "# Given an array `A`, we may rotate it by a non-negative integer `K` so that the array becomes `A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1]`. Afterward, any entries that are less than or equal to their index are worth 1 point. \n# For example, if we have `[2, 4, 1, 3, 0]`, and we rotate by `K = 2`, it becomes `[1, 3, 0, 2, 4]`. This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point].\n# \n# Over all possible rotations, return the rotation index K that corresponds to the highest score we could receive. If there are multiple answers, return the smallest such index K.\n# \n# \n# Example 1:\n# Input: [2, 3, 1, 4, 0]\n# Output: 3\n# Explanation: \n# Scores for each K are listed below: \n# K = 0, A = [2,3,1,4,0], score 2\n# K = 1, A = [3,1,4,0,2], score 3\n# K = 2, A = [1,4,0,2,3], score 3\n# K = 3, A = [4,0,2,3,1], score 4\n# K = 4, A = [0,2,3,1,4], score 3\n# So we should choose K = 3, which has the highest score.\n# \n# \n# Example 2:\n# Input: [1, 3, 0, 2, 4]\n# Output: 0\n# Explanation: A will always have 3 points no matter how it shifts.\n# \n# So we will choose the smallest K, which is 0.\n# \n# Note:\n# `A` will have length at most `20000`.\n# \n# `A[i]` will be in the range `[0, A.length]`.\nclass Solution:\n def bestRotation(self, nums: List[int]) -> int:\n ", "entry_point": "bestRotation", "cannonical_solution": "", "test": ""}
{"tast_id": "bricks-falling-when-hit", "prompt": "# You are given an `m x n` binary `grid`, where each `1` represents a brick and `0` represents an empty space. A brick is stable if:\n# It is directly connected to the top of the grid, or\n# At least one other brick in its four adjacent cells is stable.\n# \n# You are also given an array `hits`, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location `hits[i] = (rowi, coli)`. The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the `grid` (i.e., it does not land on other stable bricks).\n# \n# Return an array `result`, where each `result[i]` is the number of bricks that will fall after the `ith` erasure is applied.\n# \n# Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.\n# \n# \n# Example 1:\n# Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]\n# Output: [2]\n# Explanation: Starting with the grid:\n# [[1,0,0,0],\n# [1,1,1,0]]\n# We erase the underlined brick at (1,0), resulting in the grid:\n# [[1,0,0,0],\n# [0,1,1,0]]\n# The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:\n# [[1,0,0,0],\n# [0,0,0,0]]\n# Hence the result is [2].\n# \n# \n# Example 2:\n# Input: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]\n# Output: [0,0]\n# Explanation: Starting with the grid:\n# [[1,0,0,0],\n# [1,1,0,0]]\n# We erase the underlined brick at (1,1), resulting in the grid:\n# [[1,0,0,0],\n# [1,0,0,0]]\n# All remaining bricks are still stable, so no bricks fall. The grid remains the same:\n# [[1,0,0,0],\n# [1,0,0,0]]\n# Next, we erase the underlined brick at (1,0), resulting in the grid:\n# [[1,0,0,0],\n# [0,0,0,0]]\n# Once again, all remaining bricks are still stable, so no bricks fall.\n# \n# Hence the result is [0,0].\n# \n# \n# Constraints:\n# `m == grid.length`\n# `n == grid[i].length`\n# `1 <= m, n <= 200`\n# `grid[i][j]` is `0` or `1`.\n# \n# `1 <= hits.length <= 4 * 104`\n# `hits[i].length == 2`\n# `0 <= xi <= m - 1`\n# `0 <= yi <= n - 1`\n# All `(xi, yi)` are unique.\nclass Solution:\n def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:\n ", "entry_point": "hitBricks", "cannonical_solution": "", "test": ""}
{"tast_id": "split-array-with-same-average", "prompt": "# You are given an integer array `nums`.\n# \n# You should move each element of `nums` into one of the two arrays `A` and `B` such that `A` and `B` are non-empty, and `average(A) == average(B)`.\n# \n# Return `true` if it is possible to achieve that and `false` otherwise.\n# \n# Note that for an array `arr`, `average(arr)` is the sum of all the elements of `arr` over the length of `arr`.\n# \n# \n# Example 1:\n# Input: nums = [1,2,3,4,5,6,7,8]\n# Output: true\n# Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.\n# \n# \n# Example 2:\n# Input: nums = [3,1]\n# Output: false\n# \n# Constraints:\n# `1 <= nums.length <= 30`\n# `0 <= nums[i] <= 104`\nclass Solution:\n def splitArraySameAverage(self, nums: List[int]) -> bool:\n ", "entry_point": "splitArraySameAverage", "cannonical_solution": "", "test": ""}
{"tast_id": "chalkboard-xor-game", "prompt": "# We are given non-negative integers nums[i] which are written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. (Also, we'll say the bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.)\n# Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.\n# \n# Return True if and only if Alice wins the game, assuming both players play optimally.\n# \n# \n# Example:\n# Input: nums = [1, 1, 2]\n# Output: false\n# Explanation: \n# Alice has two choices: erase 1 or erase 2. \n# If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. \n# If Alice erases 2 first, now nums becomes [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.\n# \n# Notes: \n# `1 <= N <= 1000`. \n# `0 <= nums[i] <= 2^16`.\nclass Solution:\n def xorGame(self, nums: List[int]) -> bool:\n ", "entry_point": "xorGame", "cannonical_solution": "", "test": ""}
{"tast_id": "bus-routes", "prompt": "# You are given an array `routes` representing bus routes where `routes[i]` is a bus 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# \n# You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only.\n# \n# Return the least number of buses you must take to travel from `source` to `target`. Return `-1` if it is not possible.\n# \n# \n# Example 1:\n# Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6\n# Output: 2\n# Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.\n# \n# \n# Example 2:\n# Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12\n# Output: -1\n# \n# Constraints:\n# `1 <= routes.length <= 500`.\n# \n# `1 <= routes[i].length <= 105`\n# All the values of `routes[i]` are unique.\n# \n# `sum(routes[i].length) <= 105`\n# `0 <= routes[i][j] < 106`\n# `0 <= source, target < 106`\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n ", "entry_point": "numBusesToDestination", "cannonical_solution": "", "test": ""}
{"tast_id": "race-car", "prompt": "# Your car starts at position 0 and speed +1 on an infinite number line. (Your car can go into negative positions.)\n# Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse).\n# \n# When you get an instruction \"A\", your car does the following: `position += speed, speed *= 2`.\n# \n# When you get an instruction \"R\", your car does the following: if your speed is positive then `speed = -1` , otherwise `speed = 1`. (Your position stays the same.)\n# For example, after commands \"AAR\", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1.\n# \n# Now for some target position, say the length of the shortest sequence of instructions to get there.\n# \n# \n# Example 1:\n# Input: \n# target = 3\n# Output: 2\n# Explanation: \n# The shortest instruction sequence is \"AA\".\n# \n# Your position goes from 0->1->3.\n# \n# \n# Example 2:\n# Input: \n# target = 6\n# Output: 5\n# Explanation: \n# The shortest instruction sequence is \"AAARA\".\n# \n# Your position goes from 0->1->3->7->7->6.\n# \n# Note: \n# `1 <= target <= 10000`.\nclass Solution:\n def racecar(self, target: int) -> int:\n ", "entry_point": "racecar", "cannonical_solution": "", "test": ""}
{"tast_id": "making-a-large-island", "prompt": "# You are given an `n x n` binary matrix `grid`. You are allowed to change at most one `0` to be `1`.\n# \n# Return the size of the largest island in `grid` after applying this operation.\n# \n# An island is a 4-directionally connected group of `1`s.\n# \n# \n# Example 1:\n# Input: grid = [[1,0],[0,1]]\n# Output: 3\n# Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.\n# \n# \n# Example 2:\n# Input: grid = [[1,1],[1,0]]\n# Output: 4\n# Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.\n# \n# \n# Example 3:\n# Input: grid = [[1,1],[1,1]]\n# Output: 4\n# Explanation: Can't change any 0 to 1, only one island with area = 4.\n# \n# \n# Constraints:\n# `n == grid.length`\n# `n == grid[i].length`\n# `1 <= n <= 500`\n# `grid[i][j]` is either `0` or `1`.\nclass Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n ", "entry_point": "largestIsland", "cannonical_solution": "", "test": ""}
{"tast_id": "count-unique-characters-of-all-substrings-of-a-given-string", "prompt": "# Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`, for example if `s = \"LEETCODE\"` then `\"L\"`, `\"T\"`,`\"C\"`,`\"O\"`,`\"D\"` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`.\n# \n# On this problem given a string `s` we need to return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. Notice that some substrings can be repeated so on this case you have to count the repeated ones too.\n# \n# Since the answer can be very large, return the answer modulo `10 ^ 9 + 7`.\n# \n# \n# Example 1:\n# Input: s = \"ABC\"\n# Output: 10\n# Explanation: All possible substrings are: \"A\",\"B\",\"C\",\"AB\",\"BC\" and \"ABC\".\n# \n# Evey substring is composed with only unique letters.\n# \n# Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10\n# \n# Example 2:\n# Input: s = \"ABA\"\n# Output: 8\n# Explanation: The same as example 1, except `countUniqueChars`(\"ABA\") = 1.\n# \n# \n# Example 3:\n# Input: s = \"LEETCODE\"\n# Output: 92\n# \n# Constraints:\n# `0 <= s.length <= 10^4`\n# `s` contain upper-case English letters only.\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n ", "entry_point": "uniqueLetterString", "cannonical_solution": "", "test": ""}
{"tast_id": "consecutive-numbers-sum", "prompt": "# Given a positive integer `N`, how many ways can we write it as a sum of consecutive positive integers?\n# \n# Example 1:\n# Input: 5\n# Output: 2\n# Explanation: 5 = 5 = 2 + 3\n# \n# Example 2:\n# Input: 9\n# Output: 3\n# Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4\n# \n# Example 3:\n# Input: 15\n# Output: 4\n# Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5\n# Note: `1 <= N <= 10 ^ 9`.\nclass Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n ", "entry_point": "consecutiveNumbersSum", "cannonical_solution": "", "test": ""}
{"tast_id": "sum-of-distances-in-tree", "prompt": "# An undirected, connected tree with `N` nodes labelled `0...N-1` and `N-1` `edges` are given.\n# \n# The `i`th edge connects nodes `edges[i][0] `and` edges[i][1]` together.\n# \n# Return a list `ans`, where `ans[i]` is the sum of the distances between node `i` and all other nodes.\n# \n# \n# Example 1:\n# Input: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]\n# Output: [8,12,6,10,10,10]\n# Explanation: \n# Here is a diagram of the given tree:\n# 0\n# / \\\n# 1 2\n# /|\\\n# 3 4 5\n# We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\n# equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer[0] = 8, and so on.\n# \n# Note: `1 <= N <= 10000`\nclass Solution:\n def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n ", "entry_point": "sumOfDistancesInTree", "cannonical_solution": "", "test": ""}
{"tast_id": "similar-string-groups", "prompt": "# Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal.\n# \n# For example, `\"tars\"` and `\"rats\"` are similar (swapping at positions `0` and `2`), and `\"rats\"` and `\"arts\"` are similar, but `\"star\"` is not similar to `\"tars\"`, `\"rats\"`, or `\"arts\"`.\n# \n# Together, these form two connected groups by similarity: `{\"tars\", \"rats\", \"arts\"}` and `{\"star\"}`. Notice that `\"tars\"` and `\"arts\"` are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.\n# \n# We are given a list `strs` of strings where every string in `strs` is an anagram of every other string in `strs`. How many groups are there?\n# \n# Example 1:\n# Input: strs = [\"tars\",\"rats\",\"arts\",\"star\"]\n# Output: 2\n# \n# Example 2:\n# Input: strs = [\"omv\",\"ovm\"]\n# Output: 1\n# \n# Constraints:\n# `1 <= strs.length <= 300`\n# `1 <= strs[i].length <= 300`\n# `strs[i]` consists of lowercase letters only.\n# \n# All words in `strs` have the same length and are anagrams of each other.\nclass Solution:\n def numSimilarGroups(self, strs: List[str]) -> int:\n ", "entry_point": "numSimilarGroups", "cannonical_solution": "", "test": ""}
{"tast_id": "shortest-path-visiting-all-nodes", "prompt": "# An undirected, connected graph of N nodes (labeled `0, 1, 2, ..., N-1`) is given as `graph`.\n# \n# `graph.length = N`, and `j != i` is in the list `graph[i]` exactly once, if and only if nodes `i` and `j` are connected.\n# \n# Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.\n# \n# \n# Example 1:\n# Input: [[1,2,3],[0],[0],[0]]\n# Output: 4\n# Explanation: One possible path is [1,0,2,0,3]\n# \n# Example 2:\n# Input: [[1],[0,2,4],[1,3,4],[2],[1,2]]\n# Output: 4\n# Explanation: One possible path is [0,1,4,2,3]\n# Note:\n# `1 <= graph.length <= 12`\n# `0 <= graph[i].length < graph.length`\nclass Solution:\n def shortestPathLength(self, graph: List[List[int]]) -> int:\n ", "entry_point": "shortestPathLength", "cannonical_solution": "", "test": ""}
{"tast_id": "rectangle-area-ii", "prompt": "# We are given a list of (axis-aligned) `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2] `, where `(xi1, yi1)` are the coordinates of the bottom-left corner, and `(xi2, yi2)` are the coordinates of the top-right corner of the `ith` rectangle.\n# \n# Find the total area covered by all `rectangles` in the plane. Since the answer may be too large, return it modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]\n# Output: 6\n# Explanation: As illustrated in the picture.\n# \n# \n# Example 2:\n# Input: rectangles = [[0,0,1000000000,1000000000]]\n# Output: 49\n# Explanation: The answer is 1018 modulo (109 + 7), which is (109)2 = (-7)2 = 49.\n# \n# \n# Constraints:\n# `1 <= rectangles.length <= 200`\n# `rectanges[i].length = 4`\n# `0 <= rectangles[i][j] <= 109`\n# The total area covered by all rectangles will never exceed `263 - 1` and thus will fit in a 64-bit signed integer.\nclass Solution:\n def rectangleArea(self, rectangles: List[List[int]]) -> int:\n ", "entry_point": "rectangleArea", "cannonical_solution": "", "test": ""}
{"tast_id": "k-similar-strings", "prompt": "# Strings `s1` and `s2` are `k`-similar (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`.\n# \n# Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`-similar.\n# \n# \n# Example 1:\n# Input: s1 = \"ab\", s2 = \"ba\"\n# Output: 1\n# \n# Example 2:\n# Input: s1 = \"abc\", s2 = \"bca\"\n# Output: 2\n# \n# Example 3:\n# Input: s1 = \"abac\", s2 = \"baca\"\n# Output: 2\n# \n# Example 4:\n# Input: s1 = \"aabc\", s2 = \"abca\"\n# Output: 2\n# \n# Constraints:\n# `1 <= s1.length <= 20`\n# `s2.length == s1.length`\n# `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`.\n# \n# `s2` is an anagram of `s1`.\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n ", "entry_point": "kSimilarity", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-cost-to-hire-k-workers", "prompt": "# There are `N` workers. The `i`-th worker has a `quality[i]` and a minimum wage expectation `wage[i]`.\n# \n# Now we want to hire exactly `K` workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:\n# Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.\n# \n# Every worker in the paid group must be paid at least their minimum wage expectation.\n# \n# Return the least amount of money needed to form a paid group satisfying the above conditions.\n# \n# \n# Example 1:\n# Input: quality = [10,20,5], wage = [70,50,30], K = 2\n# Output: 105.00000\n# Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.\n# \n# \n# Example 2:\n# Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3\n# Output: 30.66667\n# Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately. \n# Note:\n# `1 <= K <= N <= 10000`, where `N = quality.length = wage.length`\n# `1 <= quality[i] <= 10000`\n# `1 <= wage[i] <= 10000`\n# Answers within `10^-5` of the correct answer will be considered correct.\nclass Solution:\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:\n ", "entry_point": "mincostToHireWorkers", "cannonical_solution": "", "test": ""}
{"tast_id": "shortest-subarray-with-sum-at-least-k", "prompt": "# Return the length of the shortest, non-empty, contiguous subarray of `A` with sum at least `K`.\n# \n# If there is no non-empty subarray with sum at least `K`, return `-1`.\n# \n# \n# Example 1:\n# Input: A = [1], K = 1\n# Output: 1\n# \n# Example 2:\n# Input: A = [1,2], K = 4\n# Output: -1\n# \n# Example 3:\n# Input: A = [2,-1,2], K = 3\n# Output: 3\n# Note:\n# `1 <= A.length <= 50000`\n# `-10 ^ 5 <= A[i] <= 10 ^ 5`\n# `1 <= K <= 10 ^ 9`\nclass Solution:\n def shortestSubarray(self, nums: List[int], k: int) -> int:\n ", "entry_point": "shortestSubarray", "cannonical_solution": "", "test": ""}
{"tast_id": "shortest-path-to-get-all-keys", "prompt": "# We are given a 2-dimensional `grid`. `\".\"` is an empty cell, `\"#\"` is a wall, `\"@\"` is the starting point, (`\"a\"`, `\"b\"`, ...) are keys, and (`\"A\"`, `\"B\"`, ...) are locks.\n# \n# We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions. We cannot walk outside the grid, or walk into a wall. If we walk over a key, we pick it up. We can't walk over a lock unless we have the corresponding key.\n# \n# For some 1 <= K <= 6, there is exactly one lowercase and one uppercase letter of the first `K` letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.\n# \n# Return the lowest number of moves to acquire all keys. If it's impossible, return `-1`.\n# \n# \n# Example 1:\n# Input: [\"@.a.#\",\"###.#\",\"b.A.B\"]\n# Output: 8\n# \n# Example 2:\n# Input: [\"@..aA\",\"..B#.\",\"....b\"]\n# Output: 6\n# Note:\n# `1 <= grid.length <= 30`\n# `1 <= grid[0].length <= 30`\n# `grid[i][j]` contains only` '.'`, `'#'`, `'@'`, `'a'-``'f``'` and `'A'-'F'`\n# The number of keys is in `[1, 6]`. Each key has a different letter and opens exactly one lock.\nclass Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n ", "entry_point": "shortestPathAllKeys", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-number-of-refueling-stops", "prompt": "# A car travels from a starting position to a destination which is `target` miles east of the starting position.\n# \n# Along the way, there are gas stations. Each `station[i]` represents a gas station that is `station[i][0]` miles east of the starting position, and has `station[i][1]` liters of gas.\n# \n# The car starts with an infinite tank of gas, which initially has `startFuel` liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.\n# \n# When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.\n# \n# What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return `-1`.\n# \n# Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.\n# \n# \n# Example 1:\n# Input: target = 1, startFuel = 1, stations = []\n# Output: 0\n# Explanation: We can reach the target without refueling.\n# \n# \n# Example 2:\n# Input: target = 100, startFuel = 1, stations = [[10,100]]\n# Output: -1\n# Explanation: We can't reach the target (or even the first gas station).\n# \n# \n# Example 3:\n# Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]\n# Output: 2\n# Explanation: \n# We start with 10 liters of fuel.\n# \n# We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\n# \n# Then, we drive from position 10 to position 60 (expending 50 liters of fuel),\n# and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\n# \n# We made 2 refueling stops along the way, so we return 2.\n# \n# Note:\n# `1 <= target, startFuel, stations[i][1] <= 10^9`\n# `0 <= stations.length <= 500`\n# `0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target`\nclass Solution:\n def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:\n ", "entry_point": "minRefuelStops", "cannonical_solution": "", "test": ""}
{"tast_id": "nth-magical-number", "prompt": "# A positive integer is magical if it is divisible by either `a` or `b`.\n# \n# Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, return it modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: n = 1, a = 2, b = 3\n# Output: 2\n# \n# Example 2:\n# Input: n = 4, a = 2, b = 3\n# Output: 6\n# \n# Example 3:\n# Input: n = 5, a = 2, b = 4\n# Output: 10\n# \n# Example 4:\n# Input: n = 3, a = 6, b = 4\n# Output: 8\n# \n# Constraints:\n# `1 <= n <= 109`\n# `2 <= a, b <= 4 * 104`\nclass Solution:\n def nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n ", "entry_point": "nthMagicalNumber", "cannonical_solution": "", "test": ""}
{"tast_id": "profitable-schemes", "prompt": "# There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime.\n# \n# Let's call a profitable scheme any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`.\n# \n# Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: n = 5, minProfit = 3, group = [2,2], profit = [2,3]\n# Output: 2\n# Explanation: To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.\n# \n# In total, there are 2 schemes.\n# \n# \n# Example 2:\n# Input: n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]\n# Output: 7\n# Explanation: To make a profit of at least 5, the group could commit any crimes, as long as they commit one.\n# \n# There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).\n# \n# \n# Constraints:\n# `1 <= n <= 100`\n# `0 <= minProfit <= 100`\n# `1 <= group.length <= 100`\n# `1 <= group[i] <= 100`\n# `profit.length == group.length`\n# `0 <= profit[i] <= 100`\nclass Solution:\n def profitableSchemes(self, n: int, minProfit: int, group: List[int], profit: List[int]) -> int:\n ", "entry_point": "profitableSchemes", "cannonical_solution": "", "test": ""}
{"tast_id": "reachable-nodes-in-subdivided-graph", "prompt": "# You are given an undirected graph (the \"original graph\") with `n` nodes labeled from `0` to `n - 1`. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.\n# \n# The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indicates that there is an edge between nodes `ui` and `vi` in the original graph, and `cnti` is the total number of new nodes that you will subdivide the edge into. Note that `cnti == 0` means you will not subdivide the edge.\n# \n# To subdivide the edge `[ui, vi]`, replace it with `(cnti + 1)` new edges and `cnti` new nodes. The new nodes are `x1`, `x2`, ..., `xcnti`, and the new edges are `[ui, x1]`, `[x1, x2]`, `[x2, x3]`, ..., `[xcnti+1, xcnti]`, `[xcnti, vi]`.\n# \n# In this new graph, you want to know how many nodes are reachable from the node `0`, where a node is reachable if the distance is `maxMoves` or less.\n# \n# Given the original graph and `maxMoves`, return the number of nodes that are reachable from node `0` in the new graph.\n# \n# \n# Example 1:\n# Input: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3\n# Output: 13\n# Explanation: The edge subdivisions are shown in the image above.\n# \n# The nodes that are reachable are highlighted in yellow.\n# \n# \n# Example 2:\n# Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4\n# Output: 23\n# \n# Example 3:\n# Input: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5\n# Output: 1\n# Explanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.\n# \n# \n# Constraints:\n# `0 <= edges.length <= min(n * (n - 1) / 2, 104)`\n# `edges[i].length == 3`\n# `0 <= ui < vi < n`\n# There are no multiple edges in the graph.\n# \n# `0 <= cnti <= 104`\n# `0 <= maxMoves <= 109`\n# `1 <= n <= 3000`\nclass Solution:\n def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:\n ", "entry_point": "reachableNodes", "cannonical_solution": "", "test": ""}
{"tast_id": "super-egg-drop", "prompt": "# You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`.\n# \n# You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor higher than `f` will break, and any egg dropped at or below floor `f` will not break.\n# \n# Each move, you may take an unbroken egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.\n# \n# Return the minimum number of moves that you need to determine with certainty what the value of `f` is.\n# \n# \n# Example 1:\n# Input: k = 1, n = 2\n# Output: 2\n# Explanation: \n# Drop the egg from floor 1. If it breaks, we know that f = 0.\n# \n# Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1.\n# \n# If it does not break, then we know f = 2.\n# \n# Hence, we need at minimum 2 moves to determine with certainty what the value of f is.\n# \n# \n# Example 2:\n# Input: k = 2, n = 6\n# Output: 3\n# \n# Example 3:\n# Input: k = 3, n = 14\n# Output: 4\n# \n# Constraints:\n# `1 <= k <= 100`\n# `1 <= n <= 104`\nclass Solution:\n def superEggDrop(self, k: int, n: int) -> int:\n ", "entry_point": "superEggDrop", "cannonical_solution": "", "test": ""}
{"tast_id": "sum-of-subsequence-widths", "prompt": "# Given an array of integers `A`, consider all non-empty subsequences of `A`.\n# \n# For any sequence S, let the width of S be the difference between the maximum and minimum element of S.\n# \n# Return the sum of the widths of all subsequences of A. \n# As the answer may be very large, return the answer modulo 10^9 + 7.\n# \n# \n# Example 1:\n# Input: [2,1,3]\n# Output: 6\n# Explanation:\n# Subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\n# \n# The corresponding widths are 0, 0, 0, 1, 1, 2, 2.\n# \n# The sum of these widths is 6.\n# \n# Note:\n# `1 <= A.length <= 20000`\n# `1 <= A[i] <= 20000`\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n ", "entry_point": "sumSubseqWidths", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-frequency-stack", "prompt": "# Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.\n# \n# Implement the `FreqStack` class:\n# `FreqStack()` constructs an empty frequency stack.\n# \n# `void push(int val)` pushes an integer `val` onto the top of the stack.\n# \n# `int pop()` removes and returns the most frequent element in the stack.\n# \n# \t\n# If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.\n# \n# \n# Example 1:\n# Input\n# [\"FreqStack\", \"push\", \"push\", \"push\", \"push\", \"push\", \"push\", \"pop\", \"pop\", \"pop\", \"pop\"]\n# [[], [5], [7], [5], [7], [4], [5], [], [], [], []]\n# Output\n# [null, null, null, null, null, null, null, 5, 7, 5, 4]\n# Explanation\n# FreqStack freqStack = new FreqStack();\n# freqStack.push(5); // The stack is [5]\n# freqStack.push(7); // The stack is [5,7]\n# freqStack.push(5); // The stack is [5,7,5]\n# freqStack.push(7); // The stack is [5,7,5,7]\n# freqStack.push(4); // The stack is [5,7,5,7,4]\n# freqStack.push(5); // The stack is [5,7,5,7,4,5]\n# freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].\n# \n# freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].\n# \n# freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4].\n# \n# freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].\n# \n# \n# Constraints:\n# `0 <= val <= 109`\n# At most `2 * 104` calls will be made to `push` and `pop`.\n# \n# It is guaranteed that there will be at least one element in the stack before calling `pop`.\nclass FreqStack:\n\n def __init__(self):\n \n\n def push(self, val: int) -> None:\n \n\n def pop(self) -> int:\n \n\n\n# Your FreqStack object will be instantiated and called as such:\n# obj = FreqStack()\n# obj.push(val)\n# param_2 = obj.pop()", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "orderly-queue", "prompt": "# A string `S` of lowercase letters is given. Then, we may make any number of moves.\n# \n# In each move, we choose one of the first `K` letters (starting from the left), remove it, and place it at the end of the string.\n# \n# Return the lexicographically smallest string we could have after any number of moves.\n# \n# \n# Example 1:\n# Input: S = \"cba\", K = 1\n# Output: \"acb\"\n# Explanation: \n# In the first move, we move the 1st character (\"c\") to the end, obtaining the string \"bac\".\n# \n# In the second move, we move the 1st character (\"b\") to the end, obtaining the final result \"acb\".\n# \n# \n# Example 2:\n# Input: S = \"baaca\", K = 3\n# Output: \"aaabc\"\n# Explanation: \n# In the first move, we move the 1st character (\"b\") to the end, obtaining the string \"aacab\".\n# \n# In the second move, we move the 3rd character (\"c\") to the end, obtaining the final result \"aaabc\".\n# \n# Note:\n# `1 <= K <= S.length <= 1000`\n# `S` consists of lowercase letters only.\nclass Solution:\n def orderlyQueue(self, s: str, k: int) -> str:\n ", "entry_point": "orderlyQueue", "cannonical_solution": "", "test": ""}
{"tast_id": "numbers-at-most-n-given-digit-set", "prompt": "# Given an array of `digits` which is sorted in non-decreasing order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`.\n# \n# Return the number of positive integers that can be generated that are less than or equal to a given integer `n`.\n# \n# \n# Example 1:\n# Input: digits = [\"1\",\"3\",\"5\",\"7\"], n = 100\n# Output: 20\n# Explanation: \n# The 20 numbers that can be written are:\n# 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.\n# \n# \n# Example 2:\n# Input: digits = [\"1\",\"4\",\"9\"], n = 1000000000\n# Output: 29523\n# Explanation: \n# We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,\n# 81 four digit numbers, 243 five digit numbers, 729 six digit numbers,\n# 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.\n# \n# In total, this is 29523 integers that can be written using the digits array.\n# \n# \n# Example 3:\n# Input: digits = [\"7\"], n = 8\n# Output: 1\n# \n# Constraints:\n# `1 <= digits.length <= 9`\n# `digits[i].length == 1`\n# `digits[i]` is a digit from `'1'` to `'9'`.\n# \n# All the values in `digits` are unique.\n# \n# `digits` is sorted in non-decreasing order.\n# \n# `1 <= n <= 109`\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n ", "entry_point": "atMostNGivenDigitSet", "cannonical_solution": "", "test": ""}
{"tast_id": "valid-permutations-for-di-sequence", "prompt": "# We are given `S`, a length `n` string of characters from the set `{'D', 'I'}`. (These letters stand for \"decreasing\" and \"increasing\".)\n# A valid permutation is a permutation `P[0], P[1], ..., P[n]` of integers `{0, 1, ..., n}`, such that for all `i`:\n# If `S[i] == 'D'`, then `P[i] > P[i+1]`, and;\n# If `S[i] == 'I'`, then `P[i] < P[i+1]`.\n# \n# How many valid permutations are there? Since the answer may be large, return your answer modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: \"DID\"\n# Output: 5\n# Explanation: \n# The 5 valid permutations of (0, 1, 2, 3) are:\n# (1, 0, 3, 2)\n# (2, 0, 3, 1)\n# (2, 1, 3, 0)\n# (3, 0, 2, 1)\n# (3, 1, 2, 0)\n# Note:\n# `1 <= S.length <= 200`\n# `S` consists only of characters from the set `{'D', 'I'}`.\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n ", "entry_point": "numPermsDISequence", "cannonical_solution": "", "test": ""}
{"tast_id": "super-palindromes", "prompt": "# Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.\n# \n# Given two positive integers `left` and `right` represented as strings, return the number of super-palindromes integers in the inclusive range `[left, right]`.\n# \n# \n# Example 1:\n# Input: left = \"4\", right = \"1000\"\n# Output: 4\n# Explanation: 4, 9, 121, and 484 are superpalindromes.\n# \n# Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.\n# \n# \n# Example 2:\n# Input: left = \"1\", right = \"2\"\n# Output: 1\n# \n# Constraints:\n# `1 <= left.length, right.length <= 18`\n# `left` and `right` consist of only digits.\n# \n# `left` and `right` cannot have leading zeros.\n# \n# `left` and `right` represent integers in the range `[1, 1018]`.\n# \n# `left` is less than or equal to `right`.\nclass Solution:\n def superpalindromesInRange(self, left: str, right: str) -> int:\n ", "entry_point": "superpalindromesInRange", "cannonical_solution": "", "test": ""}
{"tast_id": "cat-and-mouse", "prompt": "# A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.\n# \n# The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph.\n# \n# The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`.\n# \n# During each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in `graph[1]`.\n# \n# Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)\n# Then, the game can end in three ways:\n# If ever the Cat occupies the same node as the Mouse, the Cat wins.\n# \n# If ever the Mouse reaches the Hole, the Mouse wins.\n# \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# \n# Given a `graph`, and assuming both players play optimally, return\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# \n# Example 1:\n# Input: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]\n# Output: 0\n# \n# Example 2:\n# Input: graph = [[1,3],[0],[3],[0,2]]\n# Output: 1\n# \n# Constraints:\n# `3 <= graph.length <= 50`\n# `1 <= graph[i].length < graph.length`\n# `0 <= graph[i][j] < graph.length`\n# `graph[i][j] != i`\n# `graph[i]` is unique.\n# \n# The mouse and the cat can always move.\nclass Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n ", "entry_point": "catMouseGame", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-music-playlists", "prompt": "# Your music player contains `N` different songs and she wants to listen to `L` (not necessarily different) songs during your trip. You create a playlist so that:\n# Every song is played at least once\n# A song can only be played again only if `K` other songs have been played\n# Return the number of possible playlists. As the answer can be very large, return it modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: N = 3, L = 3, K = 1\n# Output: 6\n# Explanation: There are 6 possible playlists. [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1].\n# \n# \n# Example 2:\n# Input: N = 2, L = 3, K = 0\n# Output: 6\n# Explanation: There are 6 possible playlists. [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], [1, 2, 2]\n# \n# Example 3:\n# Input: N = 2, L = 3, K = 1\n# Output: 2\n# Explanation: There are 2 possible playlists. [1, 2, 1], [2, 1, 2]\n# Note:\n# `0 <= K < N <= L <= 100`\nclass Solution:\n def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:\n ", "entry_point": "numMusicPlaylists", "cannonical_solution": "", "test": ""}
{"tast_id": "minimize-malware-spread", "prompt": "# You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.\n# \n# Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.\n# \n# Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from `initial`.\n# \n# Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with the smallest index.\n# \n# Note that if a node was removed from the `initial` list of infected nodes, it might still be infected later due to the malware spread.\n# \n# \n# Example 1:\n# Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\n# Output: 0\n# \n# Example 2:\n# Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]\n# Output: 0\n# \n# Example 3:\n# Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]\n# Output: 1\n# \n# Constraints:\n# `n == graph.length`\n# `n == graph[i].length`\n# `2 <= n <= 300`\n# `graph[i][j]` is `0` or `1`.\n# \n# `graph[i][j] == graph[j][i]`\n# `graph[i][i] == 1`\n# `1 <= initial.length <= n`\n# `0 <= initial[i] <= n - 1`\n# All the integers in `initial` are unique.\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n ", "entry_point": "minMalwareSpread", "cannonical_solution": "", "test": ""}
{"tast_id": "three-equal-parts", "prompt": "# You are given an array `arr` which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value.\n# \n# If it is possible, return any `[i, j]` with `i + 1 < j`, such that:\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# \n# All three parts have equal binary values.\n# \n# If it is not possible, return `[-1, -1]`.\n# \n# Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros are allowed, so `[0,1,1]` and `[1,1]` represent the same value.\n# \n# \n# Example 1:\n# Input: arr = [1,0,1,0,1]\n# Output: [0,3]\n# \n# Example 2:\n# Input: arr = [1,1,0,1,1]\n# Output: [-1,-1]\n# \n# Example 3:\n# Input: arr = [1,1,0,0,1]\n# Output: [0,2]\n# \n# Constraints:\n# `3 <= arr.length <= 3 * 104`\n# `arr[i]` is `0` or `1`\nclass Solution:\n def threeEqualParts(self, arr: List[int]) -> List[int]:\n ", "entry_point": "threeEqualParts", "cannonical_solution": "", "test": ""}
{"tast_id": "minimize-malware-spread-ii", "prompt": "# You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.\n# \n# Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.\n# \n# Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops.\n# \n# We will remove exactly one node from `initial`, completely removing it and any connections from this node to any other node.\n# \n# Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with the smallest index.\n# \n# \n# Example 1:\n# Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\n# Output: 0\n# \n# Example 2:\n# Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]\n# Output: 1\n# \n# Example 3:\n# Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]\n# Output: 1\n# \n# Constraints:\n# `n == graph.length`\n# `n == graph[i].length`\n# `2 <= n <= 300`\n# `graph[i][j]` is `0` or `1`.\n# \n# `graph[i][j] == graph[j][i]`\n# `graph[i][i] == 1`\n# `1 <= initial.length < n`\n# `0 <= initial[i] <= n - 1`\n# All the integers in `initial` are unique.\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n ", "entry_point": "minMalwareSpread", "cannonical_solution": "", "test": ""}
{"tast_id": "stamping-the-sequence", "prompt": "# You want to form a `target` string of lowercase letters.\n# \n# At the beginning, your sequence is `target.length` `'?'` marks. You also have a `stamp` of lowercase letters.\n# \n# On each turn, you may place the stamp over the sequence, and replace every letter in the sequence with the corresponding letter from the stamp. You can make up to `10 * target.length` turns.\n# \n# For example, if the initial sequence is \"?????\", and your stamp is `\"abc\"`, then you may make \"abc??\", \"?abc?\", \"??abc\" in the first turn. (Note that the stamp must be fully contained in the boundaries of the sequence in order to stamp.)\n# If the sequence is possible to stamp, then return an array of the index of the left-most letter being stamped at each turn. If the sequence is not possible to stamp, return an empty array.\n# \n# For example, if the sequence is \"ababc\", and the stamp is `\"abc\"`, then we could return the answer `[0, 2]`, corresponding to the moves \"?????\" -> \"abc??\" -> \"ababc\".\n# \n# Also, if the sequence is possible to stamp, it is guaranteed it is possible to stamp within `10 * target.length` moves. Any answers specifying more than this number of moves will not be accepted.\n# \n# \n# Example 1:\n# Input: stamp = \"abc\", target = \"ababc\"\n# Output: [0,2]\n# ([1,0,2] would also be accepted as an answer, as well as some other answers.)\n# \n# Example 2:\n# Input: stamp = \"abca\", target = \"aabcaca\"\n# Output: [3,0,1]\n# Note:\n# `1 <= stamp.length <= target.length <= 1000`\n# `stamp` and `target` only contain lowercase letters.\nclass Solution:\n def movesToStamp(self, stamp: str, target: str) -> List[int]:\n ", "entry_point": "movesToStamp", "cannonical_solution": "", "test": ""}
{"tast_id": "distinct-subsequences-ii", "prompt": "# Given a string `S`, count the number of distinct, non-empty subsequences of `S` .\n# \n# Since the result may be large, return the answer modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: \"abc\"\n# Output: 7\n# Explanation: The 7 distinct subsequences are \"a\", \"b\", \"c\", \"ab\", \"ac\", \"bc\", and \"abc\".\n# \n# \n# Example 2:\n# Input: \"aba\"\n# Output: 6\n# Explanation: The 6 distinct subsequences are \"a\", \"b\", \"ab\", \"ba\", \"aa\" and \"aba\".\n# \n# \n# Example 3:\n# Input: \"aaa\"\n# Output: 3\n# Explanation: The 3 distinct subsequences are \"a\", \"aa\" and \"aaa\".\n# \n# Note:\n# `S` contains only lowercase letters.\n# \n# `1 <= S.length <= 2000`\nclass Solution:\n def distinctSubseqII(self, s: str) -> int:\n ", "entry_point": "distinctSubseqII", "cannonical_solution": "", "test": ""}
{"tast_id": "find-the-shortest-superstring", "prompt": "# Given an array of strings `words`, return the smallest string that contains each string in `words` as a substring. If there are multiple valid strings of the smallest length, return any of them.\n# \n# You may assume that no string in `words` is a substring of another string in `words`.\n# \n# \n# Example 1:\n# Input: words = [\"alex\",\"loves\",\"leetcode\"]\n# Output: \"alexlovesleetcode\"\n# Explanation: All permutations of \"alex\",\"loves\",\"leetcode\" would also be accepted.\n# \n# \n# Example 2:\n# Input: words = [\"catg\",\"ctaagt\",\"gcta\",\"ttca\",\"atgcatc\"]\n# Output: \"gctaagttcatgcatc\"\n# \n# Constraints:\n# `1 <= words.length <= 12`\n# `1 <= words[i].length <= 20`\n# `words[i]` consists of lowercase English letters.\n# \n# All the strings of `words` are unique.\nclass Solution:\n def shortestSuperstring(self, words: List[str]) -> str:\n ", "entry_point": "shortestSuperstring", "cannonical_solution": "", "test": ""}
{"tast_id": "largest-component-size-by-common-factor", "prompt": "# Given a non-empty array of unique positive integers `A`, consider the following graph:\n# There are `A.length` nodes, labelled `A[0]` to `A[A.length - 1];`\n# There is an edge between `A[i]` and `A[j]` if and only if `A[i]` and `A[j]` share a common factor greater than 1.\n# \n# Return the size of the largest connected component in the graph.\n# \n# \n# Example 1:\n# Input: [4,6,15,35]\n# Output: 4\n# \n# Example 2:\n# Input: [20,50,9,63]\n# Output: 2\n# \n# Example 3:\n# Input: [2,3,6,7,4,12,21,39]\n# Output: 8\n# Note:\n# `1 <= A.length <= 20000`\n# `1 <= A[i] <= 100000`\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n ", "entry_point": "largestComponentSize", "cannonical_solution": "", "test": ""}
{"tast_id": "tallest-billboard", "prompt": "# You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.\n# \n# You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`.\n# \n# Return the largest possible height of your billboard installation. If you cannot support the billboard, return `0`.\n# \n# \n# Example 1:\n# Input: rods = [1,2,3,6]\n# Output: 6\n# Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.\n# \n# \n# Example 2:\n# Input: rods = [1,2,3,4,5,6]\n# Output: 10\n# Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.\n# \n# \n# Example 3:\n# Input: rods = [1,2]\n# Output: 0\n# Explanation: The billboard cannot be supported, so we return 0.\n# \n# \n# Constraints:\n# `1 <= rods.length <= 20`\n# `1 <= rods[i] <= 1000`\n# `sum(rods[i]) <= 5000`\nclass Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n ", "entry_point": "tallestBillboard", "cannonical_solution": "", "test": ""}
{"tast_id": "delete-columns-to-make-sorted-iii", "prompt": "# You are given an array of `n` strings `strs`, all of the same length.\n# \n# We may choose any deletion indices, and we delete all the characters in those indices for each string.\n# \n# For example, if we have `strs = [\"abcdef\",\"uvwxyz\"]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[\"bef\", \"vyz\"]`.\n# \n# Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has every string (row) in lexicographic order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return the minimum possible value of `answer.length`.\n# \n# \n# Example 1:\n# Input: strs = [\"babca\",\"bbazb\"]\n# Output: 3\n# Explanation: After deleting columns 0, 1, and 4, the final array is strs = [\"bc\", \"az\"].\n# \n# Both these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]).\n# \n# Note that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order.\n# \n# \n# Example 2:\n# Input: strs = [\"edcba\"]\n# Output: 4\n# Explanation: If we delete less than 4 columns, the only row will not be lexicographically sorted.\n# \n# \n# Example 3:\n# Input: strs = [\"ghi\",\"def\",\"abc\"]\n# Output: 0\n# Explanation: All rows are already lexicographically sorted.\n# \n# \n# Constraints:\n# `n == strs.length`\n# `1 <= n <= 100`\n# `1 <= strs[i].length <= 100`\n# `strs[i]` consists of lowercase English letters.\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n ", "entry_point": "minDeletionSize", "cannonical_solution": "", "test": ""}
{"tast_id": "least-operators-to-express-number", "prompt": "# Given a single positive integer `x`, we will write an expression of the form `x (op1) x (op2) x (op3) x ...` where each operator `op1`, `op2`, etc. is either addition, subtraction, multiplication, or division (`+`, `-`, `*`, or `/)`. For example, with `x = 3`, we might write `3 * 3 / 3 + 3 - 3` which is a value of 3.\n# \n# When writing such an expression, we adhere to the following conventions:\n# The division operator (`/`) returns rational numbers.\n# \n# There are no parentheses placed anywhere.\n# \n# We use the usual order of operations: multiplication and division happen before addition and subtraction.\n# \n# It is not allowed to use the unary negation operator (`-`). For example, \"`x - x`\" is a valid expression as it only uses subtraction, but \"`-x + x`\" is not because it uses negation.\n# \n# We would like to write an expression with the least number of operators such that the expression equals the given `target`. Return the least number of operators used.\n# \n# \n# Example 1:\n# Input: x = 3, target = 19\n# Output: 5\n# Explanation: 3 * 3 + 3 * 3 + 3 / 3.\n# \n# The expression contains 5 operations.\n# \n# \n# Example 2:\n# Input: x = 5, target = 501\n# Output: 8\n# Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.\n# \n# The expression contains 8 operations.\n# \n# \n# Example 3:\n# Input: x = 100, target = 100000000\n# Output: 3\n# Explanation: 100 * 100 * 100 * 100.\n# \n# The expression contains 3 operations.\n# \n# \n# Constraints:\n# `2 <= x <= 100`\n# `1 <= target <= 2 * 108`\nclass Solution:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n ", "entry_point": "leastOpsExpressTarget", "cannonical_solution": "", "test": ""}
{"tast_id": "equal-rational-numbers", "prompt": "# Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.\n# \n# A rational number can be represented using up to three parts: `<IntegerPart>`, `<NonRepeatingPart>`, and a `<RepeatingPart>`. The number will be represented in one of the following three ways:\n# `<IntegerPart>`\n# \t\n# For example, `12`, `0`, and `123`.\n# \n# `<IntegerPart><.><NonRepeatingPart>`\n# \t\n# For example, `0.5`, `1.`, `2.12`, and `123.0001`.\n# \n# `<IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)>`\n# \t\n# For example, `0.1(6)`, `1.(9)`, `123.00(1212)`.\n# \n# The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:\n# `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`.\n# \n# \n# Example 1:\n# Input: s = \"0.(52)\", t = \"0.5(25)\"\n# Output: true\n# Explanation: Because \"0.(52)\" represents 0.52525252..., and \"0.5(25)\" represents 0.52525252525..... , the strings represent the same number.\n# \n# \n# Example 2:\n# Input: s = \"0.1666(6)\", t = \"0.166(66)\"\n# Output: true\n# \n# Example 3:\n# Input: s = \"0.9(9)\", t = \"1.\"\n# Output: true\n# Explanation: \"0.9(9)\" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.]\n# \"1.\" represents the number 1, which is formed correctly: (IntegerPart) = \"1\" and (NonRepeatingPart) = \"\".\n# \n# \n# Constraints:\n# Each part consists only of digits.\n# \n# The `<IntegerPart>` does not have leading zeros (except for the zero itself).\n# \n# `1 <= <IntegerPart>.length <= 4`\n# `0 <= <NonRepeatingPart>.length <= 4`\n# `1 <= <RepeatingPart>.length <= 4`\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n ", "entry_point": "isRationalEqual", "cannonical_solution": "", "test": ""}
{"tast_id": "odd-even-jump", "prompt": "# You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices.\n# \n# You may jump forward from index `i` to index `j` (with `i < j`) in the following way:\n# During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index `j` such that `arr[i] <= arr[j]` and `arr[j]` is the smallest possible value. If there are multiple such indices `j`, you can only jump to the smallest such index `j`.\n# \n# During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index `j` such that `arr[i] >= arr[j]` and `arr[j]` is the largest possible value. If there are multiple such indices `j`, you can only jump to the smallest such index `j`.\n# \n# It may be the case that for some index `i`, there are no legal jumps.\n# \n# A starting index is good if, starting from that index, you can reach the end of the array (index `arr.length - 1`) by jumping some number of times (possibly 0 or more than once).\n# \n# Return the number of good starting indices.\n# \n# \n# Example 1:\n# Input: arr = [10,13,12,14,15]\n# Output: 2\n# Explanation: \n# From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.\n# \n# From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.\n# \n# From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.\n# \n# From starting index i = 4, we have reached the end already.\n# \n# In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of\n# jumps.\n# \n# \n# Example 2:\n# Input: arr = [2,3,1,1,4]\n# Output: 3\n# Explanation: \n# From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:\n# During our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].\n# \n# During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3\n# During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].\n# \n# We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.\n# \n# In a similar manner, we can deduce that:\n# From starting index i = 1, we jump to i = 4, so we reach the end.\n# \n# From starting index i = 2, we jump to i = 3, and then we can't jump anymore.\n# \n# From starting index i = 3, we jump to i = 4, so we reach the end.\n# \n# From starting index i = 4, we are already at the end.\n# \n# In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some\n# number of jumps.\n# \n# \n# Example 3:\n# Input: arr = [5,1,3,4,2]\n# Output: 3\n# Explanation: We can reach the end from starting indices 1, 2, and 4.\n# \n# \n# Constraints:\n# `1 <= arr.length <= 2 * 104`\n# `0 <= arr[i] < 105`\nclass Solution:\n def oddEvenJumps(self, arr: List[int]) -> int:\n ", "entry_point": "oddEvenJumps", "cannonical_solution": "", "test": ""}
{"tast_id": "unique-paths-iii", "prompt": "# On a 2-dimensional `grid`, there are 4 types of squares:\n# `1` represents the starting square. There is exactly one starting square.\n# \n# `2` represents the ending square. There is exactly one ending square.\n# \n# `0` represents empty squares we can walk over.\n# \n# `-1` represents obstacles that we cannot walk over.\n# \n# Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.\n# \n# \n# Example 1:\n# Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]\n# Output: 2\n# Explanation: We have the following two paths: \n# 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n# 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)\n# \n# Example 2:\n# Input: [[1,0,0,0],[0,0,0,0],[0,0,0,2]]\n# Output: 4\n# Explanation: We have the following four paths: \n# 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n# 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n# 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n# 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)\n# \n# Example 3:\n# Input: [[0,1],[2,0]]\n# Output: 0\n# Explanation: \n# There is no path that walks over every empty square exactly once.\n# \n# Note that the starting and ending square can be anywhere in the grid.\n# \n# Note:\n# `1 <= grid.length * grid[0].length <= 20`\nclass Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n ", "entry_point": "uniquePathsIII", "cannonical_solution": "", "test": ""}
{"tast_id": "triples-with-bitwise-and-equal-to-zero", "prompt": "# Given an array of integers `A`, find the number of triples of indices (i, j, k) such that:\n# `0 <= i < A.length`\n# `0 <= j < A.length`\n# `0 <= k < A.length`\n# `A[i] & A[j] & A[k] == 0`, where `&` represents the bitwise-AND operator.\n# \n# \n# Example 1:\n# Input: [2,1,3]\n# Output: 12\n# Explanation: We could choose the following i, j, k triples:\n# (i=0, j=0, k=1) : 2 & 2 & 1\n# (i=0, j=1, k=0) : 2 & 1 & 2\n# (i=0, j=1, k=1) : 2 & 1 & 1\n# (i=0, j=1, k=2) : 2 & 1 & 3\n# (i=0, j=2, k=1) : 2 & 3 & 1\n# (i=1, j=0, k=0) : 1 & 2 & 2\n# (i=1, j=0, k=1) : 1 & 2 & 1\n# (i=1, j=0, k=2) : 1 & 2 & 3\n# (i=1, j=1, k=0) : 1 & 1 & 2\n# (i=1, j=2, k=0) : 1 & 3 & 2\n# (i=2, j=0, k=1) : 3 & 2 & 1\n# (i=2, j=1, k=0) : 3 & 1 & 2\n# Note:\n# `1 <= A.length <= 1000`\n# `0 <= A[i] < 2^16`\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n ", "entry_point": "countTriplets", "cannonical_solution": "", "test": ""}
{"tast_id": "subarrays-with-k-different-integers", "prompt": "# Given an array `A` of positive integers, call a (contiguous, not necessarily distinct) subarray of `A` good if the number of different integers in that subarray is exactly `K`.\n# \n# (For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`.)\n# Return the number of good subarrays of `A`.\n# \n# \n# Example 1:\n# Input: A = [1,2,1,2,3], K = 2\n# Output: 7\n# Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].\n# \n# \n# Example 2:\n# Input: A = [1,2,1,3,4], K = 3\n# Output: 3\n# Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].\n# \n# Note:\n# `1 <= A.length <= 20000`\n# `1 <= A[i] <= A.length`\n# `1 <= K <= A.length`\nclass Solution:\n def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n ", "entry_point": "subarraysWithKDistinct", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-number-of-k-consecutive-bit-flips", "prompt": "# In an array `A` containing only 0s and 1s, a `K`-bit flip consists of choosing a (contiguous) subarray of length `K` and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.\n# \n# Return the minimum number of `K`-bit flips required so that there is no 0 in the array. If it is not possible, return `-1`.\n# \n# \n# Example 1:\n# Input: A = [0,1,0], K = 1\n# Output: 2\n# Explanation: Flip A[0], then flip A[2].\n# \n# \n# Example 2:\n# Input: A = [1,1,0], K = 2\n# Output: -1\n# Explanation: No matter how we flip subarrays of size 2, we can't make the array become [1,1,1].\n# \n# \n# Example 3:\n# Input: A = [0,0,0,1,0,1,1,0], K = 3\n# Output: 3\n# Explanation:\n# Flip A[0],A[1],A[2]: A becomes [1,1,1,1,0,1,1,0]\n# Flip A[4],A[5],A[6]: A becomes [1,1,1,1,1,0,0,0]\n# Flip A[5],A[6],A[7]: A becomes [1,1,1,1,1,1,1,1]\n# Note:\n# `1 <= A.length <= 30000`\n# `1 <= K <= A.length`\nclass Solution:\n def minKBitFlips(self, nums: List[int], k: int) -> int:\n ", "entry_point": "minKBitFlips", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-squareful-arrays", "prompt": "# Given an array `A` of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.\n# \n# Return the number of permutations of A that are squareful. Two permutations `A1` and `A2` differ if and only if there is some index `i` such that `A1[i] != A2[i]`.\n# \n# \n# Example 1:\n# Input: [1,17,8]\n# Output: 2\n# Explanation: \n# [1,8,17] and [17,8,1] are the valid permutations.\n# \n# \n# Example 2:\n# Input: [2,2,2]\n# Output: 1\n# Note:\n# `1 <= A.length <= 12`\n# `0 <= A[i] <= 1e9`\nclass Solution:\n def numSquarefulPerms(self, nums: List[int]) -> int:\n ", "entry_point": "numSquarefulPerms", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-cost-to-merge-stones", "prompt": "# There are `N` piles of stones arranged in a row. The `i`-th pile has `stones[i]` stones.\n# \n# A move consists of merging exactly `K` consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these `K` piles.\n# \n# Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return `-1`.\n# \n# \n# Example 1:\n# Input: stones = [3,2,4,1], K = 2\n# Output: 20\n# Explanation: \n# We start with [3, 2, 4, 1].\n# \n# We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].\n# \n# We merge [4, 1] for a cost of 5, and we are left with [5, 5].\n# \n# We merge [5, 5] for a cost of 10, and we are left with [10].\n# \n# The total cost was 20, and this is the minimum possible.\n# \n# \n# Example 2:\n# Input: stones = [3,2,4,1], K = 3\n# Output: -1\n# Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.\n# \n# \n# Example 3:\n# Input: stones = [3,5,1,2,6], K = 3\n# Output: 25\n# Explanation: \n# We start with [3, 5, 1, 2, 6].\n# \n# We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].\n# \n# We merge [3, 8, 6] for a cost of 17, and we are left with [17].\n# \n# The total cost was 25, and this is the minimum possible.\n# \n# Note:\n# `1 <= stones.length <= 30`\n# `2 <= K <= 30`\n# `1 <= stones[i] <= 100`\nclass Solution:\n def mergeStones(self, stones: List[int], k: int) -> int:\n ", "entry_point": "mergeStones", "cannonical_solution": "", "test": ""}
{"tast_id": "grid-illumination", "prompt": "# You are given a `grid` of size `N x N`, and each cell of this grid has a lamp that is initially turned off.\n# \n# You are also given an array of lamp positions `lamps`, where `lamps[i] = [rowi, coli]` indicates that the lamp at `grid[rowi][coli]` is turned on. When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal.\n# \n# Finally, you are given a query array `queries`, where `queries[i] = [rowi, coli]`. For the `ith` query, determine whether `grid[rowi][coli]` is illuminated or not. After answering the `ith` query, turn off the lamp at `grid[rowi][coli]` and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with `grid[rowi][coli]`.\n# \n# Return an array of integers `ans`, where `ans[i]` should be `1` if the lamp in the `ith` query was illuminated, or `0` if the lamp was not.\n# \n# \n# Example 1:\n# Input: N = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]\n# Output: [1,0]\n# Explanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].\n# \n# The 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.\n# \n# The 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.\n# \n# \n# Example 2:\n# Input: N = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]\n# Output: [1,1]\n# \n# Example 3:\n# Input: N = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]\n# Output: [1,1,0]\n# \n# Constraints:\n# `1 <= N <= 109`\n# `0 <= lamps.length <= 20000`\n# `lamps[i].length == 2`\n# `0 <= lamps[i][j] < N`\n# `0 <= queries.length <= 20000`\n# `queries[i].length == 2`\n# `0 <= queries[i][j] < N`\nclass Solution:\n def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:\n ", "entry_point": "gridIllumination", "cannonical_solution": "", "test": ""}
{"tast_id": "numbers-with-repeated-digits", "prompt": "# Given a positive integer `N`, return the number of positive integers less than or equal to `N` that have at least 1 repeated digit.\n# \n# \n# Example 1:\n# Input: 20\n# Output: 1\n# Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.\n# \n# \n# Example 2:\n# Input: 100\n# Output: 10\n# Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.\n# \n# \n# Example 3:\n# Input: 1000\n# Output: 262\n# Note:\n# `1 <= N <= 10^9`\nclass Solution:\n def numDupDigitsAtMostN(self, n: int) -> int:\n ", "entry_point": "numDupDigitsAtMostN", "cannonical_solution": "", "test": ""}
{"tast_id": "stream-of-characters", "prompt": "# Implement the `StreamChecker` class as follows:\n# `StreamChecker(words)`: Constructor, init the data structure with the given words.\n# \n# `query(letter)`: returns true if and only if for some `k >= 1`, the last `k` characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list.\n# \n# \n# Example:\n# StreamChecker streamChecker = new StreamChecker([\"cd\",\"f\",\"kl\"]); // init the dictionary.\n# \n# streamChecker.query('a'); // return false\n# streamChecker.query('b'); // return false\n# streamChecker.query('c'); // return false\n# streamChecker.query('d'); // return true, because 'cd' is in the wordlist\n# streamChecker.query('e'); // return false\n# streamChecker.query('f'); // return true, because 'f' is in the wordlist\n# streamChecker.query('g'); // return false\n# streamChecker.query('h'); // return false\n# streamChecker.query('i'); // return false\n# streamChecker.query('j'); // return false\n# streamChecker.query('k'); // return false\n# streamChecker.query('l'); // return true, because 'kl' is in the wordlist\n# Note:\n# `1 <= words.length <= 2000`\n# `1 <= words[i].length <= 2000`\n# Words will only consist of lowercase English letters.\n# \n# Queries will only consist of lowercase English letters.\n# \n# The number of queries is at most 40000.\nclass StreamChecker:\n\n def __init__(self, words: List[str]):\n \n\n def query(self, letter: str) -> bool:\n \n\n\n# Your StreamChecker object will be instantiated and called as such:\n# obj = StreamChecker(words)\n# param_1 = obj.query(letter)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "escape-a-large-maze", "prompt": "# There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are `(x, y)`.\n# \n# We start at the `source = [sx, sy]` square and want to reach the `target = [tx, ty]` square. There is also an array of `blocked` squares, where each `blocked[i] = [xi, yi]` represents a blocked square with coordinates `(xi, yi)`.\n# \n# Each move, we can walk one square north, east, south, or west if the square is not in the array of `blocked` squares. We are also not allowed to walk outside of the grid.\n# \n# Return `true` if and only if it is possible to reach the `target` square from the `source` square through a sequence of valid moves.\n# \n# \n# Example 1:\n# Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]\n# Output: false\n# Explanation: The target square is inaccessible starting from the source square because we cannot move.\n# \n# We cannot move north or east because those squares are blocked.\n# \n# We cannot move south or west because we cannot go outside of the grid.\n# \n# \n# Example 2:\n# Input: blocked = [], source = [0,0], target = [999999,999999]\n# Output: true\n# Explanation: Because there are no blocked cells, it is possible to reach the target square.\n# \n# \n# Constraints:\n# `0 <= blocked.length <= 200`\n# `blocked[i].length == 2`\n# `0 <= xi, yi < 106`\n# `source.length == target.length == 2`\n# `0 <= sx, sy, tx, ty < 106`\n# `source != target`\n# It is guaranteed that `source` and `target` are not blocked.\nclass Solution:\n def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:\n ", "entry_point": "isEscapePossible", "cannonical_solution": "", "test": ""}
{"tast_id": "longest-duplicate-substring", "prompt": "# Given a string `s`, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.\n# \n# Return any duplicated substring that has the longest possible length. If `s` does not have a duplicated substring, the answer is `\"\"`.\n# \n# \n# Example 1:\n# Input: s = \"banana\"\n# Output: \"ana\"\n# \n# Example 2:\n# Input: s = \"abcd\"\n# Output: \"\"\n# \n# Constraints:\n# `2 <= s.length <= 3 * 104`\n# `s` consists of lowercase English letters.\nclass Solution:\n def longestDupSubstring(self, s: str) -> str:\n ", "entry_point": "longestDupSubstring", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-submatrices-that-sum-to-target", "prompt": "# Given a `matrix` and a `target`, return the number of non-empty submatrices that sum to target.\n# \n# A submatrix `x1, y1, x2, y2` is the set of all cells `matrix[x][y]` with `x1 <= x <= x2` and `y1 <= y <= y2`.\n# \n# Two submatrices `(x1, y1, x2, y2)` and `(x1', y1', x2', y2')` are different if they have some coordinate that is different: for example, if `x1 != x1'`.\n# \n# \n# Example 1:\n# Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0\n# Output: 4\n# Explanation: The four 1x1 submatrices that only contain 0.\n# \n# \n# Example 2:\n# Input: matrix = [[1,-1],[-1,1]], target = 0\n# Output: 5\n# Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.\n# \n# \n# Example 3:\n# Input: matrix = [[904]], target = 0\n# Output: 0\n# \n# Constraints:\n# `1 <= matrix.length <= 100`\n# `1 <= matrix[0].length <= 100`\n# `-1000 <= matrix[i] <= 1000`\n# `-10^8 <= target <= 10^8`\nclass Solution:\n def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n ", "entry_point": "numSubmatrixSumTarget", "cannonical_solution": "", "test": ""}
{"tast_id": "shortest-common-supersequence", "prompt": "# Given two strings `str1` and `str2`, return the shortest string that has both `str1` and `str2` as subsequences. If multiple answers exist, you may return any of them.\n# \n# (A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results in the string S.)\n# \n# Example 1:\n# Input: str1 = \"abac\", str2 = \"cab\"\n# Output: \"cabac\"\n# Explanation: \n# str1 = \"abac\" is a subsequence of \"cabac\" because we can delete the first \"c\".\n# \n# str2 = \"cab\" is a subsequence of \"cabac\" because we can delete the last \"ac\".\n# \n# The answer provided is the shortest such string that satisfies these properties.\n# \n# Note:\n# `1 <= str1.length, str2.length <= 1000`\n# `str1` and `str2` consist of lowercase English letters.\nclass Solution:\n def shortestCommonSupersequence(self, str1: str, str2: str) -> str:\n ", "entry_point": "shortestCommonSupersequence", "cannonical_solution": "", "test": ""}
{"tast_id": "brace-expansion-ii", "prompt": "# Under a grammar given below, strings can represent a set of lowercase words. Let's use `R(expr)` to denote the set of words the expression represents.\n# \n# Grammar can best be understood through simple examples:\n# Single letters represent a singleton set containing that word.\n# \n# \t\n# `R(\"a\") = {\"a\"}`\n# `R(\"w\") = {\"w\"}`\n# When we take a comma delimited list of 2 or more expressions, we take the union of possibilities.\n# \n# \t\n# `R(\"{a,b,c}\") = {\"a\",\"b\",\"c\"}`\n# `R(\"{{a,b},{b,c}}\") = {\"a\",\"b\",\"c\"}` (notice the final set only contains each word at most once)\n# When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression.\n# \n# \t\n# `R(\"{a,b}{c,d}\") = {\"ac\",\"ad\",\"bc\",\"bd\"}`\n# `R(\"a{b,c}{d,e}f{g,h}\") = {\"abdfg\", \"abdfh\", \"abefg\", \"abefh\", \"acdfg\", \"acdfh\", \"acefg\", \"acefh\"}`\n# Formally, the 3 rules for our grammar:\n# For every lowercase letter `x`, we have `R(x) = {x}`\n# For expressions `e_1, e_2, ... , e_k` with `k >= 2`, we have `R({e_1,e_2,...}) = R(e_1) \u222a R(e_2) \u222a ...`\n# For expressions `e_1` and `e_2`, we have `R(e_1 + e_2) = {a + b for (a, b) in R(e_1) \u00d7 R(e_2)}`, where + denotes concatenation, and \u00d7 denotes the cartesian product.\n# \n# Given an `expression` representing a set of words under the given grammar, return the sorted list of words that the expression represents.\n# \n# \n# Example 1:\n# Input: \"{a,b}{c,{d,e}}\"\n# Output: [\"ac\",\"ad\",\"ae\",\"bc\",\"bd\",\"be\"]\n# \n# Example 2:\n# Input: \"{{a,z},a{b,c},{ab,z}}\"\n# Output: [\"a\",\"ab\",\"ac\",\"z\"]\n# Explanation: Each distinct word is written only once in the final answer.\n# \n# \n# Constraints:\n# `1 <= expression.length <= 60`\n# `expression[i]` consists of `'{'`, `'}'`, `','`or lowercase English letters.\n# \n# The given `expression` represents a set of words based on the grammar given in the description.\nclass Solution:\n def braceExpansionII(self, expression: str) -> List[str]:\n ", "entry_point": "braceExpansionII", "cannonical_solution": "", "test": ""}
{"tast_id": "parsing-a-boolean-expression", "prompt": "# Return the result of evaluating a given boolean `expression`, represented as a string.\n# \n# An expression can either be:\n# `\"t\"`, evaluating to `True`;\n# `\"f\"`, evaluating to `False`;\n# `\"!(expr)\"`, evaluating to the logical NOT of the inner expression `expr`;\n# `\"&(expr1,expr2,...)\"`, evaluating to the logical AND of 2 or more inner expressions `expr1, expr2, ...`;\n# `\"|(expr1,expr2,...)\"`, evaluating to the logical OR of 2 or more inner expressions `expr1, expr2, ...`\n# \n# Example 1:\n# Input: expression = \"!(f)\"\n# Output: true\n# \n# Example 2:\n# Input: expression = \"|(f,t)\"\n# Output: true\n# \n# Example 3:\n# Input: expression = \"&(t,f)\"\n# Output: false\n# \n# Example 4:\n# Input: expression = \"|(&(t,f,t),!(t))\"\n# Output: false\n# \n# Constraints:\n# `1 <= expression.length <= 20000`\n# `expression[i]` consists of characters in `{'(', ')', '&', '|', '!', 't', 'f', ','}`.\n# \n# `expression` is a valid expression representing a boolean, as given in the description.\nclass Solution:\n def parseBoolExpr(self, expression: str) -> bool:\n ", "entry_point": "parseBoolExpr", "cannonical_solution": "", "test": ""}
{"tast_id": "smallest-sufficient-team", "prompt": "# In a project, you have a list of required skills `req_skills`, and a list of people. The `ith` person `people[i]` contains a list of skills that the person has.\n# \n# Consider a sufficient team: a set of people such that for every required skill in `req_skills`, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.\n# \n# For example, `team = [0, 1, 3]` represents the people with skills `people[0]`, `people[1]`, and `people[3]`.\n# \n# Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.\n# \n# It is guaranteed an answer exists.\n# \n# \n# Example 1:\n# Input: req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]\n# Output: [0,2]\n# \n# Example 2:\n# Input: req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]\n# Output: [1,2]\n# \n# Constraints:\n# `1 <= req_skills.length <= 16`\n# `1 <= req_skills[i].length <= 16`\n# `req_skills[i]` consists of lowercase English letters.\n# \n# All the strings of `req_skills` are unique.\n# \n# `1 <= people.length <= 60`\n# `0 <= people[i].length <= 16`\n# `1 <= people[i][j].length <= 16`\n# `people[i][j]` consists of lowercase English letters.\n# \n# All the strings of `people[i]` are unique.\n# \n# Every skill in `people[i]` is a skill in `req_skills`.\n# \n# It is guaranteed a sufficient team exists.\nclass Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n ", "entry_point": "smallestSufficientTeam", "cannonical_solution": "", "test": ""}
{"tast_id": "longest-chunked-palindrome-decomposition", "prompt": "# You are given a string `text`. You should split it to k substrings `(subtext1, subtext2, ..., subtextk)` such that:\n# `subtexti` is a non-empty string.\n# \n# The concatenation of all the substrings is equal to `text` (i.e., `subtext1 + subtext2 + ... + subtextk == text`).\n# \n# `subtexti == subtextk - i + 1` for all valid values of `i` (i.e., `1 <= i <= k`).\n# \n# Return the largest possible value of `k`.\n# \n# \n# Example 1:\n# Input: text = \"ghiabcdefhelloadamhelloabcdefghi\"\n# Output: 7\n# Explanation: We can split the string on \"(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)\".\n# \n# \n# Example 2:\n# Input: text = \"merchant\"\n# Output: 1\n# Explanation: We can split the string on \"(merchant)\".\n# \n# \n# Example 3:\n# Input: text = \"antaprezatepzapreanta\"\n# Output: 11\n# Explanation: We can split the string on \"(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)\".\n# \n# \n# Example 4:\n# Input: text = \"aaa\"\n# Output: 3\n# Explanation: We can split the string on \"(a)(a)(a)\".\n# \n# \n# Constraints:\n# `1 <= text.length <= 1000`\n# `text` consists only of lowercase English characters.\nclass Solution:\n def longestDecomposition(self, text: str) -> int:\n ", "entry_point": "longestDecomposition", "cannonical_solution": "", "test": ""}
{"tast_id": "online-majority-element-in-subarray", "prompt": "# Implementing the class `MajorityChecker`, which has the following API:\n# `MajorityChecker(int[] arr)` constructs an instance of MajorityChecker with the given array `arr`;\n# `int query(int left, int right, int threshold)` has arguments such that:\n# \t\n# `0 <= left <= right < arr.length` representing a subarray of `arr`;\n# `2 * threshold > right - left + 1`, ie. the threshold is always a strict majority of the length of the subarray\n# Each `query(...)` returns the element in `arr[left], arr[left+1], ..., arr[right]` that occurs at least `threshold` times, or `-1` if no such element exists.\n# \n# \n# Example:\n# MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);\n# majorityChecker.query(0,5,4); // returns 1\n# majorityChecker.query(0,3,3); // returns -1\n# majorityChecker.query(2,3,2); // returns 2\n# \n# Constraints:\n# `1 <= arr.length <= 20000`\n# `1 <= arr[i] <= 20000`\n# For each query, `0 <= left <= right < len(arr)`\n# For each query, `2 * threshold > right - left + 1`\n# The number of queries is at most `10000`\nclass MajorityChecker:\n\n def __init__(self, arr: List[int]):\n \n\n def query(self, left: int, right: int, threshold: int) -> int:\n \n\n\n# Your MajorityChecker object will be instantiated and called as such:\n# obj = MajorityChecker(arr)\n# param_1 = obj.query(left,right,threshold)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "last-substring-in-lexicographical-order", "prompt": "# Given a string `s`, return the last substring of `s` in lexicographical order.\n# \n# \n# Example 1:\n# Input: s = \"abab\"\n# Output: \"bab\"\n# Explanation: The substrings are [\"a\", \"ab\", \"aba\", \"abab\", \"b\", \"ba\", \"bab\"]. The lexicographically maximum substring is \"bab\".\n# \n# \n# Example 2:\n# Input: s = \"leetcode\"\n# Output: \"tcode\"\n# \n# Constraints:\n# `1 <= s.length <= 4 * 105`\n# `s` contains only lowercase English letters.\nclass Solution:\n def lastSubstring(self, s: str) -> str:\n ", "entry_point": "lastSubstring", "cannonical_solution": "", "test": ""}
{"tast_id": "dinner-plate-stacks", "prompt": "# You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum `capacity`.\n# \n# Implement the `DinnerPlates` class:\n# `DinnerPlates(int capacity)` Initializes the object with the maximum `capacity` of the stacks.\n# \n# `void push(int val)` Pushes the given positive integer `val` into the leftmost stack with size less than `capacity`.\n# \n# `int pop()` Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns `-1` if all stacks are empty.\n# \n# `int popAtStack(int index)` Returns the value at the top of the stack with the given `index` and removes it from that stack, and returns -1 if the stack with that given `index` is empty.\n# \n# \n# Example:\n# Input: \n# [\"DinnerPlates\",\"push\",\"push\",\"push\",\"push\",\"push\",\"popAtStack\",\"push\",\"push\",\"popAtStack\",\"popAtStack\",\"pop\",\"pop\",\"pop\",\"pop\",\"pop\"]\n# [[2],[1],[2],[3],[4],[5],[0],[20],[21],[0],[2],[],[],[],[],[]]\n# Output: \n# [null,null,null,null,null,null,2,null,null,20,21,5,4,3,1,-1]\n# Explanation: \n# DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2\n# D.push(1);\n# D.push(2);\n# D.push(3);\n# D.push(4);\n# D.push(5); // The stacks are now: 2 4\n# 1 3 5\n# ] ] ]\n# D.popAtStack(0); // Returns 2. The stacks are now: 4\n# 1 3 5\n# ] ] ]\n# D.push(20); // The stacks are now: 20 4\n# 1 3 5\n# ] ] ]\n# D.push(21); // The stacks are now: 20 4 21\n# 1 3 5\n# ] ] ]\n# D.popAtStack(0); // Returns 20. The stacks are now: 4 21\n# 1 3 5\n# ] ] ]\n# D.popAtStack(2); // Returns 21. The stacks are now: 4\n# 1 3 5\n# ] ] ] \n# D.pop() // Returns 5. The stacks are now: 4\n# 1 3 \n# ] ] \n# D.pop() // Returns 4. The stacks are now: 1 3 \n# ] ] \n# D.pop() // Returns 3. The stacks are now: 1 \n# ] \n# D.pop() // Returns 1. There are no stacks.\n# \n# D.pop() // Returns -1. There are still no stacks.\n# \n# \n# Constraints:\n# `1 <= capacity <= 20000`\n# `1 <= val <= 20000`\n# `0 <= index <= 100000`\n# At most `200000` calls will be made to `push`, `pop`, and `popAtStack`.\nclass DinnerPlates:\n\n def __init__(self, capacity: int):\n \n\n def push(self, val: int) -> None:\n \n\n def pop(self) -> int:\n \n\n def popAtStack(self, index: int) -> int:\n \n\n\n# Your DinnerPlates object will be instantiated and called as such:\n# obj = DinnerPlates(capacity)\n# obj.push(val)\n# param_2 = obj.pop()\n# param_3 = obj.popAtStack(index)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-valid-words-for-each-puzzle", "prompt": "# With respect to a given `puzzle` string, a `word` is valid if both the following conditions are satisfied:\n# `word` contains the first letter of `puzzle`.\n# \n# For each letter in `word`, that letter is in `puzzle`.\n# \n# \tFor example, if the puzzle is \"abcdefg\", then valid words are \"faced\", \"cabbage\", and \"baggage\"; while invalid words are \"beefed\" (doesn't include \"a\") and \"based\" (includes \"s\" which isn't in the puzzle).\n# \n# Return an array `answer`, where `answer[i]` is the number of words in the given word list `words` that are valid with respect to the puzzle `puzzles[i]`.\n# \n# \n# Example :\n# Input: \n# words = [\"aaaa\",\"asas\",\"able\",\"ability\",\"actt\",\"actor\",\"access\"], \n# puzzles = [\"aboveyz\",\"abrodyz\",\"abslute\",\"absoryz\",\"actresz\",\"gaswxyz\"]\n# Output: [1,1,3,2,4,0]\n# Explanation:\n# 1 valid word for \"aboveyz\" : \"aaaa\" \n# 1 valid word for \"abrodyz\" : \"aaaa\"\n# 3 valid words for \"abslute\" : \"aaaa\", \"asas\", \"able\"\n# 2 valid words for \"absoryz\" : \"aaaa\", \"asas\"\n# 4 valid words for \"actresz\" : \"aaaa\", \"asas\", \"actt\", \"access\"\n# There're no valid words for \"gaswxyz\" cause none of the words in the list contains letter 'g'.\n# \n# \n# Constraints:\n# `1 <= words.length <= 10^5`\n# `4 <= words[i].length <= 50`\n# `1 <= puzzles.length <= 10^4`\n# `puzzles[i].length == 7`\n# `words[i][j]`, `puzzles[i][j]` are English lowercase letters.\n# \n# Each `puzzles[i] `doesn't contain repeated characters.\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n ", "entry_point": "findNumOfValidWords", "cannonical_solution": "", "test": ""}
{"tast_id": "make-array-strictly-increasing", "prompt": "# Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.\n# \n# In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.\n# \n# If there is no way to make `arr1` strictly increasing, return `-1`.\n# \n# \n# Example 1:\n# Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]\n# Output: 1\n# Explanation: Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.\n# \n# \n# Example 2:\n# Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1]\n# Output: 2\n# Explanation: Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.\n# \n# \n# Example 3:\n# Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]\n# Output: -1\n# Explanation: You can't make `arr1` strictly increasing.\n# \n# \n# Constraints:\n# `1 <= arr1.length, arr2.length <= 2000`\n# `0 <= arr1[i], arr2[i] <= 10^9`\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n ", "entry_point": "makeArrayIncreasing", "cannonical_solution": "", "test": ""}
{"tast_id": "critical-connections-in-a-network", "prompt": "# There are `n` servers numbered from `0` to `n-1` connected by undirected server-to-server `connections` forming a network where `connections[i] = [a, b]` represents a connection between servers `a` and `b`. Any server can reach any other server directly or indirectly through the network.\n# \n# A critical connection is a connection that, if removed, will make some server unable to reach some other server.\n# \n# Return all critical connections in the network in any order.\n# \n# \n# Example 1:\n# Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]\n# Output: [[1,3]]\n# Explanation: [[3,1]] is also accepted.\n# \n# \n# Constraints:\n# `1 <= n <= 10^5`\n# `n-1 <= connections.length <= 10^5`\n# `connections[i][0] != connections[i][1]`\n# There are no repeated connections.\nclass Solution:\n def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n ", "entry_point": "criticalConnections", "cannonical_solution": "", "test": ""}
{"tast_id": "sort-items-by-groups-respecting-dependencies", "prompt": "# There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`-th item belongs to and it's equal to `-1` if the `i`-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.\n# \n# Return a sorted list of the items such that:\n# The items that belong to the same group are next to each other in the sorted list.\n# \n# There are some relations between these items where `beforeItems[i]` is a list containing all the items that should come before the `i`-th item in the sorted array (to the left of the `i`-th item).\n# \n# Return any solution if there is more than one solution and return an empty list if there is no solution.\n# \n# \n# Example 1:\n# Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]\n# Output: [6,3,4,1,5,2,0,7]\n# \n# Example 2:\n# Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]\n# Output: []\n# Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.\n# \n# \n# Constraints:\n# `1 <= m <= n <= 3 * 104`\n# `group.length == beforeItems.length == n`\n# `-1 <= group[i] <= m - 1`\n# `0 <= beforeItems[i].length <= n - 1`\n# `0 <= beforeItems[i][j] <= n - 1`\n# `i != beforeItems[i][j]`\n# `beforeItems[i] `does not contain duplicates elements.\nclass Solution:\n def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:\n ", "entry_point": "sortItems", "cannonical_solution": "", "test": ""}
{"tast_id": "design-skiplist", "prompt": "# Design a Skiplist without using any built-in libraries.\n# \n# A Skiplist is a data structure that takes O(log(n)) time to `add`, `erase` and `search`. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists are just simple linked lists.\n# \n# For example: we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way:\n# Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons\n# You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, `add` , `erase` and `search `can be faster than O(n). It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n).\n# \n# To be specific, your design should include these functions:\n# `bool search(int target)` : Return whether the `target` exists in the Skiplist or not.\n# \n# `void add(int num)`: Insert a value into the SkipList. \n# `bool erase(int num)`: Remove a value in the Skiplist. If `num` does not exist in the Skiplist, do nothing and return false. If there exists multiple `num` values, removing any one of them is fine.\n# \n# See more about Skiplist : https://en.wikipedia.org/wiki/Skip_list\n# Note that duplicates may exist in the Skiplist, your code needs to handle this situation.\n# \n# \n# Example:\n# Skiplist skiplist = new Skiplist();\n# skiplist.add(1);\n# skiplist.add(2);\n# skiplist.add(3);\n# skiplist.search(0); // return false.\n# \n# skiplist.add(4);\n# skiplist.search(1); // return true.\n# \n# skiplist.erase(0); // return false, 0 is not in skiplist.\n# \n# skiplist.erase(1); // return true.\n# \n# skiplist.search(1); // return false, 1 has already been erased.\n# \n# \n# Constraints:\n# `0 <= num, target <= 20000`\n# At most `50000` calls will be made to `search`, `add`, and `erase`.\nclass Skiplist:\n\n def __init__(self):\n \n\n def search(self, target: int) -> bool:\n \n\n def add(self, num: int) -> None:\n \n\n def erase(self, num: int) -> bool:\n \n\n\n# Your Skiplist object will be instantiated and called as such:\n# obj = Skiplist()\n# param_1 = obj.search(target)\n# obj.add(num)\n# param_3 = obj.erase(num)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-moves-to-reach-target-with-rotations", "prompt": "# In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.\n# \n# In one move the snake can:\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# \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# \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# \n# Return the minimum number of moves to reach the target.\n# \n# If there is no way to reach the target, return `-1`.\n# \n# \n# Example 1:\n# Input: grid = [[0,0,0,0,0,1],\n# [1,1,0,0,1,0],\n# [0,0,0,0,1,1],\n# [0,0,1,0,1,0],\n# [0,1,1,0,0,0],\n# [0,1,1,0,0,0]]\n# Output: 11\n# Explanation:\n# One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].\n# \n# \n# Example 2:\n# Input: grid = [[0,0,1,1,1,1],\n# [0,0,0,0,1,1],\n# [1,1,0,0,0,1],\n# [1,1,1,0,0,1],\n# [1,1,1,0,0,1],\n# [1,1,1,0,0,0]]\n# Output: 9\n# \n# Constraints:\n# `2 <= n <= 100`\n# `0 <= grid[i][j] <= 1`\n# It is guaranteed that the snake starts at empty cells.\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n ", "entry_point": "minimumMoves", "cannonical_solution": "", "test": ""}
{"tast_id": "count-vowels-permutation", "prompt": "# Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules:\n# Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`)\n# Each vowel `'a'` may only be followed by an `'e'`.\n# \n# Each vowel `'e'` may only be followed by an `'a'` or an `'i'`.\n# \n# Each vowel `'i'` may not be followed by another `'i'`.\n# \n# Each vowel `'o'` may only be followed by an `'i'` or a `'u'`.\n# \n# Each vowel `'u'` may only be followed by an `'a'.`\n# Since the answer may be too large, return it modulo `10^9 + 7.`\n# \n# Example 1:\n# Input: n = 1\n# Output: 5\n# Explanation: All possible strings are: \"a\", \"e\", \"i\" , \"o\" and \"u\".\n# \n# \n# Example 2:\n# Input: n = 2\n# Output: 10\n# Explanation: All possible strings are: \"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\" and \"ua\".\n# \n# \n# Example 3: \n# Input: n = 5\n# Output: 68\n# \n# Constraints:\n# `1 <= n <= 2 * 10^4`\nclass Solution:\n def countVowelPermutation(self, n: int) -> int:\n ", "entry_point": "countVowelPermutation", "cannonical_solution": "", "test": ""}
{"tast_id": "dice-roll-simulation", "prompt": "# A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number `i` more than `rollMax[i]` (1-indexed) consecutive times. \n# Given an array of integers `rollMax` and an integer `n`, return the number of distinct sequences that can be obtained with exact `n` rolls.\n# \n# Two sequences are considered different if at least one element differs from each other. Since the answer may be too large, return it modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: n = 2, rollMax = [1,1,2,2,2,3]\n# Output: 34\n# Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.\n# \n# \n# Example 2:\n# Input: n = 2, rollMax = [1,1,1,1,1,1]\n# Output: 30\n# \n# Example 3:\n# Input: n = 3, rollMax = [1,1,1,2,2,3]\n# Output: 181\n# \n# Constraints:\n# `1 <= n <= 5000`\n# `rollMax.length == 6`\n# `1 <= rollMax[i] <= 15`\nclass Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n ", "entry_point": "dieSimulator", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-equal-frequency", "prompt": "# Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.\n# \n# If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).\n# \n# \n# Example 1:\n# Input: nums = [2,2,1,1,5,3,3,5]\n# Output: 7\n# Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.\n# \n# \n# Example 2:\n# Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]\n# Output: 13\n# \n# Example 3:\n# Input: nums = [1,1,1,2,2,2]\n# Output: 5\n# \n# Example 4:\n# Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6]\n# Output: 8\n# \n# Constraints:\n# `2 <= nums.length <= 10^5`\n# `1 <= nums[i] <= 10^5`\nclass Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n ", "entry_point": "maxEqualFreq", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-profit-in-job-scheduling", "prompt": "# We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`.\n# \n# You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.\n# \n# If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`.\n# \n# \n# Example 1:\n# Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]\n# Output: 120\n# Explanation: The subset chosen is the first and fourth job. \n# Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.\n# \n# \n# Example 2:\n# Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]\n# Output: 150\n# Explanation: The subset chosen is the first, fourth and fifth job. \n# Profit obtained 150 = 20 + 70 + 60.\n# \n# \n# Example 3:\n# Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]\n# Output: 6\n# \n# Constraints:\n# `1 <= startTime.length == endTime.length == profit.length <= 5 * 104`\n# `1 <= startTime[i] < endTime[i] <= 109`\n# `1 <= profit[i] <= 104`\nclass Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n ", "entry_point": "jobScheduling", "cannonical_solution": "", "test": ""}
{"tast_id": "tiling-a-rectangle-with-the-fewest-squares", "prompt": "# Given a rectangle of size `n` x `m`, find the minimum number of integer-sided squares that tile the rectangle.\n# \n# \n# Example 1:\n# Input: n = 2, m = 3\n# Output: 3\n# Explanation: `3` squares are necessary to cover the rectangle.\n# \n# `2` (squares of `1x1`)\n# `1` (square of `2x2`)\n# \n# Example 2:\n# Input: n = 5, m = 8\n# Output: 5\n# \n# Example 3:\n# Input: n = 11, m = 13\n# Output: 6\n# \n# Constraints:\n# `1 <= n <= 13`\n# `1 <= m <= 13`\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n ", "entry_point": "tilingRectangle", "cannonical_solution": "", "test": ""}
{"tast_id": "check-if-it-is-a-good-array", "prompt": "# Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of `1` from the array by any possible subset and multiplicand.\n# \n# Return `True` if the array is good otherwise return `False`.\n# \n# \n# Example 1:\n# Input: nums = [12,5,7,23]\n# Output: true\n# Explanation: Pick numbers 5 and 7.\n# \n# 5*3 + 7*(-2) = 1\n# \n# Example 2:\n# Input: nums = [29,6,10]\n# Output: true\n# Explanation: Pick numbers 29, 6 and 10.\n# \n# 29*1 + 6*(-3) + 10*(-1) = 1\n# \n# Example 3:\n# Input: nums = [3,6]\n# Output: false\n# \n# Constraints:\n# `1 <= nums.length <= 10^5`\n# `1 <= nums[i] <= 10^9`\nclass Solution:\n def isGoodArray(self, nums: List[int]) -> bool:\n ", "entry_point": "isGoodArray", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-score-words-formed-by-letters", "prompt": "# Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character.\n# \n# Return the maximum score of any valid set of words formed by using the given letters (`words[i]` cannot be used two or more times).\n# \n# It is not necessary to use all characters in `letters` and each letter can only be used once. Score of letters `'a'`, `'b'`, `'c'`, ... ,`'z'` is given by `score[0]`, `score[1]`, ... , `score[25]` respectively.\n# \n# \n# Example 1:\n# Input: words = [\"dog\",\"cat\",\"dad\",\"good\"], letters = [\"a\",\"a\",\"c\",\"d\",\"d\",\"d\",\"g\",\"o\",\"o\"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]\n# Output: 23\n# Explanation:\n# Score a=1, c=9, d=5, g=3, o=2\n# Given letters, we can form the words \"dad\" (5+1+5) and \"good\" (3+2+2+5) with a score of 23.\n# \n# Words \"dad\" and \"dog\" only get a score of 21.\n# \n# \n# Example 2:\n# Input: words = [\"xxxz\",\"ax\",\"bx\",\"cx\"], letters = [\"z\",\"a\",\"b\",\"c\",\"x\",\"x\",\"x\"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]\n# Output: 27\n# Explanation:\n# Score a=4, b=4, c=4, x=5, z=10\n# Given letters, we can form the words \"ax\" (4+5), \"bx\" (4+5) and \"cx\" (4+5) with a score of 27.\n# \n# Word \"xxxz\" only get a score of 25.\n# \n# \n# Example 3:\n# Input: words = [\"leetcode\"], letters = [\"l\",\"e\",\"t\",\"c\",\"o\",\"d\"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]\n# Output: 0\n# Explanation:\n# Letter \"e\" can only be used once.\n# \n# \n# Constraints:\n# `1 <= words.length <= 14`\n# `1 <= words[i].length <= 15`\n# `1 <= letters.length <= 100`\n# `letters[i].length == 1`\n# `score.length == 26`\n# `0 <= score[i] <= 10`\n# `words[i]`, `letters[i]` contains only lower case English letters.\nclass Solution:\n def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n ", "entry_point": "maxScoreWords", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-moves-to-move-a-box-to-their-target-location", "prompt": "# Storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.\n# \n# The game is represented by a `grid` of size `m x n`, where each element is a wall, floor, or a box.\n# \n# Your task is move the box `'B'` to the target position `'T'` under the following rules:\n# Player is represented by character `'S'` and can move up, down, left, right in the `grid` if it is a floor (empy cell).\n# \n# Floor is represented by character `'.'` that means free cell to walk.\n# \n# Wall is represented by character `'#'` that means obstacle (impossible to walk there). \n# There is only one box `'B'` and one target cell `'T'` in the `grid`.\n# \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# \n# The player cannot walk through the box.\n# \n# Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return `-1`.\n# \n# \n# Example 1:\n# Input: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n# [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n# [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n# [\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n# [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n# [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\n# Output: 3\n# Explanation: We return only the number of times the box is pushed.\n# \n# \n# Example 2:\n# Input: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n# [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n# [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n# [\"#\",\"#\",\"#\",\"#\",\".\",\"#\"],\n# [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n# [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\n# Output: -1\n# \n# Example 3:\n# Input: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n# [\"#\",\"T\",\".\",\".\",\"#\",\"#\"],\n# [\"#\",\".\",\"#\",\"B\",\".\",\"#\"],\n# [\"#\",\".\",\".\",\".\",\".\",\"#\"],\n# [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n# [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\n# Output: 5\n# Explanation: push the box down, left, left, up and up.\n# \n# \n# Example 4:\n# Input: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n# [\"#\",\"S\",\"#\",\".\",\"B\",\"T\",\"#\"],\n# [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\n# Output: -1\n# \n# Constraints:\n# `m == grid.length`\n# `n == grid[i].length`\n# `1 <= m <= 20`\n# `1 <= n <= 20`\n# `grid` contains only characters `'.'`, `'#'`, `'S'` , `'T'`, or `'B'`.\n# \n# There is only one character `'S'`, `'B'` and `'T'` in the `grid`.\nclass Solution:\n def minPushBox(self, grid: List[List[str]]) -> int:\n ", "entry_point": "minPushBox", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-ways-to-stay-in-the-same-place-after-some-steps", "prompt": "# You have a pointer at index `0` in an array of size `arrLen`. At each step, you can move 1 position to the left, 1 position to the right in the array or stay in the same place (The pointer should not be placed outside the array at any time).\n# \n# Given two integers `steps` and `arrLen`, return the number of ways such that your pointer still at index `0` after exactly `steps` steps.\n# \n# Since the answer may be too large, return it modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: steps = 3, arrLen = 2\n# Output: 4\n# Explanation: There are 4 differents ways to stay at index 0 after 3 steps.\n# \n# Right, Left, Stay\n# Stay, Right, Left\n# Right, Stay, Left\n# Stay, Stay, Stay\n# \n# Example 2:\n# Input: steps = 2, arrLen = 4\n# Output: 2\n# Explanation: There are 2 differents ways to stay at index 0 after 2 steps\n# Right, Left\n# Stay, Stay\n# \n# Example 3:\n# Input: steps = 4, arrLen = 2\n# Output: 8\n# \n# Constraints:\n# `1 <= steps <= 500`\n# `1 <= arrLen <= 10^6`\nclass Solution:\n def numWays(self, steps: int, arrLen: int) -> int:\n ", "entry_point": "numWays", "cannonical_solution": "", "test": ""}
{"tast_id": "palindrome-partitioning-iii", "prompt": "# You are given a string `s` containing lowercase letters and an integer `k`. You need to :\n# First, change some characters of `s` to other lowercase English letters.\n# \n# Then divide `s` into `k` non-empty disjoint substrings such that each substring is palindrome.\n# \n# Return the minimal number of characters that you need to change to divide the string.\n# \n# \n# Example 1:\n# Input: s = \"abc\", k = 2\n# Output: 1\n# Explanation: You can split the string into \"ab\" and \"c\", and change 1 character in \"ab\" to make it palindrome.\n# \n# \n# Example 2:\n# Input: s = \"aabbc\", k = 3\n# Output: 0\n# Explanation: You can split the string into \"aa\", \"bb\" and \"c\", all of them are palindrome.\n# \n# \n# Example 3:\n# Input: s = \"leetcode\", k = 8\n# Output: 0\n# \n# Constraints:\n# `1 <= k <= s.length <= 100`.\n# \n# `s` only contains lowercase English letters.\nclass Solution:\n def palindromePartition(self, s: str, k: int) -> int:\n ", "entry_point": "palindromePartition", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix", "prompt": "# Given a `m x n` binary matrix `mat`. In one step, you can choose one cell and flip it and all the four neighbours of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighboors if they share one edge.\n# \n# Return the minimum number of steps required to convert `mat` to a zero matrix or -1 if you cannot.\n# \n# Binary matrix is a matrix with all cells equal to 0 or 1 only.\n# \n# Zero matrix is a matrix with all cells equal to 0.\n# \n# \n# Example 1:\n# Input: mat = [[0,0],[0,1]]\n# Output: 3\n# Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.\n# \n# \n# Example 2:\n# Input: mat = [[0]]\n# Output: 0\n# Explanation: Given matrix is a zero matrix. We don't need to change it.\n# \n# \n# Example 3:\n# Input: mat = [[1,1,1],[1,0,1],[0,0,0]]\n# Output: 6\n# \n# Example 4:\n# Input: mat = [[1,0,0],[1,0,0]]\n# Output: -1\n# Explanation: Given matrix can't be a zero matrix\n# \n# Constraints:\n# `m == mat.length`\n# `n == mat[0].length`\n# `1 <= m <= 3`\n# `1 <= n <= 3`\n# `mat[i][j]` is 0 or 1.\nclass Solution:\n def minFlips(self, mat: List[List[int]]) -> int:\n ", "entry_point": "minFlips", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-falling-path-sum-ii", "prompt": "# Given a square grid of integers `arr`, a falling path with non-zero shifts is a choice of exactly one element from each row of `arr`, such that no two elements chosen in adjacent rows are in the same column.\n# \n# Return the minimum sum of a falling path with non-zero shifts.\n# \n# \n# Example 1:\n# Input: arr = [[1,2,3],[4,5,6],[7,8,9]]\n# Output: 13\n# Explanation: \n# The possible falling paths are:\n# [1,5,9], [1,5,7], [1,6,7], [1,6,8],\n# [2,4,8], [2,4,9], [2,6,7], [2,6,8],\n# [3,4,8], [3,4,9], [3,5,7], [3,5,9]\n# The falling path with the smallest sum is [1,5,7], so the answer is 13.\n# \n# \n# Constraints:\n# `1 <= arr.length == arr[i].length <= 200`\n# `-99 <= arr[i][j] <= 99`\nclass Solution:\n def minFallingPathSum(self, grid: List[List[int]]) -> int:\n ", "entry_point": "minFallingPathSum", "cannonical_solution": "", "test": ""}
{"tast_id": "shortest-path-in-a-grid-with-obstacles-elimination", "prompt": "# Given a `m * n` grid, where each cell is either `0` (empty) or `1` (obstacle). In one step, you can move up, down, left or right from and to an empty cell.\n# \n# Return the minimum number of steps to walk from the upper left corner `(0, 0)` to the lower right corner `(m-1, n-1)` given that you can eliminate at most `k` obstacles. If it is not possible to find such walk return -1.\n# \n# \n# Example 1:\n# Input: \n# grid = \n# [[0,0,0],\n# [1,1,0],\n# [0,0,0],\n# [0,1,1],\n# [0,0,0]], \n# k = 1\n# Output: 6\n# Explanation: \n# The shortest path without eliminating any obstacle is 10. \n# The shortest path with one obstacle elimination at position (3,2) is 6. Such path is `(0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2)`.\n# \n# \n# Example 2:\n# Input: \n# grid = \n# [[0,1,1],\n# [1,1,1],\n# [1,0,0]], \n# k = 1\n# Output: -1\n# Explanation: \n# We need to eliminate at least two obstacles to find such a walk.\n# \n# \n# Constraints:\n# `grid.length == m`\n# `grid[0].length == n`\n# `1 <= m, n <= 40`\n# `1 <= k <= m*n`\n# `grid[i][j] == 0 or 1`\n# `grid[0][0] == grid[m-1][n-1] == 0`\nclass Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n ", "entry_point": "shortestPath", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-candies-you-can-get-from-boxes", "prompt": "# Given `n` boxes, each box is given in the format `[status, candies, keys, containedBoxes]` where:\n# `status[i]`: an integer which is 1 if `box[i]` is open and 0 if `box[i]` is closed.\n# \n# `candies[i]`: an integer representing the number of candies in `box[i]`.\n# \n# `keys[i]`: an array contains the indices of the boxes you can open with the key in `box[i]`.\n# \n# `containedBoxes[i]`: an array contains the indices of the boxes found in `box[i]`.\n# \n# You will start with some boxes given in `initialBoxes` array. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.\n# \n# Return the maximum number of candies you can get following the rules above.\n# \n# \n# Example 1:\n# Input: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]\n# Output: 16\n# Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2. Box 1 is closed and you don't have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.\n# \n# In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.\n# \n# Total number of candies collected = 7 + 4 + 5 = 16 candy.\n# \n# \n# Example 2:\n# Input: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]\n# Output: 6\n# Explanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys. The total number of candies will be 6.\n# \n# \n# Example 3:\n# Input: status = [1,1,1], candies = [100,1,100], keys = [[],[0,2],[]], containedBoxes = [[],[],[]], initialBoxes = [1]\n# Output: 1\n# \n# Example 4:\n# Input: status = [1], candies = [100], keys = [[]], containedBoxes = [[]], initialBoxes = []\n# Output: 0\n# \n# Example 5:\n# Input: status = [1,1,1], candies = [2,3,2], keys = [[],[],[]], containedBoxes = [[],[],[]], initialBoxes = [2,1,0]\n# Output: 7\n# \n# Constraints:\n# `1 <= status.length <= 1000`\n# `status.length == candies.length == keys.length == containedBoxes.length == n`\n# `status[i]` is `0` or `1`.\n# \n# `1 <= candies[i] <= 1000`\n# `0 <= keys[i].length <= status.length`\n# `0 <= keys[i][j] < status.length`\n# All values in `keys[i]` are unique.\n# \n# `0 <= containedBoxes[i].length <= status.length`\n# `0 <= containedBoxes[i][j] < status.length`\n# All values in `containedBoxes[i]` are unique.\n# \n# Each box is contained in one box at most.\n# \n# `0 <= initialBoxes.length <= status.length`\n# `0 <= initialBoxes[i] < status.length`\nclass Solution:\n def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:\n ", "entry_point": "maxCandies", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-paths-with-max-score", "prompt": "# You are given a square `board` of characters. You can move on the board starting at the bottom right square marked with the character `'S'`.\n# \n# You need to reach the top left square marked with the character `'E'`. The rest of the squares are labeled either with a numeric character `1, 2, ..., 9` or with an obstacle `'X'`. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.\n# \n# Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo `10^9 + 7`.\n# \n# In case there is no path, return `[0, 0]`.\n# \n# \n# Example 1:\n# Input: board = [\"E23\",\"2X2\",\"12S\"]\n# Output: [7,1]\n# \n# Example 2:\n# Input: board = [\"E12\",\"1X1\",\"21S\"]\n# Output: [4,2]\n# \n# Example 3:\n# Input: board = [\"E11\",\"XXX\",\"11S\"]\n# Output: [0,0]\n# \n# Constraints:\n# `2 <= board.length == board[i].length <= 100`\nclass Solution:\n def pathsWithMaxScore(self, board: List[str]) -> List[int]:\n ", "entry_point": "pathsWithMaxScore", "cannonical_solution": "", "test": ""}
{"tast_id": "verbal-arithmetic-puzzle", "prompt": "# Given an equation, represented by `words` on left side and the `result` on right side.\n# \n# You need to check if the equation is solvable under the following rules:\n# Each character is decoded as one digit (0 - 9).\n# \n# Every pair of different characters they must map to different digits.\n# \n# Each `words[i]` and `result` are decoded as one number without leading zeros.\n# \n# Sum of numbers on left side (`words`) will equal to the number on right side (`result`). \n# Return `True` if the equation is solvable otherwise return `False`.\n# \n# \n# Example 1:\n# Input: words = [\"SEND\",\"MORE\"], result = \"MONEY\"\n# Output: true\n# Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'\n# Such that: \"SEND\" + \"MORE\" = \"MONEY\" , 9567 + 1085 = 10652\n# \n# Example 2:\n# Input: words = [\"SIX\",\"SEVEN\",\"SEVEN\"], result = \"TWENTY\"\n# Output: true\n# Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4\n# Such that: \"SIX\" + \"SEVEN\" + \"SEVEN\" = \"TWENTY\" , 650 + 68782 + 68782 = 138214\n# \n# Example 3:\n# Input: words = [\"THIS\",\"IS\",\"TOO\"], result = \"FUNNY\"\n# Output: true\n# \n# Example 4:\n# Input: words = [\"LEET\",\"CODE\"], result = \"POINT\"\n# Output: false\n# \n# Constraints:\n# `2 <= words.length <= 5`\n# `1 <= words[i].length, result.length <= 7`\n# `words[i], result` contain only uppercase English letters.\n# \n# The number of different characters used in the expression is at most `10`.\nclass Solution:\n def isSolvable(self, words: List[str], result: str) -> bool:\n ", "entry_point": "isSolvable", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-insertion-steps-to-make-a-string-palindrome", "prompt": "# Given a string `s`. In one step you can insert any character at any index of the string.\n# \n# Return the minimum number of steps to make `s` palindrome.\n# \n# A Palindrome String is one that reads the same backward as well as forward.\n# \n# \n# Example 1:\n# Input: s = \"zzazz\"\n# Output: 0\n# Explanation: The string \"zzazz\" is already palindrome we don't need any insertions.\n# \n# \n# Example 2:\n# Input: s = \"mbadm\"\n# Output: 2\n# Explanation: String can be \"mbdadbm\" or \"mdbabdm\".\n# \n# \n# Example 3:\n# Input: s = \"leetcode\"\n# Output: 5\n# Explanation: Inserting 5 characters the string becomes \"leetcodocteel\".\n# \n# \n# Example 4:\n# Input: s = \"g\"\n# Output: 0\n# \n# Example 5:\n# Input: s = \"no\"\n# Output: 1\n# \n# Constraints:\n# `1 <= s.length <= 500`\n# All characters of `s` are lower case English letters.\nclass Solution:\n def minInsertions(self, s: str) -> int:\n ", "entry_point": "minInsertions", "cannonical_solution": "", "test": ""}
{"tast_id": "distinct-echo-substrings", "prompt": "# Return the number of distinct non-empty substrings of `text` that can be written as the concatenation of some string with itself (i.e. it can be written as `a + a` where `a` is some string).\n# \n# \n# Example 1:\n# Input: text = \"abcabcabc\"\n# Output: 3\n# Explanation: The 3 substrings are \"abcabc\", \"bcabca\" and \"cabcab\".\n# \n# \n# Example 2:\n# Input: text = \"leetcodeleetcode\"\n# Output: 2\n# Explanation: The 2 substrings are \"ee\" and \"leetcodeleetcode\".\n# \n# \n# Constraints:\n# `1 <= text.length <= 2000`\n# `text` has only lowercase English letters.\nclass Solution:\n def distinctEchoSubstrings(self, text: str) -> int:\n ", "entry_point": "distinctEchoSubstrings", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-distance-to-type-a-word-using-two-fingers", "prompt": "# You have a keyboard layout as shown above in the XY plane, where each English uppercase letter is located at some coordinate, for example, the letter A is located at coordinate (0,0), the letter B is located at coordinate (0,1), the letter P is located at coordinate (2,3) and the letter Z is located at coordinate (4,1).\n# \n# Given the string `word`, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1,y1) and (x2,y2) is |x1 - x2| + |y1 - y2|. \n# Note that the initial positions of your two fingers are considered free so don't count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.\n# \n# \n# Example 1:\n# Input: word = \"CAKE\"\n# Output: 3\n# Explanation: \n# Using two fingers, one optimal way to type \"CAKE\" is: \n# Finger 1 on letter 'C' -> cost = 0 \n# Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 \n# Finger 2 on letter 'K' -> cost = 0 \n# Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 \n# Total distance = 3\n# \n# Example 2:\n# Input: word = \"HAPPY\"\n# Output: 6\n# Explanation: \n# Using two fingers, one optimal way to type \"HAPPY\" is:\n# Finger 1 on letter 'H' -> cost = 0\n# Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2\n# Finger 2 on letter 'P' -> cost = 0\n# Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0\n# Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4\n# Total distance = 6\n# \n# Example 3:\n# Input: word = \"NEW\"\n# Output: 3\n# \n# Example 4:\n# Input: word = \"YEAR\"\n# Output: 7\n# \n# Constraints:\n# `2 <= word.length <= 300`\n# Each word[i]` is an English uppercase letter.\nclass Solution:\n def minimumDistance(self, word: str) -> int:\n ", "entry_point": "minimumDistance", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-number-of-taps-to-open-to-water-a-garden", "prompt": "# There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`).\n# \n# There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden.\n# \n# Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-indexed) means the `i-th` tap can water the area `[i - ranges[i], i + ranges[i]]` if it was open.\n# \n# Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.\n# \n# \n# Example 1:\n# Input: n = 5, ranges = [3,4,1,1,0,0]\n# Output: 1\n# Explanation: The tap at point 0 can cover the interval [-3,3]\n# The tap at point 1 can cover the interval [-3,5]\n# The tap at point 2 can cover the interval [1,3]\n# The tap at point 3 can cover the interval [2,4]\n# The tap at point 4 can cover the interval [4,4]\n# The tap at point 5 can cover the interval [5,5]\n# Opening Only the second tap will water the whole garden [0,5]\n# \n# Example 2:\n# Input: n = 3, ranges = [0,0,0,0]\n# Output: -1\n# Explanation: Even if you activate all the four taps you cannot water the whole garden.\n# \n# \n# Example 3:\n# Input: n = 7, ranges = [1,2,1,0,2,1,0,1]\n# Output: 3\n# \n# Example 4:\n# Input: n = 8, ranges = [4,0,0,0,0,0,0,0,4]\n# Output: 2\n# \n# Example 5:\n# Input: n = 8, ranges = [4,0,0,0,4,0,0,0,4]\n# Output: 1\n# \n# Constraints:\n# `1 <= n <= 10^4`\n# `ranges.length == n + 1`\n# `0 <= ranges[i] <= 100`\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n ", "entry_point": "minTaps", "cannonical_solution": "", "test": ""}
{"tast_id": "reverse-subarray-to-maximize-array-value", "prompt": "# You are given an integer array `nums`. The value of this array is defined as the sum of `|nums[i]-nums[i+1]|` for all `0 <= i < nums.length-1`.\n# \n# You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.\n# \n# Find maximum possible value of the final array.\n# \n# \n# Example 1:\n# Input: nums = [2,3,1,5,4]\n# Output: 10\n# Explanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.\n# \n# \n# Example 2:\n# Input: nums = [2,4,9,24,2,1,10]\n# Output: 68\n# \n# Constraints:\n# `1 <= nums.length <= 3*10^4`\n# `-10^5 <= nums[i] <= 10^5`\nclass Solution:\n def maxValueAfterReverse(self, nums: List[int]) -> int:\n ", "entry_point": "maxValueAfterReverse", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-difficulty-of-a-job-schedule", "prompt": "# You want to schedule a list of jobs in `d` days. Jobs are dependent (i.e To work on the `i-th` job, you have to finish all the jobs `j` where `0 <= j < i`).\n# \n# You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the `d` days. The difficulty of a day is the maximum difficulty of a job done in that day.\n# \n# Given an array of integers `jobDifficulty` and an integer `d`. The difficulty of the `i-th` job is `jobDifficulty[i]`.\n# \n# Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.\n# \n# \n# Example 1:\n# Input: jobDifficulty = [6,5,4,3,2,1], d = 2\n# Output: 7\n# Explanation: First day you can finish the first 5 jobs, total difficulty = 6.\n# \n# Second day you can finish the last job, total difficulty = 1.\n# \n# The difficulty of the schedule = 6 + 1 = 7 \n# \n# Example 2:\n# Input: jobDifficulty = [9,9,9], d = 4\n# Output: -1\n# Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.\n# \n# \n# Example 3:\n# Input: jobDifficulty = [1,1,1], d = 3\n# Output: 3\n# Explanation: The schedule is one job per day. total difficulty will be 3.\n# \n# \n# Example 4:\n# Input: jobDifficulty = [7,1,7,1,7,1], d = 3\n# Output: 15\n# \n# Example 5:\n# Input: jobDifficulty = [11,111,22,222,33,333,44,444], d = 6\n# Output: 843\n# \n# Constraints:\n# `1 <= jobDifficulty.length <= 300`\n# `0 <= jobDifficulty[i] <= 1000`\n# `1 <= d <= 10`\nclass Solution:\n def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:\n ", "entry_point": "minDifficulty", "cannonical_solution": "", "test": ""}
{"tast_id": "jump-game-v", "prompt": "# Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index:\n# `i + x` where: `i + x < arr.length` and ` 0 < x <= d`.\n# \n# `i - x` where: `i - x >= 0` and ` 0 < x <= d`.\n# \n# In addition, you can only jump from index `i` to index `j` if `arr[i] > arr[j]` and `arr[i] > arr[k]` for all indices `k` between `i` and `j` (More formally `min(i, j) < k < max(i, j)`).\n# \n# You can choose any index of the array and start jumping. Return the maximum number of indices you can visit.\n# \n# Notice that you can not jump outside of the array at any time.\n# \n# \n# Example 1:\n# Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2\n# Output: 4\n# Explanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.\n# \n# Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.\n# \n# Similarly You cannot jump from index 3 to index 2 or index 1.\n# \n# \n# Example 2:\n# Input: arr = [3,3,3,3,3], d = 3\n# Output: 1\n# Explanation: You can start at any index. You always cannot jump to any index.\n# \n# \n# Example 3:\n# Input: arr = [7,6,5,4,3,2,1], d = 1\n# Output: 7\n# Explanation: Start at index 0. You can visit all the indicies. \n# \n# Example 4:\n# Input: arr = [7,1,7,1,7,1], d = 2\n# Output: 2\n# \n# Example 5:\n# Input: arr = [66], d = 1\n# Output: 1\n# \n# Constraints:\n# `1 <= arr.length <= 1000`\n# `1 <= arr[i] <= 10^5`\n# `1 <= d <= arr.length`\nclass Solution:\n def maxJumps(self, arr: List[int], d: int) -> int:\n ", "entry_point": "maxJumps", "cannonical_solution": "", "test": ""}
{"tast_id": "jump-game-iv", "prompt": "# Given an array of integers `arr`, you are initially positioned at the first index of the array.\n# \n# In one step you can jump from index `i` to index:\n# `i + 1` where: `i + 1 < arr.length`.\n# \n# `i - 1` where: `i - 1 >= 0`.\n# \n# `j` where: `arr[i] == arr[j]` and `i != j`.\n# \n# Return the minimum number of steps to reach the last index of the array.\n# \n# Notice that you can not jump outside of the array at any time.\n# \n# \n# Example 1:\n# Input: arr = [100,-23,-23,404,100,23,23,23,3,404]\n# Output: 3\n# Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.\n# \n# \n# Example 2:\n# Input: arr = [7]\n# Output: 0\n# Explanation: Start index is the last index. You don't need to jump.\n# \n# \n# Example 3:\n# Input: arr = [7,6,9,6,9,6,9,7]\n# Output: 1\n# Explanation: You can jump directly from index 0 to index 7 which is last index of the array.\n# \n# \n# Example 4:\n# Input: arr = [6,1,9]\n# Output: 2\n# \n# Example 5:\n# Input: arr = [11,22,7,7,7,7,7,7,7,22,13]\n# Output: 3\n# \n# Constraints:\n# `1 <= arr.length <= 5 * 104`\n# `-108 <= arr[i] <= 108`\nclass Solution:\n def minJumps(self, arr: List[int]) -> int:\n ", "entry_point": "minJumps", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-students-taking-exam", "prompt": "# Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character.\n# \n# Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible..\n# \n# Students must be placed in seats in good condition.\n# \n# \n# Example 1:\n# Input: seats = [[\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n# [\".\",\"#\",\"#\",\"#\",\"#\",\".\"],\n# [\"#\",\".\",\"#\",\"#\",\".\",\"#\"]]\n# Output: 4\n# Explanation: Teacher can place 4 students in available seats so they don't cheat on the exam. \n# \n# Example 2:\n# Input: seats = [[\".\",\"#\"],\n# [\"#\",\"#\"],\n# [\"#\",\".\"],\n# [\"#\",\"#\"],\n# [\".\",\"#\"]]\n# Output: 3\n# Explanation: Place all students in available seats. \n# \n# Example 3:\n# Input: seats = [[\"#\",\".\",\".\",\".\",\"#\"],\n# [\".\",\"#\",\".\",\"#\",\".\"],\n# [\".\",\".\",\"#\",\".\",\".\"],\n# [\".\",\"#\",\".\",\"#\",\".\"],\n# [\"#\",\".\",\".\",\".\",\"#\"]]\n# Output: 10\n# Explanation: Place students in available seats in column 1, 3 and 5.\n# \n# \n# Constraints:\n# `seats` contains only characters `'.' and``'#'.`\n# `m == seats.length`\n# `n == seats[i].length`\n# `1 <= m <= 8`\n# `1 <= n <= 8`\nclass Solution:\n def maxStudents(self, seats: List[List[str]]) -> int:\n ", "entry_point": "maxStudents", "cannonical_solution": "", "test": ""}
{"tast_id": "construct-target-array-with-multiple-sums", "prompt": "# Given an array of integers `target`. From a starting array, `A` consisting of all 1's, you may perform the following procedure :\n# let `x` be the sum of all elements currently in your array.\n# \n# choose index `i`, such that `0 <= i < target.size` and set the value of `A` at index `i` to `x`.\n# \n# You may repeat this procedure as many times as needed.\n# \n# Return True if it is possible to construct the `target` array from `A` otherwise return False.\n# \n# \n# Example 1:\n# Input: target = [9,3,5]\n# Output: true\n# Explanation: Start with [1, 1, 1] \n# [1, 1, 1], sum = 3 choose index 1\n# [1, 3, 1], sum = 5 choose index 2\n# [1, 3, 5], sum = 9 choose index 0\n# [9, 3, 5] Done\n# \n# Example 2:\n# Input: target = [1,1,1,2]\n# Output: false\n# Explanation: Impossible to create target array from [1,1,1,1].\n# \n# \n# Example 3:\n# Input: target = [8,5]\n# Output: true\n# \n# Constraints:\n# `N == target.length`\n# `1 <= target.length <= 5 * 10^4`\n# `1 <= target[i] <= 10^9`\nclass Solution:\n def isPossible(self, target: List[int]) -> bool:\n ", "entry_point": "isPossible", "cannonical_solution": "", "test": ""}
{"tast_id": "count-all-valid-pickup-and-delivery-options", "prompt": "# Given `n` orders, each order consist in pickup and delivery services. \n# Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). \n# Since the answer may be too large, return it modulo 10^9 + 7.\n# \n# \n# Example 1:\n# Input: n = 1\n# Output: 1\n# Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.\n# \n# \n# Example 2:\n# Input: n = 2\n# Output: 6\n# Explanation: All possible orders: \n# (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).\n# \n# This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.\n# \n# \n# Example 3:\n# Input: n = 3\n# Output: 90\n# \n# Constraints:\n# `1 <= n <= 500`\nclass Solution:\n def countOrders(self, n: int) -> int:\n ", "entry_point": "countOrders", "cannonical_solution": "", "test": ""}
{"tast_id": "largest-multiple-of-three", "prompt": "# Given an integer array of `digits`, return the largest multiple of three that can be formed by concatenating some of the given digits in any order.\n# \n# Since the answer may not fit in an integer data type, return the answer as a string.\n# \n# If there is no answer return an empty string.\n# \n# \n# Example 1:\n# Input: digits = [8,1,9]\n# Output: \"981\"\n# \n# Example 2:\n# Input: digits = [8,6,7,1,0]\n# Output: \"8760\"\n# \n# Example 3:\n# Input: digits = [1]\n# Output: \"\"\n# \n# Example 4:\n# Input: digits = [0,0,0,0,0,0]\n# Output: \"0\"\n# \n# Constraints:\n# `1 <= digits.length <= 10^4`\n# `0 <= digits[i] <= 9`\n# The returning answer must not contain unnecessary leading zeros.\nclass Solution:\n def largestMultipleOfThree(self, digits: List[int]) -> str:\n ", "entry_point": "largestMultipleOfThree", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-cost-to-make-at-least-one-valid-path-in-a-grid", "prompt": "# Given a m x n `grid`. Each cell of the `grid` has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of `grid[i][j]` can be:\n# 1 which means go to the cell to the right. (i.e go from `grid[i][j]` to `grid[i][j + 1]`)\n# 2 which means go to the cell to the left. (i.e go from `grid[i][j]` to `grid[i][j - 1]`)\n# 3 which means go to the lower cell. (i.e go from `grid[i][j]` to `grid[i + 1][j]`)\n# 4 which means go to the upper cell. (i.e go from `grid[i][j]` to `grid[i - 1][j]`)\n# Notice that there could be some invalid signs on the cells of the `grid` which points outside the `grid`.\n# \n# You will initially start at the upper left cell `(0,0)`. A valid path in the grid is a path which starts from the upper left cell `(0,0)` and ends at the bottom-right cell `(m - 1, n - 1)` following the signs on the grid. The valid path doesn't have to be the shortest.\n# \n# You can modify the sign on a cell with `cost = 1`. You can modify the sign on a cell one time only.\n# \n# Return the minimum cost to make the grid have at least one valid path.\n# \n# \n# Example 1:\n# Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]\n# Output: 3\n# Explanation: You will start at point (0, 0).\n# \n# The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)\n# The total cost = 3.\n# \n# \n# Example 2:\n# Input: grid = [[1,1,3],[3,2,2],[1,1,4]]\n# Output: 0\n# Explanation: You can follow the path from (0, 0) to (2, 2).\n# \n# \n# Example 3:\n# Input: grid = [[1,2],[4,3]]\n# Output: 1\n# \n# Example 4:\n# Input: grid = [[2,2,2],[2,2,2]]\n# Output: 3\n# \n# Example 5:\n# Input: grid = [[4]]\n# Output: 0\n# \n# Constraints:\n# `m == grid.length`\n# `n == grid[i].length`\n# `1 <= m, n <= 100`\nclass Solution:\n def minCost(self, grid: List[List[int]]) -> int:\n ", "entry_point": "minCost", "cannonical_solution": "", "test": ""}
{"tast_id": "frog-position-after-t-seconds", "prompt": "# Given an undirected tree consisting of `n` vertices numbered from `1` to `n`. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex.\n# \n# The edges of the undirected tree are given in the array `edges`, where `edges[i] = [ai, bi]` means that exists an edge connecting the vertices `ai` and `bi`.\n# \n# Return the probability that after `t` seconds the frog is on the vertex `target`.\n# \n# \n# Example 1:\n# Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4\n# Output: 0.16666666666666666 \n# Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. \n# \n# Example 2:\n# Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7\n# Output: 0.3333333333333333\n# Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1. \n# \n# Example 3:\n# Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 20, target = 6\n# Output: 0.16666666666666666\n# \n# Constraints:\n# `1 <= n <= 100`\n# `edges.length == n - 1`\n# `edges[i].length == 2`\n# `1 <= ai, bi <= n`\n# `1 <= t <= 50`\n# `1 <= target <= n`\n# Answers within `10-5` of the actual value will be accepted as correct.\nclass Solution:\n def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:\n ", "entry_point": "frogPosition", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-performance-of-a-team", "prompt": "# There are `n` engineers numbered from 1 to `n` and two arrays: `speed` and `efficiency`, where `speed[i]` and `efficiency[i]` represent the speed and efficiency for the i-th engineer respectively. Return the maximum performance of a team composed of at most `k` engineers, since the answer can be a huge number, return this modulo 10^9 + 7.\n# \n# The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. \n# \n# Example 1:\n# Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2\n# Output: 60\n# Explanation: \n# We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.\n# \n# \n# Example 2:\n# Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3\n# Output: 68\n# Explanation:\n# This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.\n# \n# \n# Example 3:\n# Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4\n# Output: 72\n# \n# Constraints:\n# `1 <= n <= 10^5`\n# `speed.length == n`\n# `efficiency.length == n`\n# `1 <= speed[i] <= 10^5`\n# `1 <= efficiency[i] <= 10^8`\n# `1 <= k <= n`\nclass Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n ", "entry_point": "maxPerformance", "cannonical_solution": "", "test": ""}
{"tast_id": "pizza-with-3n-slices", "prompt": "# There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:\n# You will pick any pizza slice.\n# \n# Your friend Alice will pick next slice in anti clockwise direction of your pick. \n# Your friend Bob will pick next slice in clockwise direction of your pick.\n# \n# Repeat until there are no more slices of pizzas.\n# \n# Sizes of Pizza slices is represented by circular array `slices` in clockwise direction.\n# \n# Return the maximum possible sum of slice sizes which you can have.\n# \n# \n# Example 1:\n# Input: slices = [1,2,3,4,5,6]\n# Output: 10\n# Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.\n# \n# \n# Example 2:\n# Input: slices = [8,9,8,6,1,1]\n# Output: 16\n# Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.\n# \n# Example 3:\n# Input: slices = [4,1,2,5,8,3,1,9,7]\n# Output: 21\n# \n# Example 4:\n# Input: slices = [3,1,2]\n# Output: 3\n# \n# Constraints:\n# `1 <= slices.length <= 500`\n# `slices.length % 3 == 0`\n# `1 <= slices[i] <= 1000`\nclass Solution:\n def maxSizeSlices(self, slices: List[int]) -> int:\n ", "entry_point": "maxSizeSlices", "cannonical_solution": "", "test": ""}
{"tast_id": "longest-happy-prefix", "prompt": "# A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).\n# \n# Given a string `s`. Return the longest happy prefix of `s` .\n# \n# Return an empty string if no such prefix exists.\n# \n# \n# Example 1:\n# Input: s = \"level\"\n# Output: \"l\"\n# Explanation: s contains 4 prefix excluding itself (\"l\", \"le\", \"lev\", \"leve\"), and suffix (\"l\", \"el\", \"vel\", \"evel\"). The largest prefix which is also suffix is given by \"l\".\n# \n# \n# Example 2:\n# Input: s = \"ababab\"\n# Output: \"abab\"\n# Explanation: \"abab\" is the largest prefix which is also suffix. They can overlap in the original string.\n# \n# \n# Example 3:\n# Input: s = \"leetcodeleet\"\n# Output: \"leet\"\n# \n# Example 4:\n# Input: s = \"a\"\n# Output: \"\"\n# \n# Constraints:\n# `1 <= s.length <= 10^5`\n# `s` contains only lowercase English letters.\nclass Solution:\n def longestPrefix(self, s: str) -> str:\n ", "entry_point": "longestPrefix", "cannonical_solution": "", "test": ""}
{"tast_id": "find-all-good-strings", "prompt": "# Given the strings `s1` and `s2` of size `n`, and the string `evil`. Return the number of good strings.\n# \n# A good string has size `n`, it is alphabetically greater than or equal to `s1`, it is alphabetically smaller than or equal to `s2`, and it does not contain the string `evil` as a substring. Since the answer can be a huge number, return this modulo 10^9 + 7.\n# \n# \n# Example 1:\n# Input: n = 2, s1 = \"aa\", s2 = \"da\", evil = \"b\"\n# Output: 51 \n# Explanation: There are 25 good strings starting with 'a': \"aa\",\"ac\",\"ad\",...,\"az\". Then there are 25 good strings starting with 'c': \"ca\",\"cc\",\"cd\",...,\"cz\" and finally there is one good string starting with 'd': \"da\". \n# \n# Example 2:\n# Input: n = 8, s1 = \"leetcode\", s2 = \"leetgoes\", evil = \"leet\"\n# Output: 0 \n# Explanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix \"leet\", therefore, there is not any good string.\n# \n# \n# Example 3:\n# Input: n = 2, s1 = \"gx\", s2 = \"gz\", evil = \"x\"\n# Output: 2\n# \n# Constraints:\n# `s1.length == n`\n# `s2.length == n`\n# `s1 <= s2`\n# `1 <= n <= 500`\n# `1 <= evil.length <= 50`\n# All strings consist of lowercase English letters.\nclass Solution:\n def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:\n ", "entry_point": "findGoodStrings", "cannonical_solution": "", "test": ""}
{"tast_id": "reducing-dishes", "prompt": "# A chef has collected data on the `satisfaction` level of his `n` dishes. Chef can cook any dish in 1 unit of time.\n# \n# Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. `time[i]`*`satisfaction[i]`\n# Return the maximum sum of Like-time coefficient that the chef can obtain after dishes preparation.\n# \n# Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.\n# \n# \n# Example 1:\n# Input: satisfaction = [-1,-8,0,5,-9]\n# Output: 14\n# Explanation: After Removing the second and last dish, the maximum total Like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14). Each dish is prepared in one unit of time.\n# \n# \n# Example 2:\n# Input: satisfaction = [4,3,2]\n# Output: 20\n# Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)\n# \n# Example 3:\n# Input: satisfaction = [-1,-4,-5]\n# Output: 0\n# Explanation: People don't like the dishes. No dish is prepared.\n# \n# \n# Example 4:\n# Input: satisfaction = [-2,5,-1,0,3,-3]\n# Output: 35\n# \n# Constraints:\n# `n == satisfaction.length`\n# `1 <= n <= 500`\n# `-10^3 <= satisfaction[i] <= 10^3`\nclass Solution:\n def maxSatisfaction(self, satisfaction: List[int]) -> int:\n ", "entry_point": "maxSatisfaction", "cannonical_solution": "", "test": ""}
{"tast_id": "stone-game-iii", "prompt": "# Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array `stoneValue`.\n# \n# Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row.\n# \n# The score of each player is the sum of values of the stones taken. The score of each player is 0 initially.\n# \n# The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.\n# \n# Assume Alice and Bob play optimally.\n# \n# Return \"Alice\" if Alice will win, \"Bob\" if Bob will win or \"Tie\" if they end the game with the same score.\n# \n# \n# Example 1:\n# Input: values = [1,2,3,7]\n# Output: \"Bob\"\n# Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.\n# \n# \n# Example 2:\n# Input: values = [1,2,3,-9]\n# Output: \"Alice\"\n# Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score.\n# \n# If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose.\n# \n# If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose.\n# \n# Remember that both play optimally so here Alice will choose the scenario that makes her win.\n# \n# \n# Example 3:\n# Input: values = [1,2,3,6]\n# Output: \"Tie\"\n# Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.\n# \n# \n# Example 4:\n# Input: values = [1,2,3,-1,-2,-3,7]\n# Output: \"Alice\"\n# \n# Example 5:\n# Input: values = [-1,-2,-3]\n# Output: \"Tie\"\n# \n# Constraints:\n# `1 <= values.length <= 50000`\n# `-1000 <= values[i] <= 1000`\nclass Solution:\n def stoneGameIII(self, stoneValue: List[int]) -> str:\n ", "entry_point": "stoneGameIII", "cannonical_solution": "", "test": ""}
{"tast_id": "restore-the-array", "prompt": "# A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits and all we know is that all integers in the array were in the range `[1, k]` and there are no leading zeros in the array.\n# \n# Given the string `s` and the integer `k`. There can be multiple ways to restore the array.\n# \n# Return the number of possible array that can be printed as a string `s` using the mentioned program.\n# \n# The number of ways could be very large so return it modulo `10^9 + 7`\n# \n# Example 1:\n# Input: s = \"1000\", k = 10000\n# Output: 1\n# Explanation: The only possible array is [1000]\n# \n# Example 2:\n# Input: s = \"1000\", k = 10\n# Output: 0\n# Explanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.\n# \n# \n# Example 3:\n# Input: s = \"1317\", k = 2000\n# Output: 8\n# Explanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]\n# \n# Example 4:\n# Input: s = \"2020\", k = 30\n# Output: 1\n# Explanation: The only possible array is [20,20]. [2020] is invalid because 2020 > 30. [2,020] is ivalid because 020 contains leading zeros.\n# \n# \n# Example 5:\n# Input: s = \"1234567890\", k = 90\n# Output: 34\n# \n# Constraints:\n# `1 <= s.length <= 10^5`.\n# \n# `s` consists of only digits and doesn't contain leading zeros.\n# \n# `1 <= k <= 10^9`.\nclass Solution:\n def numberOfArrays(self, s: str, k: int) -> int:\n ", "entry_point": "numberOfArrays", "cannonical_solution": "", "test": ""}
{"tast_id": "build-array-where-you-can-find-the-maximum-exactly-k-comparisons", "prompt": "# Given three integers `n`, `m` and `k`. Consider the following algorithm to find the maximum element of an array of positive integers:\n# You should build the array arr which has the following properties:\n# `arr` has exactly `n` integers.\n# \n# `1 <= arr[i] <= m` where `(0 <= i < n)`.\n# \n# After applying the mentioned algorithm to `arr`, the value `search_cost` is equal to `k`.\n# \n# Return the number of ways to build the array `arr` under the mentioned conditions. As the answer may grow large, the answer must be computed modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: n = 2, m = 3, k = 1\n# Output: 6\n# Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]\n# \n# Example 2:\n# Input: n = 5, m = 2, k = 3\n# Output: 0\n# Explanation: There are no possible arrays that satisify the mentioned conditions.\n# \n# \n# Example 3:\n# Input: n = 9, m = 1, k = 1\n# Output: 1\n# Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]\n# \n# Example 4:\n# Input: n = 50, m = 100, k = 25\n# Output: 34549172\n# Explanation: Don't forget to compute the answer modulo 1000000007\n# \n# Example 5:\n# Input: n = 37, m = 17, k = 7\n# Output: 418930126\n# \n# Constraints:\n# `1 <= n <= 50`\n# `1 <= m <= 100`\n# `0 <= k <= n`\nclass Solution:\n def numOfArrays(self, n: int, m: int, k: int) -> int:\n ", "entry_point": "numOfArrays", "cannonical_solution": "", "test": ""}
{"tast_id": "constrained-subsequence-sum", "prompt": "# Given an integer array `nums` and an integer `k`, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, `nums[i]` and `nums[j]`, where `i < j`, the condition `j - i <= k` is satisfied.\n# \n# A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.\n# \n# \n# Example 1:\n# Input: nums = [10,2,-10,5,20], k = 2\n# Output: 37\n# Explanation: The subsequence is [10, 2, 5, 20].\n# \n# \n# Example 2:\n# Input: nums = [-1,-2,-3], k = 1\n# Output: -1\n# Explanation: The subsequence must be non-empty, so we choose the largest number.\n# \n# \n# Example 3:\n# Input: nums = [10,-2,-10,-5,20], k = 2\n# Output: 23\n# Explanation: The subsequence is [10, -2, -5, 20].\n# \n# \n# Constraints:\n# `1 <= k <= nums.length <= 105`\n# `-104 <= nums[i] <= 104`\nclass Solution:\n def constrainedSubsetSum(self, nums: List[int], k: int) -> int:\n ", "entry_point": "constrainedSubsetSum", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-ways-to-wear-different-hats-to-each-other", "prompt": "# There are `n` people and 40 types of hats labeled from 1 to 40.\n# \n# Given a list of list of integers `hats`, where `hats[i]` is a list of all hats preferred by the i-th` person.\n# \n# Return the number of ways that the n people wear different hats to each other.\n# \n# Since the answer may be too large, return it modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: hats = [[3,4],[4,5],[5]]\n# Output: 1\n# Explanation: There is only one way to choose hats given the conditions. \n# First person choose hat 3, Second person choose hat 4 and last one hat 5.\n# \n# \n# Example 2:\n# Input: hats = [[3,5,1],[3,5]]\n# Output: 4\n# Explanation: There are 4 ways to choose hats\n# (3,5), (5,3), (1,3) and (1,5)\n# \n# Example 3:\n# Input: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]\n# Output: 24\n# Explanation: Each person can choose hats labeled from 1 to 4.\n# \n# Number of Permutations of (1,2,3,4) = 24.\n# \n# \n# Example 4:\n# Input: hats = [[1,2,3],[2,3,5,6],[1,3,7,9],[1,8,9],[2,5,7]]\n# Output: 111\n# \n# Constraints:\n# `n == hats.length`\n# `1 <= n <= 10`\n# `1 <= hats[i].length <= 40`\n# `1 <= hats[i][j] <= 40`\n# `hats[i]` contains a list of unique integers.\nclass Solution:\n def numberWays(self, hats: List[List[int]]) -> int:\n ", "entry_point": "numberWays", "cannonical_solution": "", "test": ""}
{"tast_id": "find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows", "prompt": "# You are given an `m * n` matrix, `mat`, and an integer `k`, which has its rows sorted in non-decreasing order.\n# \n# You are allowed to choose exactly 1 element from each row to form an array. Return the Kth smallest array sum among all possible arrays.\n# \n# \n# Example 1:\n# Input: mat = [[1,3,11],[2,4,6]], k = 5\n# Output: 7\n# Explanation: Choosing one element from each row, the first k smallest sum are:\n# [1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7. \n# \n# Example 2:\n# Input: mat = [[1,3,11],[2,4,6]], k = 9\n# Output: 17\n# \n# Example 3:\n# Input: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7\n# Output: 9\n# Explanation: Choosing one element from each row, the first k smallest sum are:\n# [1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9. \n# \n# Example 4:\n# Input: mat = [[1,1,10],[2,2,9]], k = 7\n# Output: 12\n# \n# Constraints:\n# `m == mat.length`\n# `n == mat.length[i]`\n# `1 <= m, n <= 40`\n# `1 <= k <= min(200, n ^ m)`\n# `1 <= mat[i][j] <= 5000`\n# `mat[i]` is a non decreasing array.\nclass Solution:\n def kthSmallest(self, mat: List[List[int]], k: int) -> int:\n ", "entry_point": "kthSmallest", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-ways-of-cutting-a-pizza", "prompt": "# Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. \n# For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.\n# \n# Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.\n# \n# \n# Example 1:\n# Input: pizza = [\"A..\",\"AAA\",\"...\"], k = 3\n# Output: 3 \n# Explanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.\n# \n# \n# Example 2:\n# Input: pizza = [\"A..\",\"AA.\",\"...\"], k = 3\n# Output: 1\n# \n# Example 3:\n# Input: pizza = [\"A..\",\"A..\",\"...\"], k = 1\n# Output: 1\n# \n# Constraints:\n# `1 <= rows, cols <= 50`\n# `rows == pizza.length`\n# `cols == pizza[i].length`\n# `1 <= k <= 10`\n# `pizza` consists of characters `'A'` and `'.'` only.\nclass Solution:\n def ways(self, pizza: List[str], k: int) -> int:\n ", "entry_point": "ways", "cannonical_solution": "", "test": ""}
{"tast_id": "form-largest-integer-with-digits-that-add-up-to-target", "prompt": "# Given an array of integers `cost` and an integer `target`. Return the maximum integer you can paint under the following rules:\n# The cost of painting a digit (i+1) is given by `cost[i]` (0 indexed).\n# \n# The total cost used must be equal to `target`.\n# \n# Integer does not have digits 0.\n# \n# Since the answer may be too large, return it as string.\n# \n# If there is no way to paint any integer given the condition, return \"0\".\n# \n# \n# Example 1:\n# Input: cost = [4,3,2,5,6,7,2,5,5], target = 9\n# Output: \"7772\"\n# Explanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost(\"7772\") = 2*3+ 3*1 = 9. You could also paint \"977\", but \"7772\" is the largest number.\n# \n# Digit cost\n# 1 -> 4\n# 2 -> 3\n# 3 -> 2\n# 4 -> 5\n# 5 -> 6\n# 6 -> 7\n# 7 -> 2\n# 8 -> 5\n# 9 -> 5\n# \n# Example 2:\n# Input: cost = [7,6,5,5,5,6,8,7,8], target = 12\n# Output: \"85\"\n# Explanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost(\"85\") = 7 + 5 = 12.\n# \n# \n# Example 3:\n# Input: cost = [2,4,6,2,4,6,4,4,4], target = 5\n# Output: \"0\"\n# Explanation: It's not possible to paint any integer with total cost equal to target.\n# \n# \n# Example 4:\n# Input: cost = [6,10,15,40,40,40,40,40,40], target = 47\n# Output: \"32211\"\n# \n# Constraints:\n# `cost.length == 9`\n# `1 <= cost[i] <= 5000`\n# `1 <= target <= 5000`\nclass Solution:\n def largestNumber(self, cost: List[int], target: int) -> str:\n ", "entry_point": "largestNumber", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-number-of-darts-inside-of-a-circular-dartboard", "prompt": "# You have a very large square wall and a circular dartboard placed on the wall. You have been challenged to throw darts into the board blindfolded. Darts thrown at the wall are represented as an array of `points` on a 2D plane. \n# Return the maximum number of points that are within or lie on any circular dartboard of radius `r`.\n# \n# \n# Example 1:\n# Input: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 2\n# Output: 4\n# Explanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.\n# \n# \n# Example 2:\n# Input: points = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5\n# Output: 5\n# Explanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).\n# \n# \n# Example 3:\n# Input: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 1\n# Output: 1\n# \n# Example 4:\n# Input: points = [[1,2],[3,5],[1,-1],[2,3],[4,1],[1,3]], r = 2\n# Output: 4\n# \n# Constraints:\n# `1 <= points.length <= 100`\n# `points[i].length == 2`\n# `-10^4 <= points[i][0], points[i][1] <= 10^4`\n# `1 <= r <= 5000`\nclass Solution:\n def numPoints(self, darts: List[List[int]], r: int) -> int:\n ", "entry_point": "numPoints", "cannonical_solution": "", "test": ""}
{"tast_id": "max-dot-product-of-two-subsequences", "prompt": "# Given two arrays `nums1` and `nums2`.\n# \n# Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.\n# \n# A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, `[2,3,5]` is a subsequence of `[1,2,3,4,5]` while `[1,5,3]` is not).\n# \n# \n# Example 1:\n# Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]\n# Output: 18\n# Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\n# \n# Their dot product is (2*3 + (-2)*(-6)) = 18.\n# \n# \n# Example 2:\n# Input: nums1 = [3,-2], nums2 = [2,-6,7]\n# Output: 21\n# Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.\n# \n# Their dot product is (3*7) = 21.\n# \n# \n# Example 3:\n# Input: nums1 = [-1,-1], nums2 = [1,1]\n# Output: -1\n# Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.\n# \n# Their dot product is -1.\n# \n# \n# Constraints:\n# `1 <= nums1.length, nums2.length <= 500`\n# `-1000 <= nums1[i], nums2[i] <= 1000`\nclass Solution:\n def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:\n ", "entry_point": "maxDotProduct", "cannonical_solution": "", "test": ""}
{"tast_id": "cherry-pickup-ii", "prompt": "# Given a `rows x cols` matrix `grid` representing a field of cherries. Each cell in `grid` represents the number of cherries that you can collect.\n# \n# You have two robots that can collect cherries for you, Robot #1 is located at the top-left corner (0,0) , and Robot #2 is located at the top-right corner (0, cols-1) of the grid.\n# \n# Return the maximum number of cherries collection using both robots by following the rules below:\n# From a cell (i,j), robots can move to cell (i+1, j-1) , (i+1, j) or (i+1, j+1).\n# \n# When any robot is passing through a cell, It picks it up all cherries, and the cell becomes an empty cell (0).\n# \n# When both robots stay on the same cell, only one of them takes the cherries.\n# \n# Both robots cannot move outside of the grid at any moment.\n# \n# Both robots should reach the bottom row in the `grid`.\n# \n# \n# Example 1:\n# Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]\n# Output: 24\n# Explanation: Path of robot #1 and #2 are described in color green and blue respectively.\n# \n# Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.\n# \n# Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.\n# \n# Total of cherries: 12 + 12 = 24.\n# \n# \n# Example 2:\n# Input: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]\n# Output: 28\n# Explanation: Path of robot #1 and #2 are described in color green and blue respectively.\n# \n# Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.\n# \n# Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.\n# \n# Total of cherries: 17 + 11 = 28.\n# \n# \n# Example 3:\n# Input: grid = [[1,0,0,3],[0,0,0,3],[0,0,3,3],[9,0,3,3]]\n# Output: 22\n# \n# Example 4:\n# Input: grid = [[1,1],[1,1]]\n# Output: 4\n# \n# Constraints:\n# `rows == grid.length`\n# `cols == grid[i].length`\n# `2 <= rows, cols <= 70`\n# `0 <= grid[i][j] <= 100 `\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n ", "entry_point": "cherryPickup", "cannonical_solution": "", "test": ""}
{"tast_id": "probability-of-a-two-boxes-having-the-same-number-of-distinct-balls", "prompt": "# Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`. \n# All the balls will be shuffled uniformly at random, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please read the explanation of the second example carefully).\n# \n# Please note that the two boxes are considered different. For example, if we have two balls of colors `a` and `b`, and two boxes `[]` and `()`, then the distribution `[a] (b)` is considered different than the distribution `[b] (a) `(Please read the explanation of the first example carefully).\n# \n# We want to calculate the probability that the two boxes have the same number of distinct balls.\n# \n# \n# Example 1:\n# Input: balls = [1,1]\n# Output: 1.00000\n# Explanation: Only 2 ways to divide the balls equally:\n# - A ball of color 1 to box 1 and a ball of color 2 to box 2\n# - A ball of color 2 to box 1 and a ball of color 1 to box 2\n# In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1\n# \n# Example 2:\n# Input: balls = [2,1,1]\n# Output: 0.66667\n# Explanation: We have the set of balls [1, 1, 2, 3]\n# This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equale probability (i.e. 1/12):\n# [1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]\n# After that we add the first two balls to the first box and the second two balls to the second box.\n# \n# We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.\n# \n# Probability is 8/12 = 0.66667\n# \n# Example 3:\n# Input: balls = [1,2,1,2]\n# Output: 0.60000\n# Explanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.\n# \n# Probability = 108 / 180 = 0.6\n# \n# Example 4:\n# Input: balls = [3,2,1]\n# Output: 0.30000\n# Explanation: The set of balls is [1, 1, 1, 2, 2, 3]. It is hard to display all the 60 possible random shuffles of this set but it is easy to check that 18 of them will have the same number of distinct colors in each box.\n# \n# Probability = 18 / 60 = 0.3\n# \n# Example 5:\n# Input: balls = [6,6,6,6,6,6]\n# Output: 0.90327\n# \n# Constraints:\n# `1 <= balls.length <= 8`\n# `1 <= balls[i] <= 6`\n# `sum(balls)` is even.\n# \n# Answers within `10^-5` of the actual value will be accepted as correct.\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n ", "entry_point": "getProbability", "cannonical_solution": "", "test": ""}
{"tast_id": "paint-house-iii", "prompt": "# There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again.\n# \n# A neighborhood is a maximal group of continuous houses that are painted with the same color.\n# \n# For example: `houses = [1,2,2,3,3,2,1,1]` contains `5` neighborhoods `[{1}, {2,2}, {3,3}, {2}, {1,1}]`.\n# \n# Given an array `houses`, an `m x n` matrix `cost` and an integer `target` where:\n# `houses[i]`: is the color of the house `i`, and `0` if the house is not painted yet.\n# \n# `cost[i][j]`: is the cost of paint the house `i` with the color `j + 1`.\n# \n# Return the minimum cost of painting all the remaining houses in such a way that there are exactly `target` neighborhoods. If it is not possible, return `-1`.\n# \n# \n# Example 1:\n# Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\n# Output: 9\n# Explanation: Paint houses of this way [1,2,2,1,1]\n# This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].\n# \n# Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.\n# \n# \n# Example 2:\n# Input: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\n# Output: 11\n# Explanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2]\n# This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. \n# Cost of paint the first and last house (10 + 1) = 11.\n# \n# \n# Example 3:\n# Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[1,10],[10,1],[1,10]], m = 5, n = 2, target = 5\n# Output: 5\n# \n# Example 4:\n# Input: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3\n# Output: -1\n# Explanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.\n# \n# \n# Constraints:\n# `m == houses.length == cost.length`\n# `n == cost[i].length`\n# `1 <= m <= 100`\n# `1 <= n <= 20`\n# `1 <= target <= m`\n# `0 <= houses[i] <= n`\n# `1 <= cost[i][j] <= 10^4`\nclass Solution:\n def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:\n ", "entry_point": "minCost", "cannonical_solution": "", "test": ""}
{"tast_id": "allocate-mailboxes", "prompt": "# Given the array `houses` and an integer `k`. where `houses[i]` is the location of the ith house along a street, your task is to allocate `k` mailboxes in the street.\n# \n# Return the minimum total distance between each house and its nearest mailbox.\n# \n# The answer is guaranteed to fit in a 32-bit signed integer.\n# \n# \n# Example 1:\n# Input: houses = [1,4,8,10,20], k = 3\n# Output: 5\n# Explanation: Allocate mailboxes in position 3, 9 and 20.\n# \n# Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 \n# \n# Example 2:\n# Input: houses = [2,3,5,12,18], k = 2\n# Output: 9\n# Explanation: Allocate mailboxes in position 3 and 14.\n# \n# Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.\n# \n# \n# Example 3:\n# Input: houses = [7,4,6,1], k = 1\n# Output: 8\n# \n# Example 4:\n# Input: houses = [3,6,14,10], k = 4\n# Output: 0\n# \n# Constraints:\n# `n == houses.length`\n# `1 <= n <= 100`\n# `1 <= houses[i] <= 10^4`\n# `1 <= k <= n`\n# Array `houses` contain unique integers.\nclass Solution:\n def minDistance(self, houses: List[int], k: int) -> int:\n ", "entry_point": "minDistance", "cannonical_solution": "", "test": ""}
{"tast_id": "kth-ancestor-of-a-tree-node", "prompt": "# You are given a tree with `n` nodes numbered from `0` to `n-1` in the form of a parent array where `parent[i]` is the parent of node `i`. The root of the tree is node `0`.\n# \n# Implement the function `getKthAncestor``(int node, int k)` to return the `k`-th ancestor of the given `node`. If there is no such ancestor, return `-1`.\n# \n# The k-th ancestor of a tree node is the `k`-th node in the path from that node to the root.\n# \n# \n# Example:\n# Input:\n# [\"TreeAncestor\",\"getKthAncestor\",\"getKthAncestor\",\"getKthAncestor\"]\n# [[7,[-1,0,0,1,1,2,2]],[3,1],[5,2],[6,3]]\n# Output:\n# [null,1,0,-1]\n# Explanation:\n# TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);\n# treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3\n# treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5\n# treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor\n# \n# Constraints:\n# `1 <= k <= n <= 5*10^4`\n# `parent[0] == -1` indicating that `0` is the root node.\n# \n# `0 <= parent[i] < n` for all `0 < i < n`\n# `0 <= node < n`\n# There will be at most `5*10^4` queries.\nclass TreeAncestor:\n\n def __init__(self, n: int, parent: List[int]):\n \n\n def getKthAncestor(self, node: int, k: int) -> int:\n \n\n\n# Your TreeAncestor object will be instantiated and called as such:\n# obj = TreeAncestor(n, parent)\n# param_1 = obj.getKthAncestor(node,k)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree", "prompt": "# Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.\n# \n# Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.\n# \n# Note that you can return the indices of the edges in any order.\n# \n# \n# Example 1:\n# Input: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]\n# Output: [[0,1],[2,3,4,5]]\n# Explanation: The figure above describes the graph.\n# \n# The following figure shows all the possible MSTs:\n# Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.\n# \n# The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.\n# \n# \n# Example 2:\n# Input: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]\n# Output: [[],[0,1,2,3]]\n# Explanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.\n# \n# \n# Constraints:\n# `2 <= n <= 100`\n# `1 <= edges.length <= min(200, n * (n - 1) / 2)`\n# `edges[i].length == 3`\n# `0 <= ai < bi < n`\n# `1 <= weighti <= 1000`\n# All pairs `(ai, bi)` are distinct.\nclass Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n ", "entry_point": "findCriticalAndPseudoCriticalEdges", "cannonical_solution": "", "test": ""}
{"tast_id": "parallel-courses-ii", "prompt": "# Given the integer `n` representing the number of courses at some university labeled from `1` to `n`, and the array `dependencies` where `dependencies[i] = [xi, yi]` represents a prerequisite relationship, that is, the course `xi` must be taken before the course `yi`. Also, you are given the integer `k`.\n# \n# In one semester you can take at most `k` courses as long as you have taken all the prerequisites for the courses you are taking.\n# \n# Return the minimum number of semesters to take all courses. It is guaranteed that you can take all courses in some way.\n# \n# \n# Example 1:\n# Input: n = 4, dependencies = [[2,1],[3,1],[1,4]], k = 2\n# Output: 3 \n# Explanation: The figure above represents the given graph. In this case we can take courses 2 and 3 in the first semester, then take course 1 in the second semester and finally take course 4 in the third semester.\n# \n# \n# Example 2:\n# Input: n = 5, dependencies = [[2,1],[3,1],[4,1],[1,5]], k = 2\n# Output: 4 \n# Explanation: The figure above represents the given graph. In this case one optimal way to take all courses is: take courses 2 and 3 in the first semester and take course 4 in the second semester, then take course 1 in the third semester and finally take course 5 in the fourth semester.\n# \n# \n# Example 3:\n# Input: n = 11, dependencies = [], k = 2\n# Output: 6\n# \n# Constraints:\n# `1 <= n <= 15`\n# `1 <= k <= n`\n# `0 <= dependencies.length <= n * (n-1) / 2`\n# `dependencies[i].length == 2`\n# `1 <= xi, yi <= n`\n# `xi != yi`\n# All prerequisite relationships are distinct, that is, `dependencies[i] != dependencies[j]`.\n# \n# The given graph is a directed acyclic graph.\nclass Solution:\n def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int:\n ", "entry_point": "minNumberOfSemesters", "cannonical_solution": "", "test": ""}
{"tast_id": "max-value-of-equation", "prompt": "# Given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.\n# \n# Find the maximum value of the equation `yi + yj + |xi - xj|` where `|xi - xj| <= k` and `1 <= i < j <= points.length`. It is guaranteed that there exists at least one pair of points that satisfy the constraint `|xi - xj| <= k`.\n# \n# \n# Example 1:\n# Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1\n# Output: 4\n# Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.\n# \n# No other pairs satisfy the condition, so we return the max of 4 and 1.\n# \n# \n# Example 2:\n# Input: points = [[0,0],[3,0],[9,2]], k = 3\n# Output: 3\n# Explanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.\n# \n# \n# Constraints:\n# `2 <= points.length <= 10^5`\n# `points[i].length == 2`\n# `-10^8 <= points[i][0], points[i][1] <= 10^8`\n# `0 <= k <= 2 * 10^8`\n# `points[i][0] < points[j][0]` for all `1 <= i < j <= points.length`\n# `xi` form a strictly increasing sequence.\nclass Solution:\n def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int:\n ", "entry_point": "findMaxValueOfEquation", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits", "prompt": "# Given a string `num` representing the digits of a very large integer and an integer `k`.\n# \n# You are allowed to swap any two adjacent digits of the integer at most `k` times.\n# \n# Return the minimum integer you can obtain also as a string.\n# \n# \n# Example 1:\n# Input: num = \"4321\", k = 4\n# Output: \"1342\"\n# Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.\n# \n# \n# Example 2:\n# Input: num = \"100\", k = 1\n# Output: \"010\"\n# Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.\n# \n# \n# Example 3:\n# Input: num = \"36789\", k = 1000\n# Output: \"36789\"\n# Explanation: We can keep the number without any swaps.\n# \n# \n# Example 4:\n# Input: num = \"22\", k = 22\n# Output: \"22\"\n# \n# Example 5:\n# Input: num = \"9438957234785635408\", k = 23\n# Output: \"0345989723478563548\"\n# \n# Constraints:\n# `1 <= num.length <= 30000`\n# `num` contains digits only and doesn't have leading zeros.\n# \n# `1 <= k <= 10^9`\nclass Solution:\n def minInteger(self, num: str, k: int) -> str:\n ", "entry_point": "minInteger", "cannonical_solution": "", "test": ""}
{"tast_id": "stone-game-iv", "prompt": "# Alice and Bob take turns playing a game, with Alice starting first.\n# \n# Initially, there are `n` stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.\n# \n# Also, if a player cannot make a move, he/she loses the game.\n# \n# Given a positive integer `n`. Return `True` if and only if Alice wins the game otherwise return `False`, assuming both players play optimally.\n# \n# \n# Example 1:\n# Input: n = 1\n# Output: true\n# Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.\n# \n# \n# Example 2:\n# Input: n = 2\n# Output: false\n# Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).\n# \n# \n# Example 3:\n# Input: n = 4\n# Output: true\n# Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).\n# \n# \n# Example 4:\n# Input: n = 7\n# Output: false\n# Explanation: Alice can't win the game if Bob plays optimally.\n# \n# If Alice starts removing 4 stones, Bob will remove 1 stone then Alice should remove only 1 stone and finally Bob removes the last one (7 -> 3 -> 2 -> 1 -> 0). \n# If Alice starts removing 1 stone, Bob will remove 4 stones then Alice only can remove 1 stone and finally Bob removes the last one (7 -> 6 -> 2 -> 1 -> 0).\n# \n# \n# Example 5:\n# Input: n = 17\n# Output: false\n# Explanation: Alice can't win the game if Bob plays optimally.\n# \n# \n# Constraints:\n# `1 <= n <= 10^5`\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n ", "entry_point": "winnerSquareGame", "cannonical_solution": "", "test": ""}
{"tast_id": "best-position-for-a-service-centre", "prompt": "# A delivery company wants to build a new service centre in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new centre in a position such that the sum of the euclidean distances to all customers is minimum.\n# \n# Given an array `positions` where `positions[i] = [xi, yi]` is the position of the `ith` customer on the map, return the minimum sum of the euclidean distances to all customers.\n# \n# In other words, you need to choose the position of the service centre `[xcentre, ycentre]` such that the following formula is minimized:\n# Answers within `10^-5` of the actual value will be accepted.\n# \n# \n# Example 1:\n# Input: positions = [[0,1],[1,0],[1,2],[2,1]]\n# Output: 4.00000\n# Explanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.\n# \n# \n# Example 2:\n# Input: positions = [[1,1],[3,3]]\n# Output: 2.82843\n# Explanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843\n# \n# Example 3:\n# Input: positions = [[1,1]]\n# Output: 0.00000\n# \n# Example 4:\n# Input: positions = [[1,1],[0,0],[2,0]]\n# Output: 2.73205\n# Explanation: At the first glance, you may think that locating the centre at [1, 0] will achieve the minimum sum, but locating it at [1, 0] will make the sum of distances = 3.\n# \n# Try to locate the centre at [1.0, 0.5773502711] you will see that the sum of distances is 2.73205.\n# \n# Be careful with the precision!\n# \n# Example 5:\n# Input: positions = [[0,1],[3,2],[4,5],[7,6],[8,9],[11,1],[2,12]]\n# Output: 32.94036\n# Explanation: You can use [4.3460852395, 4.9813795505] as the position of the centre.\n# \n# \n# Constraints:\n# `1 <= positions.length <= 50`\n# `positions[i].length == 2`\n# `0 <= positions[i][0], positions[i][1] <= 100`\nclass Solution:\n def getMinDistSum(self, positions: List[List[int]]) -> float:\n ", "entry_point": "getMinDistSum", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-number-of-non-overlapping-substrings", "prompt": "# Given a string `s` of lowercase letters, you need to find the maximum number of non-empty substrings of `s` that meet the following conditions:\n# The substrings do not overlap, that is for any two substrings `s[i..j]` and `s[k..l]`, either `j < k` or `i > l` is true.\n# \n# A substring that contains a certain character `c` must also contain all occurrences of `c`.\n# \n# Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length.\n# \n# Notice that you can return the substrings in any order.\n# \n# \n# Example 1:\n# Input: s = \"adefaddaccc\"\n# Output: [\"e\",\"f\",\"ccc\"]\n# Explanation: The following are all the possible substrings that meet the conditions:\n# [\n# \"adefaddaccc\"\n# \"adefadda\",\n# \"ef\",\n# \"e\",\n# \"f\",\n# \"ccc\",\n# ]\n# If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose \"adefadda\", we are left with \"ccc\" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose \"ef\" since it can be split into two. Therefore, the optimal way is to choose [\"e\",\"f\",\"ccc\"] which gives us 3 substrings. No other solution of the same number of substrings exist.\n# \n# \n# Example 2:\n# Input: s = \"abbaccd\"\n# Output: [\"d\",\"bb\",\"cc\"]\n# Explanation: Notice that while the set of substrings [\"d\",\"abba\",\"cc\"] also has length 3, it's considered incorrect since it has larger total length.\n# \n# \n# Constraints:\n# `1 <= s.length <= 10^5`\n# `s` contains only lowercase English letters.\nclass Solution:\n def maxNumOfSubstrings(self, s: str) -> List[str]:\n ", "entry_point": "maxNumOfSubstrings", "cannonical_solution": "", "test": ""}
{"tast_id": "find-a-value-of-a-mysterious-function-closest-to-target", "prompt": "# Winston was given the above mysterious function `func`. He has an integer array `arr` and an integer `target` and he wants to find the values `l` and `r` that make the value `|func(arr, l, r) - target|` minimum possible.\n# \n# Return the minimum possible value of `|func(arr, l, r) - target|`.\n# \n# Notice that `func` should be called with the values `l` and `r` where `0 <= l, r < arr.length`.\n# \n# \n# Example 1:\n# Input: arr = [9,12,3,7,15], target = 5\n# Output: 2\n# Explanation: Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.\n# \n# \n# Example 2:\n# Input: arr = [1000000,1000000,1000000], target = 1\n# Output: 999999\n# Explanation: Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.\n# \n# \n# Example 3:\n# Input: arr = [1,2,4,8,16], target = 0\n# Output: 0\n# \n# Constraints:\n# `1 <= arr.length <= 105`\n# `1 <= arr[i] <= 106`\n# `0 <= target <= 107`\nclass Solution:\n def closestToTarget(self, arr: List[int], target: int) -> int:\n ", "entry_point": "closestToTarget", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-number-of-increments-on-subarrays-to-form-a-target-array", "prompt": "# Given an array of positive integers `target` and an array `initial` of same size with all zeros.\n# \n# Return the minimum number of operations to form a `target` array from `initial` if you are allowed to do the following operation:\n# Choose any subarray from `initial` and increment each value by one.\n# \n# The answer is guaranteed to fit within the range of a 32-bit signed integer.\n# \n# \n# Example 1:\n# Input: target = [1,2,3,2,1]\n# Output: 3\n# Explanation: We need at least 3 operations to form the target array from the initial array.\n# \n# [0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).\n# \n# [1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).\n# \n# [1,2,2,2,1] increment 1 at index 2.\n# \n# [1,2,3,2,1] target array is formed.\n# \n# \n# Example 2:\n# Input: target = [3,1,1,2]\n# Output: 4\n# Explanation: (initial)[0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2] (target).\n# \n# \n# Example 3:\n# Input: target = [3,1,5,4,2]\n# Output: 7\n# Explanation: (initial)[0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] \n# -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2] (target).\n# \n# \n# Example 4:\n# Input: target = [1,1,1,1]\n# Output: 1\n# \n# Constraints:\n# `1 <= target.length <= 10^5`\n# `1 <= target[i] <= 10^5`\nclass Solution:\n def minNumberOperations(self, target: List[int]) -> int:\n ", "entry_point": "minNumberOperations", "cannonical_solution": "", "test": ""}
{"tast_id": "string-compression-ii", "prompt": "# Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string `\"aabccc\"` we replace `\"aa\"` by `\"a2\"` and replace `\"ccc\"` by `\"c3\"`. Thus the compressed string becomes `\"a2bc3\"`.\n# \n# Notice that in this problem, we are not adding `'1'` after single characters.\n# \n# Given a string `s` and an integer `k`. You need to delete at most `k` characters from `s` such that the run-length encoded version of `s` has minimum length.\n# \n# Find the minimum length of the run-length encoded version of `s` after deleting at most `k` characters.\n# \n# \n# Example 1:\n# Input: s = \"aaabcccd\", k = 2\n# Output: 4\n# Explanation: Compressing s without deleting anything will give us \"a3bc3d\" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = \"abcccd\" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be \"a3c3\" of length 4.\n# \n# \n# Example 2:\n# Input: s = \"aabbaa\", k = 2\n# Output: 2\n# Explanation: If we delete both 'b' characters, the resulting compressed string would be \"a4\" of length 2.\n# \n# \n# Example 3:\n# Input: s = \"aaaaaaaaaaa\", k = 0\n# Output: 3\n# Explanation: Since k is zero, we cannot delete anything. The compressed string is \"a11\" of length 3.\n# \n# \n# Constraints:\n# `1 <= s.length <= 100`\n# `0 <= k <= s.length`\n# `s` contains only lowercase English letters.\nclass Solution:\n def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n ", "entry_point": "getLengthOfOptimalCompression", "cannonical_solution": "", "test": ""}
{"tast_id": "get-the-maximum-score", "prompt": "# You are given two sorted arrays of distinct integers `nums1` and `nums2.`\n# A valid path is defined as follows:\n# Choose array nums1 or nums2 to traverse (from index-0).\n# \n# Traverse the current array from left to right.\n# \n# If you are reading any value that is present in `nums1` and `nums2` you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).\n# \n# Score is defined as the sum of uniques values in a valid path.\n# \n# Return the maximum score you can obtain of all possible valid paths.\n# \n# Since the answer may be too large, return it modulo 10^9 + 7.\n# \n# \n# Example 1:\n# Input: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]\n# Output: 30\n# Explanation: Valid paths:\n# [2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)\n# [4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)\n# The maximum is obtained with the path in green [2,4,6,8,10].\n# \n# \n# Example 2:\n# Input: nums1 = [1,3,5,7,9], nums2 = [3,5,100]\n# Output: 109\n# Explanation: Maximum sum is obtained with the path [1,3,5,100].\n# \n# \n# Example 3:\n# Input: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]\n# Output: 40\n# Explanation: There are no common elements between nums1 and nums2.\n# \n# Maximum sum is obtained with the path [6,7,8,9,10].\n# \n# \n# Example 4:\n# Input: nums1 = [1,4,5,8,9,11,19], nums2 = [2,3,4,11,12]\n# Output: 61\n# \n# Constraints:\n# `1 <= nums1.length <= 10^5`\n# `1 <= nums2.length <= 10^5`\n# `1 <= nums1[i], nums2[i] <= 10^7`\n# `nums1` and `nums2` are strictly increasing.\nclass Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n ", "entry_point": "maxSum", "cannonical_solution": "", "test": ""}
{"tast_id": "find-longest-awesome-substring", "prompt": "# Given a string `s`. An awesome substring is a non-empty substring of `s` such that we can make any number of swaps in order to make it palindrome.\n# \n# Return the length of the maximum length awesome substring of `s`.\n# \n# \n# Example 1:\n# Input: s = \"3242415\"\n# Output: 5\n# Explanation: \"24241\" is the longest awesome substring, we can form the palindrome \"24142\" with some swaps.\n# \n# \n# Example 2:\n# Input: s = \"12345678\"\n# Output: 1\n# \n# Example 3:\n# Input: s = \"213123\"\n# Output: 6\n# Explanation: \"213123\" is the longest awesome substring, we can form the palindrome \"231132\" with some swaps.\n# \n# \n# Example 4:\n# Input: s = \"00\"\n# Output: 2\n# \n# Constraints:\n# `1 <= s.length <= 10^5`\n# `s` consists only of digits.\nclass Solution:\n def longestAwesome(self, s: str) -> int:\n ", "entry_point": "longestAwesome", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-cost-to-cut-a-stick", "prompt": "# Given a wooden stick of length `n` units. The stick is labelled from `0` to `n`. For example, a stick of length 6 is labelled as follows:\n# Given an integer array `cuts` where `cuts[i]` denotes a position you should perform a cut at.\n# \n# You should perform the cuts in order, you can change the order of the cuts as you wish.\n# \n# The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.\n# \n# Return the minimum total cost of the cuts.\n# \n# \n# Example 1:\n# Input: n = 7, cuts = [1,3,4,5]\n# Output: 16\n# Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:\n# The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.\n# \n# Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).\n# \n# \n# Example 2:\n# Input: n = 9, cuts = [5,6,1,4,2]\n# Output: 22\n# Explanation: If you try the given cuts ordering the cost will be 25.\n# \n# There are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.\n# \n# \n# Constraints:\n# `2 <= n <= 10^6`\n# `1 <= cuts.length <= min(n - 1, 100)`\n# `1 <= cuts[i] <= n - 1`\n# All the integers in `cuts` array are distinct.\nclass Solution:\n def minCost(self, n: int, cuts: List[int]) -> int:\n ", "entry_point": "minCost", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-number-of-days-to-eat-n-oranges", "prompt": "# There are `n` oranges in the kitchen and you decided to eat some of these oranges every day as follows:\n# Eat one orange.\n# \n# If the number of remaining oranges (`n`) is divisible by 2 then you can eat n/2 oranges.\n# \n# If the number of remaining oranges (`n`) is divisible by 3 then you can eat 2*(n/3) oranges.\n# \n# You can only choose one of the actions per day.\n# \n# Return the minimum number of days to eat `n` oranges.\n# \n# \n# Example 1:\n# Input: n = 10\n# Output: 4\n# Explanation: You have 10 oranges.\n# \n# Day 1: Eat 1 orange, 10 - 1 = 9. \n# Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)\n# Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. \n# Day 4: Eat the last orange 1 - 1 = 0.\n# \n# You need at least 4 days to eat the 10 oranges.\n# \n# \n# Example 2:\n# Input: n = 6\n# Output: 3\n# Explanation: You have 6 oranges.\n# \n# Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).\n# \n# Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)\n# Day 3: Eat the last orange 1 - 1 = 0.\n# \n# You need at least 3 days to eat the 6 oranges.\n# \n# \n# Example 3:\n# Input: n = 1\n# Output: 1\n# \n# Example 4:\n# Input: n = 56\n# Output: 6\n# \n# Constraints:\n# `1 <= n <= 2*10^9`\nclass Solution:\n def minDays(self, n: int) -> int:\n ", "entry_point": "minDays", "cannonical_solution": "", "test": ""}
{"tast_id": "detect-cycles-in-2d-grid", "prompt": "# Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the same value in `grid`.\n# \n# A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.\n# \n# Also, you cannot move to the cell that you visited in your last move. For example, the cycle `(1, 1) -> (1, 2) -> (1, 1)` is invalid because from `(1, 2)` we visited `(1, 1)` which was the last visited cell.\n# \n# Return `true` if any cycle of the same value exists in `grid`, otherwise, return `false`.\n# \n# \n# Example 1:\n# Input: grid = [[\"a\",\"a\",\"a\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"a\",\"a\",\"a\"]]\n# Output: true\n# Explanation: There are two valid cycles shown in different colors in the image below:\n# \n# Example 2:\n# Input: grid = [[\"c\",\"c\",\"c\",\"a\"],[\"c\",\"d\",\"c\",\"c\"],[\"c\",\"c\",\"e\",\"c\"],[\"f\",\"c\",\"c\",\"c\"]]\n# Output: true\n# Explanation: There is only one valid cycle highlighted in the image below:\n# \n# Example 3:\n# Input: grid = [[\"a\",\"b\",\"b\"],[\"b\",\"z\",\"b\"],[\"b\",\"b\",\"a\"]]\n# Output: false\n# \n# Constraints:\n# `m == grid.length`\n# `n == grid[i].length`\n# `1 <= m <= 500`\n# `1 <= n <= 500`\n# `grid` consists only of lowercase English letters.\nclass Solution:\n def containsCycle(self, grid: List[List[str]]) -> bool:\n ", "entry_point": "containsCycle", "cannonical_solution": "", "test": ""}
{"tast_id": "stone-game-v", "prompt": "# There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array `stoneValue`.\n# \n# In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.\n# \n# The game ends when there is only one stone remaining. Alice's is initially zero.\n# \n# Return the maximum score that Alice can obtain.\n# \n# \n# Example 1:\n# Input: stoneValue = [6,2,3,4,5,5]\n# Output: 18\n# Explanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.\n# \n# In the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).\n# \n# The last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.\n# \n# \n# Example 2:\n# Input: stoneValue = [7,7,7,7,7,7,7]\n# Output: 28\n# \n# Example 3:\n# Input: stoneValue = [4]\n# Output: 0\n# \n# Constraints:\n# `1 <= stoneValue.length <= 500`\n# `1 <= stoneValue[i] <= 10^6`\nclass Solution:\n def stoneGameV(self, stoneValue: List[int]) -> int:\n ", "entry_point": "stoneGameV", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-number-of-days-to-disconnect-island", "prompt": "# Given a 2D `grid` consisting of `1`s (land) and `0`s (water). An island is a maximal 4-directionally (horizontal or vertical) connected group of `1`s.\n# \n# The grid is said to be connected if we have exactly one island, otherwise is said disconnected.\n# \n# In one day, we are allowed to change any single land cell `(1)` into a water cell `(0)`.\n# \n# Return the minimum number of days to disconnect the grid.\n# \n# \n# Example 1:\n# Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]\n# Output: 2\n# Explanation: We need at least 2 days to get a disconnected grid.\n# \n# Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island.\n# \n# \n# Example 2:\n# Input: grid = [[1,1]]\n# Output: 2\n# Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.\n# \n# \n# Example 3:\n# Input: grid = [[1,0,1,0]]\n# Output: 0\n# \n# Example 4:\n# Input: grid = [[1,1,0,1,1],\n# [1,1,1,1,1],\n# [1,1,0,1,1],\n# [1,1,0,1,1]]\n# Output: 1\n# \n# Example 5:\n# Input: grid = [[1,1,0,1,1],\n# [1,1,1,1,1],\n# [1,1,0,1,1],\n# [1,1,1,1,1]]\n# Output: 2\n# \n# Constraints:\n# `1 <= grid.length, grid[i].length <= 30`\n# `grid[i][j]` is `0` or `1`.\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n ", "entry_point": "minDays", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-ways-to-reorder-array-to-get-same-bst", "prompt": "# Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from the original array `nums`.\n# \n# For example, given `nums = [2,1,3]`, we will have 2 as the root, 1 as a left child, and 3 as a right child. The array `[2,3,1]` also yields the same BST but `[3,2,1]` yields a different BST.\n# \n# Return the number of ways to reorder `nums` such that the BST formed is identical to the original BST formed from `nums`.\n# \n# Since the answer may be very large, return it modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: nums = [2,1,3]\n# Output: 1\n# Explanation: We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.\n# \n# \n# Example 2:\n# Input: nums = [3,4,5,1,2]\n# Output: 5\n# Explanation: The following 5 arrays will yield the same BST: \n# [3,1,2,4,5]\n# [3,1,4,2,5]\n# [3,1,4,5,2]\n# [3,4,1,2,5]\n# [3,4,1,5,2]\n# \n# Example 3:\n# Input: nums = [1,2,3]\n# Output: 0\n# Explanation: There are no other orderings of nums that will yield the same BST.\n# \n# \n# Example 4:\n# Input: nums = [3,1,2,5,4,6]\n# Output: 19\n# \n# Example 5:\n# Input: nums = [9,4,2,1,3,6,5,7,8,14,11,10,12,13,16,15,17,18]\n# Output: 216212978\n# Explanation: The number of ways to reorder nums to get the same BST is 3216212999. Taking this number modulo 10^9 + 7 gives 216212978.\n# \n# \n# Constraints:\n# `1 <= nums.length <= 1000`\n# `1 <= nums[i] <= nums.length`\n# All integers in `nums` are distinct.\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n ", "entry_point": "numOfWays", "cannonical_solution": "", "test": ""}
{"tast_id": "count-all-possible-routes", "prompt": "# You are given an array of distinct positive integers locations where `locations[i]` represents the position of city `i`. You are also given integers `start`, `finish` and `fuel` representing the starting city, ending city, and the initial amount of fuel you have, respectively.\n# \n# At each step, if you are at city `i`, you can pick any city `j` such that `j != i` and `0 <= j < locations.length` and move to city `j`. Moving from city `i` to city `j` reduces the amount of fuel you have by `|locations[i] - locations[j]|`. Please notice that `|x|` denotes the absolute value of `x`.\n# \n# Notice that `fuel` cannot become negative at any point in time, and that you are allowed to visit any city more than once (including `start` and `finish`).\n# \n# Return the count of all possible routes from `start` to `finish`.\n# \n# Since the answer may be too large, return it modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5\n# Output: 4\n# Explanation: The following are all possible routes, each uses 5 units of fuel:\n# 1 -> 3\n# 1 -> 2 -> 3\n# 1 -> 4 -> 3\n# 1 -> 4 -> 2 -> 3\n# \n# Example 2:\n# Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6\n# Output: 5\n# Explanation: The following are all possible routes:\n# 1 -> 0, used fuel = 1\n# 1 -> 2 -> 0, used fuel = 5\n# 1 -> 2 -> 1 -> 0, used fuel = 5\n# 1 -> 0 -> 1 -> 0, used fuel = 3\n# 1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5\n# \n# Example 3:\n# Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3\n# Output: 0\n# Explanation: It's impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.\n# \n# \n# Example 4:\n# Input: locations = [2,1,5], start = 0, finish = 0, fuel = 3\n# Output: 2\n# Explanation: There are two possible routes, 0 and 0 -> 1 -> 0.\n# \n# \n# Example 5:\n# Input: locations = [1,2,3], start = 0, finish = 2, fuel = 40\n# Output: 615088286\n# Explanation: The total number of possible routes is 2615088300. Taking this number modulo 10^9 + 7 gives us 615088286.\n# \n# \n# Constraints:\n# `2 <= locations.length <= 100`\n# `1 <= locations[i] <= 10^9`\n# All integers in `locations` are distinct.\n# \n# `0 <= start, finish < locations.length`\n# `1 <= fuel <= 200`\nclass Solution:\n def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:\n ", "entry_point": "countRoutes", "cannonical_solution": "", "test": ""}
{"tast_id": "remove-max-number-of-edges-to-keep-graph-fully-traversable", "prompt": "# Alice and Bob have an undirected graph of `n` nodes and 3 types of edges:\n# Type 1: Can be traversed by Alice only.\n# \n# Type 2: Can be traversed by Bob only.\n# \n# Type 3: Can by traversed by both Alice and Bob.\n# \n# Given an array `edges` where `edges[i] = [typei, ui, vi]` represents a bidirectional edge of type `typei` between nodes `ui` and `vi`, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.\n# \n# Return the maximum number of edges you can remove, or return `-1` if it's impossible for the graph to be fully traversed by Alice and Bob.\n# \n# \n# Example 1:\n# Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]\n# Output: 2\n# Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.\n# \n# \n# Example 2:\n# Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]\n# Output: 0\n# Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.\n# \n# \n# Example 3:\n# Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]\n# Output: -1\n# Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.\n# \n# \n# Constraints:\n# `1 <= n <= 10^5`\n# `1 <= edges.length <= min(10^5, 3 * n * (n-1) / 2)`\n# `edges[i].length == 3`\n# `1 <= edges[i][0] <= 3`\n# `1 <= edges[i][1] < edges[i][2] <= n`\n# All tuples `(typei, ui, vi)` are distinct.\nclass Solution:\n def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n ", "entry_point": "maxNumEdgesToRemove", "cannonical_solution": "", "test": ""}
{"tast_id": "check-if-string-is-transformable-with-substring-sort-operations", "prompt": "# Given two strings `s` and `t`, you want to transform string `s` into string `t` using the following operation any number of times:\n# Choose a non-empty substring in `s` and sort it in-place so the characters are in ascending order.\n# \n# For example, applying the operation on the underlined substring in `\"14234\"` results in `\"12344\"`.\n# \n# Return `true` if it is possible to transform string `s` into string `t`. Otherwise, return `false`.\n# \n# A substring is a contiguous sequence of characters within a string.\n# \n# \n# Example 1:\n# Input: s = \"84532\", t = \"34852\"\n# Output: true\n# Explanation: You can transform s into t using the following sort operations:\n# \"84532\" (from index 2 to 3) -> \"84352\"\n# \"84352\" (from index 0 to 2) -> \"34852\"\n# \n# Example 2:\n# Input: s = \"34521\", t = \"23415\"\n# Output: true\n# Explanation: You can transform s into t using the following sort operations:\n# \"34521\" -> \"23451\"\n# \"23451\" -> \"23415\"\n# \n# Example 3:\n# Input: s = \"12345\", t = \"12435\"\n# Output: false\n# \n# Example 4:\n# Input: s = \"1\", t = \"2\"\n# Output: false\n# \n# Constraints:\n# `s.length == t.length`\n# `1 <= s.length <= 105`\n# `s` and `t` only contain digits from `'0'` to `'9'`.\nclass Solution:\n def isTransformable(self, s: str, t: str) -> bool:\n ", "entry_point": "isTransformable", "cannonical_solution": "", "test": ""}
{"tast_id": "strange-printer-ii", "prompt": "# There is a strange printer with the following two special requirements:\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# \n# Once the printer has used a color for the above operation, the same color cannot be used again.\n# \n# You are given a `m x n` matrix `targetGrid`, where `targetGrid[row][col]` is the color in the position `(row, col)` of the grid.\n# \n# Return `true` if it is possible to print the matrix `targetGrid`, otherwise, return `false`.\n# \n# \n# Example 1:\n# Input: targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]\n# Output: true\n# \n# Example 2:\n# Input: targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]\n# Output: true\n# \n# Example 3:\n# Input: targetGrid = [[1,2,1],[2,1,2],[1,2,1]]\n# Output: false\n# Explanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns.\n# \n# \n# Example 4:\n# Input: targetGrid = [[1,1,1],[3,1,3]]\n# Output: false\n# \n# Constraints:\n# `m == targetGrid.length`\n# `n == targetGrid[i].length`\n# `1 <= m, n <= 60`\n# `1 <= targetGrid[row][col] <= 60`\nclass Solution:\n def isPrintable(self, targetGrid: List[List[int]]) -> bool:\n ", "entry_point": "isPrintable", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-cost-to-connect-two-groups-of-points", "prompt": "# You are given two groups of points where the first group has `size1` points, the second group has `size2` points, and `size1 >= size2`.\n# \n# The `cost` of the connection between any two points are given in an `size1 x size2` matrix where `cost[i][j]` is the cost of connecting point `i` of the first group and point `j` of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.\n# \n# Return the minimum cost it takes to connect the two groups.\n# \n# \n# Example 1:\n# Input: cost = [[15, 96], [36, 2]]\n# Output: 17\n# Explanation: The optimal way of connecting the groups is:\n# 1--A\n# 2--B\n# This results in a total cost of 17.\n# \n# \n# Example 2:\n# Input: cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]\n# Output: 4\n# Explanation: The optimal way of connecting the groups is:\n# 1--A\n# 2--B\n# 2--C\n# 3--A\n# This results in a total cost of 4.\n# \n# Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.\n# \n# \n# Example 3:\n# Input: cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]\n# Output: 10\n# \n# Constraints:\n# `size1 == cost.length`\n# `size2 == cost[i].length`\n# `1 <= size1, size2 <= 12`\n# `size1 >= size2`\n# `0 <= cost[i][j] <= 100`\nclass Solution:\n def connectTwoGroups(self, cost: List[List[int]]) -> int:\n ", "entry_point": "connectTwoGroups", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-number-of-achievable-transfer-requests", "prompt": "# We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.\n# \n# You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`.\n# \n# All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`.\n# \n# Return the maximum number of achievable requests.\n# \n# \n# Example 1:\n# Input: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]\n# Output: 5\n# Explantion: Let's see the requests:\n# From building 0 we have employees x and y and both want to move to building 1.\n# \n# From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.\n# \n# From building 2 we have employee z and they want to move to building 0.\n# \n# From building 3 we have employee c and they want to move to building 4.\n# \n# From building 4 we don't have any requests.\n# \n# We can achieve the requests of users x and b by swapping their places.\n# \n# We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.\n# \n# \n# Example 2:\n# Input: n = 3, requests = [[0,0],[1,2],[2,1]]\n# Output: 3\n# Explantion: Let's see the requests:\n# From building 0 we have employee x and they want to stay in the same building 0.\n# \n# From building 1 we have employee y and they want to move to building 2.\n# \n# From building 2 we have employee z and they want to move to building 1.\n# \n# We can achieve all the requests. \n# \n# Example 3:\n# Input: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]\n# Output: 4\n# \n# Constraints:\n# `1 <= n <= 20`\n# `1 <= requests.length <= 16`\n# `requests[i].length == 2`\n# `0 <= fromi, toi < n`\nclass Solution:\n def maximumRequests(self, n: int, requests: List[List[int]]) -> int:\n ", "entry_point": "maximumRequests", "cannonical_solution": "", "test": ""}
{"tast_id": "find-servers-that-handled-most-number-of-requests", "prompt": "# You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm:\n# The `ith` (0-indexed) request arrives.\n# \n# If all servers are busy, the request is dropped (not handled at all).\n# \n# If the `(i % k)th` server is available, assign the request to that server.\n# \n# Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the `ith` server is busy, try to assign the request to the `(i+1)th` server, then the `(i+2)th` server, and so on.\n# \n# You are given a strictly increasing array `arrival` of positive integers, where `arrival[i]` represents the arrival time of the `ith` request, and another array `load`, where `load[i]` represents the load of the `ith` request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers.\n# \n# Return a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order.\n# \n# \n# Example 1:\n# Input: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] \n# Output: [1] \n# Explanation:\n# All of the servers start out available.\n# \n# The first 3 requests are handled by the first 3 servers in order.\n# \n# Request 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.\n# \n# Request 4 comes in. It cannot be handled since all servers are busy, so it is dropped.\n# \n# Servers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.\n# \n# \n# Example 2:\n# Input: k = 3, arrival = [1,2,3,4], load = [1,2,1,2]\n# Output: [0]\n# Explanation:\n# The first 3 requests are handled by first 3 servers.\n# \n# Request 3 comes in. It is handled by server 0 since the server is available.\n# \n# Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.\n# \n# \n# Example 3:\n# Input: k = 3, arrival = [1,2,3], load = [10,12,11]\n# Output: [0,1,2]\n# Explanation: Each server handles a single request, so they are all considered the busiest.\n# \n# \n# Example 4:\n# Input: k = 3, arrival = [1,2,3,4,8,9,10], load = [5,2,10,3,1,2,2]\n# Output: [1]\n# \n# Example 5:\n# Input: k = 1, arrival = [1], load = [1]\n# Output: [0]\n# \n# Constraints:\n# `1 <= k <= 105`\n# `1 <= arrival.length, load.length <= 105`\n# `arrival.length == load.length`\n# `1 <= arrival[i], load[i] <= 109`\n# `arrival` is strictly increasing.\nclass Solution:\n def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:\n ", "entry_point": "busiestServers", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-number-of-visible-points", "prompt": "# You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote integral coordinates on the X-Y plane.\n# \n# Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, `posx` and `posy` cannot be changed. Your field of view in degrees is represented by `angle`, determining how wide you can see from any given view direction. Let `d` be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles `[d - angle/2, d + angle/2]`.\n# \n# Your browser does not support the video tag or this video format.\n# \n# You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view.\n# \n# There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.\n# \n# Return the maximum number of points you can see.\n# \n# \n# Example 1:\n# Input: points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]\n# Output: 3\n# Explanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.\n# \n# \n# Example 2:\n# Input: points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]\n# Output: 4\n# Explanation: All points can be made visible in your field of view, including the one at your location.\n# \n# \n# Example 3:\n# Input: points = [[1,0],[2,1]], angle = 13, location = [1,1]\n# Output: 1\n# Explanation: You can only see one of the two points, as shown above.\n# \n# \n# Constraints:\n# `1 <= points.length <= 105`\n# `points[i].length == 2`\n# `location.length == 2`\n# `0 <= angle < 360`\n# `0 <= posx, posy, xi, yi <= 100`\nclass Solution:\n def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int:\n ", "entry_point": "visiblePoints", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-one-bit-operations-to-make-integers-zero", "prompt": "# Given an integer `n`, you must transform it into `0` using the following operations any number of times:\n# Change the rightmost (`0th`) bit in the binary representation of `n`.\n# \n# Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.\n# \n# Return the minimum number of operations to transform `n` into `0`.\n# \n# \n# Example 1:\n# Input: n = 0\n# Output: 0\n# \n# Example 2:\n# Input: n = 3\n# Output: 2\n# Explanation: The binary representation of 3 is \"11\".\n# \n# \"11\" -> \"01\" with the 2nd operation since the 0th bit is 1.\n# \n# \"01\" -> \"00\" with the 1st operation.\n# \n# \n# Example 3:\n# Input: n = 6\n# Output: 4\n# Explanation: The binary representation of 6 is \"110\".\n# \n# \"110\" -> \"010\" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.\n# \n# \"010\" -> \"011\" with the 1st operation.\n# \n# \"011\" -> \"001\" with the 2nd operation since the 0th bit is 1.\n# \n# \"001\" -> \"000\" with the 1st operation.\n# \n# \n# Example 4:\n# Input: n = 9\n# Output: 14\n# \n# Example 5:\n# Input: n = 333\n# Output: 393\n# \n# Constraints:\n# `0 <= n <= 109`\nclass Solution:\n def minimumOneBitOperations(self, n: int) -> int:\n ", "entry_point": "minimumOneBitOperations", "cannonical_solution": "", "test": ""}
{"tast_id": "count-subtrees-with-max-distance-between-cities", "prompt": "# There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a tree.\n# \n# A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other.\n# \n# For each `d` from `1` to `n-1`, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to `d`.\n# \n# Return an array of size `n-1` where the `dth` element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to `d`.\n# \n# Notice that the distance between the two cities is the number of edges in the path between them.\n# \n# \n# Example 1:\n# Input: n = 4, edges = [[1,2],[2,3],[2,4]]\n# Output: [3,4,0]\n# Explanation:\n# The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.\n# \n# The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.\n# \n# No subtree has two nodes where the max distance between them is 3.\n# \n# \n# Example 2:\n# Input: n = 2, edges = [[1,2]]\n# Output: [1]\n# \n# Example 3:\n# Input: n = 3, edges = [[1,2],[2,3]]\n# Output: [2,1]\n# \n# Constraints:\n# `2 <= n <= 15`\n# `edges.length == n-1`\n# `edges[i].length == 2`\n# `1 <= ui, vi <= n`\n# All pairs `(ui, vi)` are distinct.\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n ", "entry_point": "countSubgraphsForEachDiameter", "cannonical_solution": "", "test": ""}
{"tast_id": "fancy-sequence", "prompt": "# Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations.\n# \n# Implement the `Fancy` class:\n# `Fancy()` Initializes the object with an empty sequence.\n# \n# `void append(val)` Appends an integer `val` to the end of the sequence.\n# \n# `void addAll(inc)` Increments all existing values in the sequence by an integer `inc`.\n# \n# `void multAll(m)` Multiplies all existing values in the sequence by an integer `m`.\n# \n# `int getIndex(idx)` Gets the current value at index `idx` (0-indexed) of the sequence modulo `109 + 7`. If the index is greater or equal than the length of the sequence, return `-1`.\n# \n# \n# Example 1:\n# Input\n# [\"Fancy\", \"append\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"getIndex\", \"getIndex\"]\n# [[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]\n# Output\n# [null, null, null, null, null, 10, null, null, null, 26, 34, 20]\n# Explanation\n# Fancy fancy = new Fancy();\n# fancy.append(2); // fancy sequence: [2]\n# fancy.addAll(3); // fancy sequence: [2+3] -> [5]\n# fancy.append(7); // fancy sequence: [5, 7]\n# fancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14]\n# fancy.getIndex(0); // return 10\n# fancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17]\n# fancy.append(10); // fancy sequence: [13, 17, 10]\n# fancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]\n# fancy.getIndex(0); // return 26\n# fancy.getIndex(1); // return 34\n# fancy.getIndex(2); // return 20\n# \n# Constraints:\n# `1 <= val, inc, m <= 100`\n# `0 <= idx <= 105`\n# At most `105` calls total will be made to `append`, `addAll`, `multAll`, and `getIndex`.\nclass Fancy:\n\n def __init__(self):\n \n\n def append(self, val: int) -> None:\n \n\n def addAll(self, inc: int) -> None:\n \n\n def multAll(self, m: int) -> None:\n \n\n def getIndex(self, idx: int) -> int:\n \n\n\n# Your Fancy object will be instantiated and called as such:\n# obj = Fancy()\n# obj.append(val)\n# obj.addAll(inc)\n# obj.multAll(m)\n# param_4 = obj.getIndex(idx)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "graph-connectivity-with-threshold", "prompt": "# We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor strictly greater than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an integer `z` such that all of the following are true:\n# `x % z == 0`,\n# `y % z == 0`, and\n# `z > threshold`.\n# \n# Given the two integers, `n` and `threshold`, and an array of `queries`, you must determine for each `queries[i] = [ai, bi]` if cities `ai` and `bi` are connected directly or indirectly. (i.e. there is some path between them).\n# \n# Return an array `answer`, where `answer.length == queries.length` and `answer[i]` is `true` if for the `ith` query, there is a path between `ai` and `bi`, or `answer[i]` is `false` if there is no path.\n# \n# \n# Example 1:\n# Input: n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]\n# Output: [false,false,true]\n# Explanation: The divisors for each number:\n# 1: 1\n# 2: 1, 2\n# 3: 1, 3\n# 4: 1, 2, 4\n# 5: 1, 5\n# 6: 1, 2, 3, 6\n# Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the\n# only ones directly connected. The result of each query:\n# [1,4] 1 is not connected to 4\n# [2,5] 2 is not connected to 5\n# [3,6] 3 is connected to 6 through path 3--6\n# \n# Example 2:\n# Input: n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]\n# Output: [true,true,true,true,true]\n# Explanation: The divisors for each number are the same as the previous example. However, since the threshold is 0,\n# all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.\n# \n# \n# Example 3:\n# Input: n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]\n# Output: [false,false,false,false,false]\n# Explanation: Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.\n# \n# Please notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].\n# \n# \n# Constraints:\n# `2 <= n <= 104`\n# `0 <= threshold <= n`\n# `1 <= queries.length <= 105`\n# `queries[i].length == 2`\n# `1 <= ai, bi <= cities`\n# `ai != bi`\nclass Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n ", "entry_point": "areConnected", "cannonical_solution": "", "test": ""}
{"tast_id": "rank-transform-of-a-matrix", "prompt": "# Given an `m x n` `matrix`, return a new matrix `answer` where `answer[row][col]` is the rank of `matrix[row][col]`.\n# \n# The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules:\n# The rank is an integer starting from `1`.\n# \n# If two elements `p` and `q` are in the same row or column, then:\n# \t\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# \n# It is guaranteed that `answer` is unique under the given rules.\n# \n# \n# Example 1:\n# Input: matrix = [[1,2],[3,4]]\n# Output: [[1,2],[2,3]]\n# Explanation:\n# The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.\n# \n# The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.\n# \n# The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.\n# \n# The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.\n# \n# \n# Example 2:\n# Input: matrix = [[7,7],[7,7]]\n# Output: [[1,1],[1,1]]\n# \n# Example 3:\n# Input: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]\n# Output: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]\n# \n# Example 4:\n# Input: matrix = [[7,3,6],[1,4,5],[9,8,2]]\n# Output: [[5,1,4],[1,2,3],[6,3,1]]\n# \n# Constraints:\n# `m == matrix.length`\n# `n == matrix[i].length`\n# `1 <= m, n <= 500`\n# `-109 <= matrix[row][col] <= 109`\nclass Solution:\n def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]:\n ", "entry_point": "matrixRankTransform", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-ways-to-form-a-target-string-given-a-dictionary", "prompt": "# You are given a list of strings of the same length `words` and a string `target`.\n# \n# Your task is to form `target` using the given `words` under the following rules:\n# `target` should be formed from left to right.\n# \n# To form the `ith` character (0-indexed) of `target`, you can choose the `kth` character of the `jth` string in `words` if `target[i] = words[j][k]`.\n# \n# Once you use the `kth` character of the `jth` string of `words`, you can no longer use the `xth` character of any string in `words` where `x <= k`. In other words, all characters to the left of or at index `k` become unusuable for every string.\n# \n# Repeat the process until you form the string `target`.\n# \n# Notice that you can use multiple characters from the same string in `words` provided the conditions above are met.\n# \n# Return the number of ways to form `target` from `words`. Since the answer may be too large, return it modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: words = [\"acca\",\"bbbb\",\"caca\"], target = \"aba\"\n# Output: 6\n# Explanation: There are 6 ways to form target.\n# \n# \"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"caca\")\n# \"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"caca\")\n# \"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"acca\")\n# \"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n# \"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n# \"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"caca\")\n# \n# Example 2:\n# Input: words = [\"abba\",\"baab\"], target = \"bab\"\n# Output: 4\n# Explanation: There are 4 ways to form target.\n# \n# \"bab\" -> index 0 (\"baab\"), index 1 (\"baab\"), index 2 (\"abba\")\n# \"bab\" -> index 0 (\"baab\"), index 1 (\"baab\"), index 3 (\"baab\")\n# \"bab\" -> index 0 (\"baab\"), index 2 (\"baab\"), index 3 (\"baab\")\n# \"bab\" -> index 1 (\"abba\"), index 2 (\"baab\"), index 3 (\"baab\")\n# \n# Example 3:\n# Input: words = [\"abcd\"], target = \"abcd\"\n# Output: 1\n# \n# Example 4:\n# Input: words = [\"abab\",\"baba\",\"abba\",\"baab\"], target = \"abba\"\n# Output: 16\n# \n# Constraints:\n# `1 <= words.length <= 1000`\n# `1 <= words[i].length <= 1000`\n# All strings in `words` have the same length.\n# \n# `1 <= target.length <= 1000`\n# `words[i]` and `target` contain only lowercase English letters.\nclass Solution:\n def numWays(self, words: List[str], target: str) -> int:\n ", "entry_point": "numWays", "cannonical_solution": "", "test": ""}
{"tast_id": "kth-smallest-instructions", "prompt": "# Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel right and down. You are going to help Bob by providing instructions for him to reach `destination`.\n# \n# The instructions are represented as a string, where each character is either:\n# `'H'`, meaning move horizontally (go right), or\n# `'V'`, meaning move vertically (go down).\n# \n# Multiple instructions will lead Bob to `destination`. For example, if `destination` is `(2, 3)`, both `\"HHHVV\"` and `\"HVHVH\"` are valid instructions.\n# \n# However, Bob is very picky. Bob has a lucky number `k`, and he wants the `kth` lexicographically smallest instructions that will lead him to `destination`. `k` is 1-indexed.\n# \n# Given an integer array `destination` and an integer `k`, return the `kth` lexicographically smallest instructions that will take Bob to `destination`.\n# \n# \n# Example 1:\n# Input: destination = [2,3], k = 1\n# Output: \"HHHVV\"\n# Explanation: All the instructions that reach (2, 3) in lexicographic order are as follows:\n# [\"HHHVV\", \"HHVHV\", \"HHVVH\", \"HVHHV\", \"HVHVH\", \"HVVHH\", \"VHHHV\", \"VHHVH\", \"VHVHH\", \"VVHHH\"].\n# \n# \n# Example 2:\n# Input: destination = [2,3], k = 2\n# Output: \"HHVHV\"\n# \n# Example 3:\n# Input: destination = [2,3], k = 3\n# Output: \"HHVVH\"\n# \n# Constraints:\n# `destination.length == 2`\n# `1 <= row, column <= 15`\n# `1 <= k <= nCr(row + column, row)`, where `nCr(a, b)` denotes `a` choose `b`\u200b\u200b\u200b\u200b\u200b.\nclass Solution:\n def kthSmallestPath(self, destination: List[int], k: int) -> str:\n ", "entry_point": "kthSmallestPath", "cannonical_solution": "", "test": ""}
{"tast_id": "create-sorted-array-through-instructions", "prompt": "# Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from left to right in `instructions`, insert it into `nums`. The cost of each insertion is the minimum of the following:\n# The number of elements currently in `nums` that are strictly less than `instructions[i]`.\n# \n# The number of elements currently in `nums` that are strictly greater than `instructions[i]`.\n# \n# For example, if inserting element `3` into `nums = [1,2,3,5]`, the cost of insertion is `min(2, 1)` (elements `1` and `2` are less than `3`, element `5` is greater than `3`) and `nums` will become `[1,2,3,3,5]`.\n# \n# Return the total cost to insert all elements from `instructions` into `nums`. Since the answer may be large, return it modulo `109 + 7`\n# \n# Example 1:\n# Input: instructions = [1,5,6,2]\n# Output: 1\n# Explanation: Begin with nums = [].\n# \n# Insert 1 with cost min(0, 0) = 0, now nums = [1].\n# \n# Insert 5 with cost min(1, 0) = 0, now nums = [1,5].\n# \n# Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6].\n# \n# Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].\n# \n# The total cost is 0 + 0 + 0 + 1 = 1.\n# \n# \n# Example 2:\n# Input: instructions = [1,2,3,6,5,4]\n# Output: 3\n# Explanation: Begin with nums = [].\n# \n# Insert 1 with cost min(0, 0) = 0, now nums = [1].\n# \n# Insert 2 with cost min(1, 0) = 0, now nums = [1,2].\n# \n# Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3].\n# \n# Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].\n# \n# Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].\n# \n# Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].\n# \n# The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.\n# \n# \n# Example 3:\n# Input: instructions = [1,3,3,3,2,4,2,1,2]\n# Output: 4\n# Explanation: Begin with nums = [].\n# \n# Insert 1 with cost min(0, 0) = 0, now nums = [1].\n# \n# Insert 3 with cost min(1, 0) = 0, now nums = [1,3].\n# \n# Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3].\n# \n# Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].\n# \n# Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].\n# \n# Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].\n# \n# \u200b\u200b\u200b\u200b\u200b\u200b\u200bInsert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].\n# \n# \u200b\u200b\u200b\u200b\u200b\u200b\u200bInsert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].\n# \n# \u200b\u200b\u200b\u200b\u200b\u200b\u200bInsert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].\n# \n# The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.\n# \n# \n# Constraints:\n# `1 <= instructions.length <= 105`\n# `1 <= instructions[i] <= 105`\nclass Solution:\n def createSortedArray(self, instructions: List[int]) -> int:\n ", "entry_point": "createSortedArray", "cannonical_solution": "", "test": ""}
{"tast_id": "distribute-repeating-integers", "prompt": "# You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that:\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# \n# Return `true` if it is possible to distribute `nums` according to the above conditions.\n# \n# \n# Example 1:\n# Input: nums = [1,2,3,4], quantity = [2]\n# Output: false\n# Explanation: The 0th customer cannot be given two different integers.\n# \n# \n# Example 2:\n# Input: nums = [1,2,3,3], quantity = [2]\n# Output: true\n# Explanation: The 0th customer is given [3,3]. The integers [1,2] are not used.\n# \n# \n# Example 3:\n# Input: nums = [1,1,2,2], quantity = [2,2]\n# Output: true\n# Explanation: The 0th customer is given [1,1], and the 1st customer is given [2,2].\n# \n# \n# Example 4:\n# Input: nums = [1,1,2,3], quantity = [2,2]\n# Output: false\n# Explanation: Although the 0th customer could be given [1,1], the 1st customer cannot be satisfied.\n# \n# \n# Example 5:\n# Input: nums = [1,1,1,1,1], quantity = [2,3]\n# Output: true\n# Explanation: The 0th customer is given [1,1], and the 1st customer is given [1,1,1].\n# \n# \n# Constraints:\n# `n == nums.length`\n# `1 <= n <= 105`\n# `1 <= nums[i] <= 1000`\n# `m == quantity.length`\n# `1 <= m <= 10`\n# `1 <= quantity[i] <= 105`\n# There are at most `50` unique values in `nums`.\nclass Solution:\n def canDistribute(self, nums: List[int], quantity: List[int]) -> bool:\n ", "entry_point": "canDistribute", "cannonical_solution": "", "test": ""}
{"tast_id": "maximize-grid-happiness", "prompt": "# You are given four integers, `m`, `n`, `introvertsCount`, and `extrovertsCount`. You have an `m x n` grid, and there are two types of people: introverts and extroverts. There are `introvertsCount` introverts and `extrovertsCount` extroverts.\n# \n# You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid.\n# \n# The happiness of each person is calculated as follows:\n# Introverts start with `120` happiness and lose `30` happiness for each neighbor (introvert or extrovert).\n# \n# Extroverts start with `40` happiness and gain `20` happiness for each neighbor (introvert or extrovert).\n# \n# Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell.\n# \n# The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness.\n# \n# \n# Example 1:\n# Input: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2\n# Output: 240\n# Explanation: Assume the grid is 1-indexed with coordinates (row, column).\n# \n# We can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).\n# \n# - Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120\n# - Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\n# - Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\n# The grid happiness is 120 + 60 + 60 = 240.\n# \n# The above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.\n# \n# \n# Example 2:\n# Input: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1\n# Output: 260\n# Explanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).\n# \n# - Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\n# - Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80\n# - Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\n# The grid happiness is 90 + 80 + 90 = 260.\n# \n# \n# Example 3:\n# Input: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0\n# Output: 240\n# \n# Constraints:\n# `1 <= m, n <= 5`\n# `0 <= introvertsCount, extrovertsCount <= min(m * n, 6)`\nclass Solution:\n def getMaxGridHappiness(self, m: int, n: int, introvertsCount: int, extrovertsCount: int) -> int:\n ", "entry_point": "getMaxGridHappiness", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-initial-energy-to-finish-tasks", "prompt": "# You are given an array `tasks` where `tasks[i] = [actuali, minimumi]`:\n# `actuali` is the actual amount of energy you spend to finish the `ith` task.\n# \n# `minimumi` is the minimum amount of energy you require to begin the `ith` task.\n# \n# For example, if the task is `[10, 12]` and your current energy is `11`, you cannot start this task. However, if your current energy is `13`, you can complete this task, and your energy will be `3` after finishing it.\n# \n# You can finish the tasks in any order you like.\n# \n# Return the minimum initial amount of energy you will need to finish all the tasks.\n# \n# \n# Example 1:\n# Input: tasks = [[1,2],[2,4],[4,8]]\n# Output: 8\n# Explanation:\n# Starting with 8 energy, we finish the tasks in the following order:\n# - 3rd task. Now energy = 8 - 4 = 4.\n# \n# - 2nd task. Now energy = 4 - 2 = 2.\n# \n# - 1st task. Now energy = 2 - 1 = 1.\n# \n# Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.\n# \n# \n# Example 2:\n# Input: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]\n# Output: 32\n# Explanation:\n# Starting with 32 energy, we finish the tasks in the following order:\n# - 1st task. Now energy = 32 - 1 = 31.\n# \n# - 2nd task. Now energy = 31 - 2 = 29.\n# \n# - 3rd task. Now energy = 29 - 10 = 19.\n# \n# - 4th task. Now energy = 19 - 10 = 9.\n# \n# - 5th task. Now energy = 9 - 8 = 1.\n# \n# \n# Example 3:\n# Input: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]\n# Output: 27\n# Explanation:\n# Starting with 27 energy, we finish the tasks in the following order:\n# - 5th task. Now energy = 27 - 5 = 22.\n# \n# - 2nd task. Now energy = 22 - 2 = 20.\n# \n# - 3rd task. Now energy = 20 - 3 = 17.\n# \n# - 1st task. Now energy = 17 - 1 = 16.\n# \n# - 4th task. Now energy = 16 - 4 = 12.\n# \n# - 6th task. Now energy = 12 - 6 = 6.\n# \n# \n# Constraints:\n# `1 <= tasks.length <= 105`\n# `1 <= actual\u200bi <= minimumi <= 104`\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n ", "entry_point": "minimumEffort", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-number-of-removals-to-make-mountain-array", "prompt": "# You may recall that an array `arr` is a mountain array if and only if:\n# `arr.length >= 3`\n# There exists some index `i` (0-indexed) with `0 < i < arr.length - 1` such that:\n# \t\n# `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`\n# `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`\n# Given an integer array `nums`\u200b\u200b\u200b, return the minimum number of elements to remove to make `nums\u200b\u200b\u200b` a mountain array.\n# \n# \n# Example 1:\n# Input: nums = [1,3,1]\n# Output: 0\n# Explanation: The array itself is a mountain array so we do not need to remove any elements.\n# \n# \n# Example 2:\n# Input: nums = [2,1,1,5,6,2,3,1]\n# Output: 3\n# Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].\n# \n# \n# Example 3:\n# Input: nums = [4,3,2,1,1,2,3,1]\n# Output: 4\n# \n# Example 4:\n# Input: nums = [1,2,3,4,4,3,2,1]\n# Output: 1\n# \n# Constraints:\n# `3 <= nums.length <= 1000`\n# `1 <= nums[i] <= 109`\n# It is guaranteed that you can make a mountain array out of `nums`.\nclass Solution:\n def minimumMountainRemovals(self, nums: List[int]) -> int:\n ", "entry_point": "minimumMountainRemovals", "cannonical_solution": "", "test": ""}
{"tast_id": "minimize-deviation-in-array", "prompt": "# You are given an array `nums` of `n` positive integers.\n# \n# You can perform two types of operations on any element of the array any number of times:\n# If the element is even, divide it by `2`.\n# \n# \t\n# For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].`\n# If the element is odd, multiply it by `2`.\n# \n# \t\n# For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].`\n# The deviation of the array is the maximum difference between any two elements in the array.\n# \n# Return the minimum deviation the array can have after performing some number of operations.\n# \n# \n# Example 1:\n# Input: nums = [1,2,3,4]\n# Output: 1\n# Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.\n# \n# \n# Example 2:\n# Input: nums = [4,1,5,20,3]\n# Output: 3\n# Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.\n# \n# \n# Example 3:\n# Input: nums = [2,10,8]\n# Output: 3\n# \n# Constraints:\n# `n == nums.length`\n# `2 <= n <= 105`\n# `1 <= nums[i] <= 109`\nclass Solution:\n def minimumDeviation(self, nums: List[int]) -> int:\n ", "entry_point": "minimumDeviation", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-incompatibility", "prompt": "# You are given an integer array `nums`\u200b\u200b\u200b and an integer `k`. You are asked to distribute this array into `k` subsets of equal size such that there are no two equal elements in the same subset.\n# \n# A subset's incompatibility is the difference between the maximum and minimum elements in that array.\n# \n# Return the minimum possible sum of incompatibilities of the `k` subsets after distributing the array optimally, or return `-1` if it is not possible.\n# \n# A subset is a group integers that appear in the array with no particular order.\n# \n# \n# Example 1:\n# Input: nums = [1,2,1,4], k = 2\n# Output: 4\n# Explanation: The optimal distribution of subsets is [1,2] and [1,4].\n# \n# The incompatibility is (2-1) + (4-1) = 4.\n# \n# Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.\n# \n# \n# Example 2:\n# Input: nums = [6,3,8,1,3,1,2,2], k = 4\n# Output: 6\n# Explanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].\n# \n# The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.\n# \n# \n# Example 3:\n# Input: nums = [5,3,3,6,3,3], k = 3\n# Output: -1\n# Explanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.\n# \n# \n# Constraints:\n# `1 <= k <= nums.length <= 16`\n# `nums.length` is divisible by `k`\n# `1 <= nums[i] <= nums.length`\nclass Solution:\n def minimumIncompatibility(self, nums: List[int], k: int) -> int:\n ", "entry_point": "minimumIncompatibility", "cannonical_solution": "", "test": ""}
{"tast_id": "delivering-boxes-from-storage-to-ports", "prompt": "# You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry.\n# \n# You are given an array `boxes`, where `boxes[i] = [ports\u200b\u200bi\u200b, weighti]`, and three 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# \n# `portsCount` is the number of ports.\n# \n# `maxBoxes` and `maxWeight` are the respective box and weight limits of the ship.\n# \n# The boxes need to be delivered in the order they are given. The ship will follow these steps:\n# The ship will take some number of boxes from the `boxes` queue, not violating the `maxBoxes` and `maxWeight` constraints.\n# \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# \n# The ship then makes a return trip to storage to take more boxes from the queue.\n# \n# The ship must end at storage after all the boxes have been delivered.\n# \n# Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.\n# \n# \n# Example 1:\n# Input: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3\n# Output: 4\n# Explanation: The optimal strategy is as follows: \n# - The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.\n# \n# So the total number of trips is 4.\n# \n# Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).\n# \n# \n# Example 2:\n# Input: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6\n# Output: 6\n# Explanation: The optimal strategy is as follows: \n# - The ship takes the first box, goes to port 1, then returns to storage. 2 trips.\n# \n# - The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.\n# \n# - The ship takes the fifth box, goes to port 3, then returns to storage. 2 trips.\n# \n# So the total number of trips is 2 + 2 + 2 = 6.\n# \n# \n# Example 3:\n# Input: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7\n# Output: 6\n# Explanation: The optimal strategy is as follows:\n# - The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.\n# \n# - The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.\n# \n# - The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.\n# \n# So the total number of trips is 2 + 2 + 2 = 6.\n# \n# \n# Example 4:\n# Input: boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]], portsCount = 5, maxBoxes = 5, maxWeight = 7\n# Output: 14\n# Explanation: The optimal strategy is as follows:\n# - The ship takes the first box, goes to port 2, then storage. 2 trips.\n# \n# - The ship takes the second box, goes to port 2, then storage. 2 trips.\n# \n# - The ship takes the third and fourth boxes, goes to port 3, then storage. 2 trips.\n# \n# - The ship takes the fifth box, goes to port 3, then storage. 2 trips.\n# \n# - The ship takes the sixth and seventh boxes, goes to port 3, then port 4, then storage. 3 trips. \n# - The ship takes the eighth and ninth boxes, goes to port 1, then port 5, then storage. 3 trips.\n# \n# So the total number of trips is 2 + 2 + 2 + 2 + 3 + 3 = 14.\n# \n# \n# Constraints:\n# `1 <= boxes.length <= 105`\n# `1 <= portsCount, maxBoxes, maxWeight <= 105`\n# `1 <= ports\u200b\u200bi <= portsCount`\n# `1 <= weightsi <= maxWeight`\nclass Solution:\n def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int:\n ", "entry_point": "boxDelivering", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-height-by-stacking-cuboids", "prompt": "# Given `n` `cuboids` where the dimensions of the `ith` cuboid is `cuboids[i] = [widthi, lengthi, heighti]` (0-indexed). Choose a subset of `cuboids` and place them on each other.\n# \n# You can place cuboid `i` on cuboid `j` if `widthi <= widthj` and `lengthi <= lengthj` and `heighti <= heightj`. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid.\n# \n# Return the maximum height of the stacked `cuboids`.\n# \n# \n# Example 1:\n# Input: cuboids = [[50,45,20],[95,37,53],[45,23,12]]\n# Output: 190\n# Explanation:\n# Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.\n# \n# Cuboid 0 is placed next with the 45x20 side facing down with height 50.\n# \n# Cuboid 2 is placed next with the 23x12 side facing down with height 45.\n# \n# The total height is 95 + 50 + 45 = 190.\n# \n# \n# Example 2:\n# Input: cuboids = [[38,25,45],[76,35,3]]\n# Output: 76\n# Explanation:\n# You can't place any of the cuboids on the other.\n# \n# We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.\n# \n# \n# Example 3:\n# Input: cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]\n# Output: 102\n# Explanation:\n# After rearranging the cuboids, you can see that all cuboids have the same dimension.\n# \n# You can place the 11x7 side down on all cuboids so their heights are 17.\n# \n# The maximum height of stacked cuboids is 6 * 17 = 102.\n# \n# \n# Constraints:\n# `n == cuboids.length`\n# `1 <= n <= 100`\n# `1 <= widthi, lengthi, heighti <= 100`\nclass Solution:\n def maxHeight(self, cuboids: List[List[int]]) -> int:\n ", "entry_point": "maxHeight", "cannonical_solution": "", "test": ""}
{"tast_id": "checking-existence-of-edge-length-limited-paths", "prompt": "# An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be multiple edges between two nodes.\n# \n# Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for each `queries[j]` whether there is a path between `pj` and `qj` such that each edge on the path has a distance strictly less than `limitj` .\n# \n# Return a boolean array `answer`, where `answer.length == queries.length` and the `jth` value of `answer` is `true` if there is a path for `queries[j]` is `true`, and `false` otherwise.\n# \n# \n# Example 1:\n# Input: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]\n# Output: [false,true]\n# Explanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.\n# \n# For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.\n# \n# For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.\n# \n# \n# Example 2:\n# Input: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]\n# Output: [true,false]\n# Exaplanation: The above figure shows the given graph.\n# \n# \n# Constraints:\n# `2 <= n <= 105`\n# `1 <= edgeList.length, queries.length <= 105`\n# `edgeList[i].length == 3`\n# `queries[j].length == 3`\n# `0 <= ui, vi, pj, qj <= n - 1`\n# `ui != vi`\n# `pj != qj`\n# `1 <= disi, limitj <= 109`\n# There may be multiple edges between two nodes.\nclass Solution:\n def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:\n ", "entry_point": "distanceLimitedPathsExist", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-adjacent-swaps-for-k-consecutive-ones", "prompt": "# You are given an integer array, `nums`, and an integer `k`. `nums` comprises of only `0`'s and `1`'s. In one move, you can choose two adjacent indices and swap their values.\n# \n# Return the minimum number of moves required so that `nums` has `k` consecutive `1`'s.\n# \n# \n# Example 1:\n# Input: nums = [1,0,0,1,0,1], k = 2\n# Output: 1\n# Explanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.\n# \n# \n# Example 2:\n# Input: nums = [1,0,0,0,0,0,1,1], k = 3\n# Output: 5\n# Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].\n# \n# \n# Example 3:\n# Input: nums = [1,1,0,1], k = 2\n# Output: 0\n# Explanation: nums already has 2 consecutive 1's.\n# \n# \n# Constraints:\n# `1 <= nums.length <= 105`\n# `nums[i]` is `0` or `1`.\n# \n# `1 <= k <= sum(nums)`\nclass Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n ", "entry_point": "minMoves", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-xor-with-an-element-from-array", "prompt": "# You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`.\n# \n# The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for all `j` such that `nums[j] <= mi`. If all elements in `nums` are larger than `mi`, then the answer is `-1`.\n# \n# Return an integer array `answer` where `answer.length == queries.length` and `answer[i]` is the answer to the `ith` query.\n# \n# \n# Example 1:\n# Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]\n# Output: [3,3,7]\n# Explanation:\n# 1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.\n# \n# 2) 1 XOR 2 = 3.\n# \n# 3) 5 XOR 2 = 7.\n# \n# \n# Example 2:\n# Input: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]\n# Output: [15,-1,5]\n# \n# Constraints:\n# `1 <= nums.length, queries.length <= 105`\n# `queries[i].length == 2`\n# `0 <= nums[j], xi, mi <= 109`\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n ", "entry_point": "maximizeXor", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-operations-to-make-a-subsequence", "prompt": "# You are given an array `target` that consists of distinct integers and another integer array `arr` that can have duplicates.\n# \n# In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array.\n# \n# Return the minimum number of operations needed to make `target` a subsequence of `arr`.\n# \n# A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not.\n# \n# \n# Example 1:\n# Input: target = [5,1,3], `arr` = [9,4,2,3,4]\n# Output: 2\n# Explanation: You can add 5 and 1 in such a way that makes `arr` = [5,9,4,1,2,3,4], then target will be a subsequence of `arr`.\n# \n# \n# Example 2:\n# Input: target = [6,4,8,1,3,2], `arr` = [4,7,6,2,3,8,6,1]\n# Output: 3\n# \n# Constraints:\n# `1 <= target.length, arr.length <= 105`\n# `1 <= target[i], arr[i] <= 109`\n# `target` contains no duplicates.\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n ", "entry_point": "minOperations", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-ways-to-reconstruct-a-tree", "prompt": "# You are given an array `pairs`, where `pairs[i] = [xi, yi]`, and:\n# There are no duplicates.\n# \n# `xi < yi`\n# Let `ways` be the number of rooted trees that satisfy the following conditions:\n# The tree consists of nodes whose values appeared in `pairs`.\n# \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# \n# Note: the tree does not have to be a binary tree.\n# \n# Two ways are considered to be different if there is at least one node that has different parents in both ways.\n# \n# Return:\n# `0` if `ways == 0`\n# `1` if `ways == 1`\n# `2` if `ways > 1`\n# A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root.\n# \n# An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.\n# \n# \n# Example 1:\n# Input: pairs = [[1,2],[2,3]]\n# Output: 1\n# Explanation: There is exactly one valid rooted tree, which is shown in the above figure.\n# \n# \n# Example 2:\n# Input: pairs = [[1,2],[2,3],[1,3]]\n# Output: 2\n# Explanation: There are multiple valid rooted trees. Three of them are shown in the above figures.\n# \n# \n# Example 3:\n# Input: pairs = [[1,2],[2,3],[2,4],[1,5]]\n# Output: 0\n# Explanation: There are no valid rooted trees.\n# \n# \n# Constraints:\n# `1 <= pairs.length <= 105`\n# `1 <= xi < yi <= 500`\n# The elements in `pairs` are unique.\nclass Solution:\n def checkWays(self, pairs: List[List[int]]) -> int:\n ", "entry_point": "checkWays", "cannonical_solution": "", "test": ""}
{"tast_id": "find-minimum-time-to-finish-all-jobs", "prompt": "# You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job.\n# \n# There are `k` workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized.\n# \n# Return the minimum possible maximum working time of any assignment. \n# \n# Example 1:\n# Input: jobs = [3,2,3], k = 3\n# Output: 3\n# Explanation: By assigning each person one job, the maximum time is 3.\n# \n# \n# Example 2:\n# Input: jobs = [1,2,4,7,8], k = 2\n# Output: 11\n# Explanation: Assign the jobs the following way:\n# Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\n# Worker 2: 4, 7 (working time = 4 + 7 = 11)\n# The maximum working time is 11.\n# \n# \n# Constraints:\n# `1 <= k <= jobs.length <= 12`\n# `1 <= jobs[i] <= 107`\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n ", "entry_point": "minimumTimeRequired", "cannonical_solution": "", "test": ""}
{"tast_id": "cat-and-mouse-ii", "prompt": "# A game is played by a cat and a mouse named Cat and Mouse.\n# \n# The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food.\n# \n# Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse).\n# \n# Floors are represented by the character `'.'` and can be walked on.\n# \n# Walls are represented by the character `'#'` and cannot be walked on.\n# \n# Food is represented by the character `'F'` and can be walked on.\n# \n# There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.\n# \n# Mouse and Cat play according to the following rules:\n# Mouse moves first, then they take turns to move.\n# \n# During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`.\n# \n# `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.\n# \n# Staying in the same position is allowed.\n# \n# Mouse can jump over Cat.\n# \n# The game can end in 4 ways:\n# If Cat occupies the same position as Mouse, Cat wins.\n# \n# If Cat reaches the food first, Cat wins.\n# \n# If Mouse reaches the food first, Mouse wins.\n# \n# If Mouse cannot get to the food within 1000 turns, Cat wins.\n# \n# Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` if Mouse can win the game if both Cat and Mouse play optimally, otherwise return `false`.\n# \n# \n# Example 1:\n# Input: grid = [\"####F\",\"#C...\",\"M....\"], catJump = 1, mouseJump = 2\n# Output: true\n# Explanation: Cat cannot catch Mouse on its turn nor can it get the food before Mouse.\n# \n# \n# Example 2:\n# Input: grid = [\"M.C...F\"], catJump = 1, mouseJump = 4\n# Output: true\n# \n# Example 3:\n# Input: grid = [\"M.C...F\"], catJump = 1, mouseJump = 3\n# Output: false\n# \n# Example 4:\n# Input: grid = [\"C...#\",\"...#F\",\"....#\",\"M....\"], catJump = 2, mouseJump = 5\n# Output: false\n# \n# Example 5:\n# Input: grid = [\".M...\",\"..#..\",\"#..#.\",\"C#.#.\",\"...#F\"], catJump = 3, mouseJump = 1\n# Output: true\n# \n# Constraints:\n# `rows == grid.length`\n# `cols = grid[i].length`\n# `1 <= rows, cols <= 8`\n# `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`.\n# \n# There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.\n# \n# `1 <= catJump, mouseJump <= 8`\nclass Solution:\n def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:\n ", "entry_point": "canMouseWin", "cannonical_solution": "", "test": ""}
{"tast_id": "count-ways-to-make-array-with-product", "prompt": "# You are given a 2D integer array, `queries`. For each `queries[i]`, where `queries[i] = [ni, ki]`, find the number of different ways you can place positive integers into an array of size `ni` such that the product of the integers is `ki`. As the number of ways may be too large, the answer to the `ith` query is the number of ways modulo `109 + 7`.\n# \n# Return an integer array `answer` where `answer.length == queries.length`, and `answer[i]` is the answer to the `ith` query.\n# \n# \n# Example 1:\n# Input: queries = [[2,6],[5,1],[73,660]]\n# Output: [4,1,50734910]\n# Explanation: Each query is independent.\n# \n# [2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].\n# \n# [5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].\n# \n# [73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910.\n# \n# \n# Example 2:\n# Input: queries = [[1,1],[2,2],[3,3],[4,4],[5,5]]\n# Output: [1,2,3,10,5]\n# \n# Constraints:\n# `1 <= queries.length <= 104 `\n# `1 <= ni, ki <= 104`\nclass Solution:\n def waysToFillArray(self, queries: List[List[int]]) -> List[int]:\n ", "entry_point": "waysToFillArray", "cannonical_solution": "", "test": ""}
{"tast_id": "building-boxes", "prompt": "# You have a cubic storeroom where the width, length, and height of the room are all equal to `n` units. You are asked to place `n` boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:\n# You can place the boxes anywhere on the floor.\n# \n# If box `x` is placed on top of the box `y`, then each side of the four vertical sides of the box `y` must either be adjacent to another box or to a wall.\n# \n# Given an integer `n`, return the minimum possible number of boxes touching the floor.\n# \n# \n# Example 1:\n# Input: n = 3\n# Output: 3\n# Explanation: The figure above is for the placement of the three boxes.\n# \n# These boxes are placed in the corner of the room, where the corner is on the left side.\n# \n# \n# Example 2:\n# Input: n = 4\n# Output: 3\n# Explanation: The figure above is for the placement of the four boxes.\n# \n# These boxes are placed in the corner of the room, where the corner is on the left side.\n# \n# \n# Example 3:\n# Input: n = 10\n# Output: 6\n# Explanation: The figure above is for the placement of the ten boxes.\n# \n# These boxes are placed in the corner of the room, where the corner is on the back side.\n# \n# \n# Constraints:\n# `1 <= n <= 109`\nclass Solution:\n def minimumBoxes(self, n: int) -> int:\n ", "entry_point": "minimumBoxes", "cannonical_solution": "", "test": ""}
{"tast_id": "palindrome-partitioning-iv", "prompt": "# Given a string `s`, return `true` if it is possible to split the string `s` into three non-empty palindromic substrings. Otherwise, return `false`.\u200b\u200b\u200b\u200b\u200b\n# A string is said to be palindrome if it the same string when reversed.\n# \n# \n# Example 1:\n# Input: s = \"abcbdd\"\n# Output: true\n# Explanation: \"abcbdd\" = \"a\" + \"bcb\" + \"dd\", and all three substrings are palindromes.\n# \n# \n# Example 2:\n# Input: s = \"bcbddxy\"\n# Output: false\n# Explanation: s cannot be split into 3 palindromes.\n# \n# \n# Constraints:\n# `3 <= s.length <= 2000`\n# `s`\u200b\u200b\u200b\u200b\u200b\u200b consists only of lowercase English letters.\nclass Solution:\n def checkPartitioning(self, s: str) -> bool:\n ", "entry_point": "checkPartitioning", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-number-of-events-that-can-be-attended-ii", "prompt": "# You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend.\n# \n# You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.\n# \n# Return the maximum sum of values that you can receive by attending events.\n# \n# \n# Example 1:\n# Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2\n# Output: 7\n# Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.\n# \n# \n# Example 2:\n# Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2\n# Output: 10\n# Explanation: Choose event 2 for a total value of 10.\n# \n# Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events.\n# \n# \n# Example 3:\n# Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3\n# Output: 9\n# Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.\n# \n# \n# Constraints:\n# `1 <= k <= events.length`\n# `1 <= k * events.length <= 106`\n# `1 <= startDayi <= endDayi <= 109`\n# `1 <= valuei <= 106`\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n ", "entry_point": "maxValue", "cannonical_solution": "", "test": ""}
{"tast_id": "closest-subsequence-sum", "prompt": "# You are given an integer array `nums` and an integer `goal`.\n# \n# You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to minimize the absolute difference `abs(sum - goal)`.\n# \n# Return the minimum possible value of `abs(sum - goal)`.\n# \n# Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.\n# \n# \n# Example 1:\n# Input: nums = [5,-7,3,5], goal = 6\n# Output: 0\n# Explanation: Choose the whole array as a subsequence, with a sum of 6.\n# \n# This is equal to the goal, so the absolute difference is 0.\n# \n# \n# Example 2:\n# Input: nums = [7,-9,15,-2], goal = -5\n# Output: 1\n# Explanation: Choose the subsequence [7,-9,-2], with a sum of -4.\n# \n# The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.\n# \n# \n# Example 3:\n# Input: nums = [1,2,3], goal = -7\n# Output: 7\n# \n# Constraints:\n# `1 <= nums.length <= 40`\n# `-107 <= nums[i] <= 107`\n# `-109 <= goal <= 109`\nclass Solution:\n def minAbsDifference(self, nums: List[int], goal: int) -> int:\n ", "entry_point": "minAbsDifference", "cannonical_solution": "", "test": ""}
{"tast_id": "minimum-degree-of-a-connected-trio-in-a-graph", "prompt": "# You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.\n# \n# A connected trio is a set of three nodes where there is an edge between every pair of them.\n# \n# The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not.\n# \n# Return the minimum degree of a connected trio in the graph, or `-1` if the graph has no connected trios.\n# \n# \n# Example 1:\n# Input: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]\n# Output: 3\n# Explanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above.\n# \n# \n# Example 2:\n# Input: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]\n# Output: 0\n# Explanation: There are exactly three trios:\n# 1) [1,4,3] with degree 0.\n# \n# 2) [2,5,6] with degree 2.\n# \n# 3) [5,6,7] with degree 2.\n# \n# \n# Constraints:\n# `2 <= n <= 400`\n# `edges[i].length == 2`\n# `1 <= edges.length <= n * (n-1) / 2`\n# `1 <= ui, vi <= n`\n# `ui != vi`\n# There are no repeated edges.\nclass Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n ", "entry_point": "minTrioDegree", "cannonical_solution": "", "test": ""}
{"tast_id": "tree-of-coprimes", "prompt": "# There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` edges. Each node has a value associated with it, and the root of the tree is node `0`.\n# \n# To represent this tree, you are given an integer array `nums` and a 2D array `edges`. Each `nums[i]` represents the `ith` node's value, and each `edges[j] = [uj, vj]` represents an edge between nodes `uj` and `vj` in the tree.\n# \n# Two values `x` and `y` are coprime if `gcd(x, y) == 1` where `gcd(x, y)` is the greatest common divisor of `x` and `y`.\n# \n# An ancestor of a node `i` is any other node on the shortest path from node `i` to the root. A node is not considered an ancestor of itself.\n# \n# Return an array `ans` of size `n`, where `ans[i]` is the closest ancestor to node `i` such that `nums[i]` and `nums[ans[i]]` are coprime, or `-1` if there is no such ancestor.\n# \n# \n# Example 1:\n# Input: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]\n# Output: [-1,0,0,1]\n# Explanation: In the above figure, each node's value is in parentheses.\n# \n# - Node 0 has no coprime ancestors.\n# \n# - Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).\n# \n# - Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's\n# value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.\n# \n# - Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its\n# closest valid ancestor.\n# \n# \n# Example 2:\n# Input: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]\n# Output: [-1,0,-1,0,0,0,-1]\n# \n# Constraints:\n# `nums.length == n`\n# `1 <= nums[i] <= 50`\n# `1 <= n <= 105`\n# `edges.length == n - 1`\n# `edges[j].length == 2`\n# `0 <= uj, vj < n`\n# `uj != vj`\nclass Solution:\n def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]:\n ", "entry_point": "getCoprimes", "cannonical_solution": "", "test": ""}
{"tast_id": "maximize-palindrome-length-from-subsequences", "prompt": "# You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:\n# Choose some non-empty subsequence `subsequence1` from `word1`.\n# \n# Choose some non-empty subsequence `subsequence2` from `word2`.\n# \n# Concatenate the subsequences: `subsequence1 + subsequence2`, to make the string.\n# \n# Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return `0`.\n# \n# A subsequence of a string `s` is a string that can be made by deleting some (possibly none) characters from `s` without changing the order of the remaining characters.\n# \n# A palindrome is a string that reads the same forward as well as backward.\n# \n# \n# Example 1:\n# Input: word1 = \"cacb\", word2 = \"cbba\"\n# Output: 5\n# Explanation: Choose \"ab\" from word1 and \"cba\" from word2 to make \"abcba\", which is a palindrome.\n# \n# \n# Example 2:\n# Input: word1 = \"ab\", word2 = \"ab\"\n# Output: 3\n# Explanation: Choose \"ab\" from word1 and \"a\" from word2 to make \"aba\", which is a palindrome.\n# \n# \n# Example 3:\n# Input: word1 = \"aa\", word2 = \"bb\"\n# Output: 0\n# Explanation: You cannot construct a palindrome from the described method, so return 0.\n# \n# \n# Constraints:\n# `1 <= word1.length, word2.length <= 1000`\n# `word1` and `word2` consist of lowercase English letters.\nclass Solution:\n def longestPalindrome(self, word1: str, word2: str) -> int:\n ", "entry_point": "longestPalindrome", "cannonical_solution": "", "test": ""}
{"tast_id": "car-fleet-ii", "prompt": "# There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where `cars[i] = [positioni, speedi]` represents:\n# `positioni` is the distance between the `ith` car and the beginning of the road in meters. It is guaranteed that `positioni < positioni+1`.\n# \n# `speedi` is the initial speed of the `ith` car in meters per second.\n# \n# For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet.\n# \n# Return an array `answer`, where `answer[i]` is the time, in seconds, at which the `ith` car collides with the next car, or `-1` if the car does not collide with the next car. Answers within `10-5` of the actual answers are accepted.\n# \n# \n# Example 1:\n# Input: cars = [[1,2],[2,1],[4,3],[7,2]]\n# Output: [1.00000,-1.00000,3.00000,-1.00000]\n# Explanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.\n# \n# \n# Example 2:\n# Input: cars = [[3,4],[5,4],[6,3],[9,1]]\n# Output: [2.00000,1.00000,1.50000,-1.00000]\n# \n# Constraints:\n# `1 <= cars.length <= 105`\n# `1 <= positioni, speedi <= 106`\n# `positioni < positioni+1`\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n ", "entry_point": "getCollisionTimes", "cannonical_solution": "", "test": ""}
{"tast_id": "count-pairs-of-nodes", "prompt": "# You are given an undirected graph represented by an integer `n`, which is the number of nodes, and `edges`, where `edges[i] = [ui, vi]` which indicates that there is an undirected edge between `ui` and `vi`. You are also given an integer array `queries`.\n# \n# The answer to the `jth` query is the number of pairs of nodes `(a, b)` that satisfy the following conditions:\n# `a < b`\n# `cnt` is strictly greater than `queries[j]`, where `cnt` is the number of edges incident to `a` or `b`.\n# \n# Return an array `answers` such that `answers.length == queries.length` and `answers[j]` is the answer of the `jth` query.\n# \n# Note that there can be repeated edges.\n# \n# \n# Example 1:\n# Input: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]\n# Output: [6,5]\n# Explanation: The number of edges incident to at least one of each pair is shown above.\n# \n# \n# Example 2:\n# Input: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]\n# Output: [10,10,9,8,6]\n# \n# Constraints:\n# `2 <= n <= 2 * 104`\n# `1 <= edges.length <= 105`\n# `1 <= ui, vi <= n`\n# `ui != vi`\n# `1 <= queries.length <= 20`\n# `0 <= queries[j] < edges.length`\nclass Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n ", "entry_point": "countPairs", "cannonical_solution": "", "test": ""}
{"tast_id": "make-the-xor-of-all-segments-equal-to-zero", "prompt": "# You are given an array `nums`\u200b\u200b\u200b and an integer `k`\u200b\u200b\u200b\u200b\u200b. The XOR of a segment `[left, right]` where `left <= right` is the `XOR` of all the elements with indices between `left` and `right`, inclusive: `nums[left] XOR nums[left+1] XOR ... XOR nums[right]`.\n# \n# Return the minimum number of elements to change in the array such that the `XOR` of all segments of size `k`\u200b\u200b\u200b\u200b\u200b\u200b is equal to zero.\n# \n# \n# Example 1:\n# Input: nums = [1,2,0,3,0], k = 1\n# Output: 3\n# Explanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0].\n# \n# \n# Example 2:\n# Input: nums = [3,4,5,2,1,7,3,4,7], k = 3\n# Output: 3\n# Explanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7].\n# \n# \n# Example 3:\n# Input: nums = [1,2,4,1,2,5,1,2,6], k = 3\n# Output: 3\n# Explanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].\n# \n# \n# Constraints:\n# `1 <= k <= nums.length <= 2000`\n# `\u200b\u200b\u200b\u200b\u200b\u200b0 <= nums[i] < 210`\nclass Solution:\n def minChanges(self, nums: List[int], k: int) -> int:\n ", "entry_point": "minChanges", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-score-of-a-good-subarray", "prompt": "# You are given an array of integers `nums` (0-indexed) and an integer `k`.\n# \n# The score of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A good subarray is a subarray where `i <= k <= j`.\n# \n# Return the maximum possible score of a good subarray.\n# \n# \n# Example 1:\n# Input: nums = [1,4,3,7,4,5], k = 3\n# Output: 15\n# Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. \n# \n# Example 2:\n# Input: nums = [5,5,4,5,4,1,1,1], k = 0\n# Output: 20\n# Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.\n# \n# \n# Constraints:\n# `1 <= nums.length <= 105`\n# `1 <= nums[i] <= 2 * 104`\n# `0 <= k < nums.length`\nclass Solution:\n def maximumScore(self, nums: List[int], k: int) -> int:\n ", "entry_point": "maximumScore", "cannonical_solution": "", "test": ""}
{"tast_id": "maximize-score-after-n-operations", "prompt": "# You are given `nums`, an array of positive integers of size `2 * n`. You must perform `n` operations on this array.\n# \n# In the `ith` operation (1-indexed), you will:\n# Choose two elements, `x` and `y`.\n# \n# Receive a score of `i * gcd(x, y)`.\n# \n# Remove `x` and `y` from `nums`.\n# \n# Return the maximum score you can receive after performing `n` operations.\n# \n# The function `gcd(x, y)` is the greatest common divisor of `x` and `y`.\n# \n# \n# Example 1:\n# Input: nums = [1,2]\n# Output: 1\n# Explanation: The optimal choice of operations is:\n# (1 * gcd(1, 2)) = 1\n# \n# Example 2:\n# Input: nums = [3,4,6,8]\n# Output: 11\n# Explanation: The optimal choice of operations is:\n# (1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11\n# \n# Example 3:\n# Input: nums = [1,2,3,4,5,6]\n# Output: 14\n# Explanation: The optimal choice of operations is:\n# (1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14\n# \n# Constraints:\n# `1 <= n <= 7`\n# `nums.length == 2 * n`\n# `1 <= nums[i] <= 106`\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n ", "entry_point": "maxScore", "cannonical_solution": "", "test": ""}
{"tast_id": "count-pairs-with-xor-in-a-range", "prompt": "# Given a (0-indexed) integer array `nums` and two integers `low` and `high`, return the number of nice pairs.\n# \n# A nice pair is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`.\n# \n# \n# Example 1:\n# Input: nums = [1,4,2,7], low = 2, high = 6\n# Output: 6\n# Explanation: All nice pairs (i, j) are as follows:\n# - (0, 1): nums[0] XOR nums[1] = 5 \n# - (0, 2): nums[0] XOR nums[2] = 3\n# - (0, 3): nums[0] XOR nums[3] = 6\n# - (1, 2): nums[1] XOR nums[2] = 6\n# - (1, 3): nums[1] XOR nums[3] = 3\n# - (2, 3): nums[2] XOR nums[3] = 5\n# \n# Example 2:\n# Input: nums = [9,8,4,2,1], low = 5, high = 14\n# Output: 8\n# Explanation: All nice pairs (i, j) are as follows:\n# \u200b\u200b\u200b\u200b\u200b - (0, 2): nums[0] XOR nums[2] = 13\n# - (0, 3): nums[0] XOR nums[3] = 11\n# - (0, 4): nums[0] XOR nums[4] = 8\n# - (1, 2): nums[1] XOR nums[2] = 12\n# - (1, 3): nums[1] XOR nums[3] = 10\n# - (1, 4): nums[1] XOR nums[4] = 9\n# - (2, 3): nums[2] XOR nums[3] = 6\n# - (2, 4): nums[2] XOR nums[4] = 5\n# \n# Constraints:\n# `1 <= nums.length <= 2 * 104`\n# `1 <= nums[i] <= 2 * 104`\n# `1 <= low <= high <= 2 * 104`\nclass Solution:\n def countPairs(self, nums: List[int], low: int, high: int) -> int:\n ", "entry_point": "countPairs", "cannonical_solution": "", "test": ""}
{"tast_id": "maximize-number-of-nice-divisors", "prompt": "# You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions:\n# The number of prime factors of `n` (not necessarily distinct) is at most `primeFactors`.\n# \n# The number of nice divisors of `n` is maximized. Note that a divisor of `n` is nice if it is divisible by every prime factor of `n`. For example, if `n = 12`, then its prime factors are `[2,2,3]`, then `6` and `12` are nice divisors, while `3` and `4` are not.\n# \n# Return the number of nice divisors of `n`. Since that number can be too large, return it modulo `109 + 7`.\n# \n# Note that a prime number is a natural number greater than `1` that is not a product of two smaller natural numbers. The prime factors of a number `n` is a list of prime numbers such that their product equals `n`.\n# \n# \n# Example 1:\n# Input: primeFactors = 5\n# Output: 6\n# Explanation: 200 is a valid value of n.\n# \n# It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].\n# \n# There is not other value of n that has at most 5 prime factors and more nice divisors.\n# \n# \n# Example 2:\n# Input: primeFactors = 8\n# Output: 18\n# \n# Constraints:\n# `1 <= primeFactors <= 109`\nclass Solution:\n def maxNiceDivisors(self, primeFactors: int) -> int:\n ", "entry_point": "maxNiceDivisors", "cannonical_solution": "", "test": ""}
{"tast_id": "maximum-number-of-groups-getting-fresh-donuts", "prompt": "# There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` customers that will visit the shop. Each customer will get exactly one donut.\n# \n# When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.\n# \n# You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.\n# \n# \n# Example 1:\n# Input: batchSize = 3, groups = [1,2,3,4,5,6]\n# Output: 4\n# Explanation: You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy.\n# \n# \n# Example 2:\n# Input: batchSize = 4, groups = [1,3,2,5,2,2,1,6]\n# Output: 4\n# \n# Constraints:\n# `1 <= batchSize <= 9`\n# `1 <= groups.length <= 30`\n# `1 <= groups[i] <= 109`\nclass Solution:\n def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int:\n ", "entry_point": "maxHappyGroups", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-different-subsequences-gcds", "prompt": "# You are given an array `nums` that consists of positive integers.\n# \n# The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly.\n# \n# For example, the GCD of the sequence `[4,6,16]` is `2`.\n# \n# A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.\n# \n# For example, `[2,5,10]` is a subsequence of `[1,2,1,2,4,1,5,10]`.\n# \n# Return the number of different GCDs among all non-empty subsequences of `nums`.\n# \n# \n# Example 1:\n# Input: nums = [6,10,3]\n# Output: 5\n# Explanation: The figure shows all the non-empty subsequences and their GCDs.\n# \n# The different GCDs are 6, 10, 3, 2, and 1.\n# \n# \n# Example 2:\n# Input: nums = [5,15,40,5,6]\n# Output: 7\n# \n# Constraints:\n# `1 <= nums.length <= 105`\n# `1 <= nums[i] <= 2 * 105`\nclass Solution:\n def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int:\n ", "entry_point": "countDifferentSubsequenceGCDs", "cannonical_solution": "", "test": ""}
{"tast_id": "finding-mk-average", "prompt": "# You are given two integers, `m` and `k`, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream.\n# \n# The MKAverage can be calculated using these steps:\n# If the number of the elements in the stream is less than `m` you should consider the MKAverage to be `-1`. Otherwise, copy the last `m` elements of the stream to a separate container.\n# \n# Remove the smallest `k` elements and the largest `k` elements from the container.\n# \n# Calculate the average value for the rest of the elements rounded down to the nearest integer.\n# \n# Implement the `MKAverage` class:\n# `MKAverage(int m, int k)` Initializes the MKAverage object with an empty stream and the two integers `m` and `k`.\n# \n# `void addElement(int num)` Inserts a new element `num` into the stream.\n# \n# `int calculateMKAverage()` Calculates and returns the MKAverage for the current stream rounded down to the nearest integer.\n# \n# \n# Example 1:\n# Input\n# [\"MKAverage\", \"addElement\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"addElement\", \"addElement\", \"calculateMKAverage\"]\n# [[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]\n# Output\n# [null, null, null, -1, null, 3, null, null, null, 5]\n# Explanation\n# MKAverage obj = new MKAverage(3, 1); \n# obj.addElement(3); // current elements are [3]\n# obj.addElement(1); // current elements are [3,1]\n# obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.\n# \n# obj.addElement(10); // current elements are [3,1,10]\n# obj.calculateMKAverage(); // The last 3 elements are [3,1,10].\n# \n# // After removing smallest and largest 1 element the container will be `[3].\n# \n# // The average of [3] equals 3/1 = 3, return 3\n# obj.addElement(5); // current elements are [3,1,10,5]\n# obj.addElement(5); // current elements are [3,1,10,5,5]\n# obj.addElement(5); // current elements are [3,1,10,5,5,5]\n# obj.calculateMKAverage(); // The last 3 elements are [5,5,5].\n# \n# // After removing smallest and largest 1 element the container will be `[5].\n# \n# // The average of [5] equals 5/1 = 5, return 5\n# ``\n# \n# Constraints:\n# `3 <= m <= 105`\n# `1 <= k*2 < m`\n# `1 <= num <= 105`\n# At most `105` calls will be made to `addElement` and `calculateMKAverage`.\nclass MKAverage:\n\n def __init__(self, m: int, k: int):\n \n\n def addElement(self, num: int) -> None:\n \n\n def calculateMKAverage(self) -> int:\n \n\n\n# Your MKAverage object will be instantiated and called as such:\n# obj = MKAverage(m, k)\n# obj.addElement(num)\n# param_2 = obj.calculateMKAverage()", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"tast_id": "arithmetic-slices-ii-subsequence", "prompt": "# A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.\n# \n# For example, these are arithmetic sequences:\n# 1, 3, 5, 7, 9\n# 7, 7, 7, 7\n# 3, -1, -5, -9\n# The following sequence is not arithmetic.\n# \n# 1, 1, 2, 5, 7\n# A zero-indexed array A consisting of N numbers is given. A subsequence slice of that array is any sequence of integers (P0, P1, ..., Pk) such that 0 \u2264 P0 < P1 < ... < Pk < N.\n# \n# A subsequence slice (P0, P1, ..., Pk) of array A is called arithmetic if the sequence A[P0], A[P1], ..., A[Pk-1], A[Pk] is arithmetic. In particular, this means that k \u2265 2.\n# \n# The function should return the number of arithmetic subsequence slices in the array A.\n# \n# The input contains N integers. Every integer is in the range of -231 and 231-1 and 0 \u2264 N \u2264 1000. The output is guaranteed to be less than 231-1.\n# \n# \n# Example:\n# Input: [2, 4, 6, 8, 10]\n# Output: 7\n# Explanation:\n# All arithmetic subsequence slices are:\n# [2,4,6]\n# [4,6,8]\n# [6,8,10]\n# [2,4,6,8]\n# [4,6,8,10]\n# [2,4,6,8,10]\n# [2,6,10]\nclass Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n ", "entry_point": "numberOfArithmeticSlices", "cannonical_solution": "", "test": ""}
{"tast_id": "number-of-ways-to-paint-n-3-grid", "prompt": "# You have a `grid` of size `n x 3` and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).\n# \n# Given `n` the number of rows of the grid, return the number of ways you can paint this `grid`. As the answer may grow large, the answer must be computed modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: n = 1\n# Output: 12\n# Explanation: There are 12 possible way to paint the grid as shown.\n# \n# \n# Example 2:\n# Input: n = 2\n# Output: 54\n# \n# Example 3:\n# Input: n = 3\n# Output: 246\n# \n# Example 4:\n# Input: n = 7\n# Output: 106494\n# \n# Example 5:\n# Input: n = 5000\n# Output: 30228214\n# \n# Constraints:\n# `n == grid.length`\n# `grid[i].length == 3`\n# `1 <= n <= 5000`\nclass Solution:\n def numOfWays(self, n: int) -> int:\n ", "entry_point": "numOfWays", "cannonical_solution": "", "test": ""}
{"task_id": "median-of-two-sorted-arrays", "prompt": "# Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return the median of the two sorted arrays.\n# \n# \n# Example 1:\n# Input: nums1 = [1,3], nums2 = [2]\n# Output: 2.00000\n# Explanation: merged array = [1,2,3] and median is 2.\n# \n# \n# Example 2:\n# Input: nums1 = [1,2], nums2 = [3,4]\n# Output: 2.50000\n# Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.\n# \n# \n# Example 3:\n# Input: nums1 = [0,0], nums2 = [0,0]\n# Output: 0.00000\n# \n# Example 4:\n# Input: nums1 = [], nums2 = [1]\n# Output: 1.00000\n# \n# Example 5:\n# Input: nums1 = [2], nums2 = []\n# Output: 2.00000\n# \n# Constraints:\n# `nums1.length == m`\n# `nums2.length == n`\n# `0 <= m <= 1000`\n# `0 <= n <= 1000`\n# `1 <= m + n <= 2000`\n# `-106 <= nums1[i], nums2[i] <= 106`\n# Follow up: The overall run time complexity should be `O(log (m+n))`.\nclass Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n ", "entry_point": "findMedianSortedArrays", "cannonical_solution": "", "test": ""}
{"task_id": "regular-expression-matching", "prompt": "# Given an input string (`s`) and a pattern (`p`), implement regular expression matching with support for `'.'` and `'*'` where:` `\n# `'.'` Matches any single character.\u200b\u200b\u200b\u200b\n# `'*'` Matches zero or more of the preceding element.\n# \n# The matching should cover the entire input string (not partial).\n# \n# \n# Example 1:\n# Input: s = \"aa\", p = \"a\"\n# Output: false\n# Explanation: \"a\" does not match the entire string \"aa\".\n# \n# \n# Example 2:\n# Input: s = \"aa\", p = \"a*\"\n# Output: true\n# Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes \"aa\".\n# \n# \n# Example 3:\n# Input: s = \"ab\", p = \".*\"\n# Output: true\n# Explanation: \".*\" means \"zero or more (*) of any character (.)\".\n# \n# \n# Example 4:\n# Input: s = \"aab\", p = \"c*a*b\"\n# Output: true\n# Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches \"aab\".\n# \n# \n# Example 5:\n# Input: s = \"mississippi\", p = \"mis*is*p*.\"\n# Output: false\n# \n# Constraints:\n# `0 <= s.length <= 20`\n# `0 <= p.length <= 30`\n# `s` contains only lowercase English letters.\n# \n# `p` contains only lowercase English letters, `'.'`, and `'*'`.\n# \n# It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match.\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n ", "entry_point": "isMatch", "cannonical_solution": "", "test": ""}
{"task_id": "substring-with-concatenation-of-all-words", "prompt": "# You are given a string `s` and an array of strings `words` of the same length. Return all starting indices of substring(s) in `s` that is a concatenation of each word in `words` exactly once, in any order, and without any intervening characters.\n# \n# You can return the answer in any order.\n# \n# \n# Example 1:\n# Input: s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"]\n# Output: [0,9]\n# Explanation: Substrings starting at index 0 and 9 are \"barfoo\" and \"foobar\" respectively.\n# \n# The output order does not matter, returning [9,0] is fine too.\n# \n# \n# Example 2:\n# Input: s = \"wordgoodgoodgoodbestword\", words = [\"word\",\"good\",\"best\",\"word\"]\n# Output: []\n# \n# Example 3:\n# Input: s = \"barfoofoobarthefoobarman\", words = [\"bar\",\"foo\",\"the\"]\n# Output: [6,9,12]\n# \n# Constraints:\n# `1 <= s.length <= 104`\n# `s` consists of lower-case English letters.\n# \n# `1 <= words.length <= 5000`\n# `1 <= words[i].length <= 30`\n# `words[i]` consists of lower-case English letters.\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n ", "entry_point": "findSubstring", "cannonical_solution": "", "test": ""}
{"task_id": "longest-valid-parentheses", "prompt": "# Given a string containing just the characters `'('` and `')'`, find the length of the longest valid (well-formed) parentheses substring.\n# \n# \n# Example 1:\n# Input: s = \"(()\"\n# Output: 2\n# Explanation: The longest valid parentheses substring is \"()\".\n# \n# \n# Example 2:\n# Input: s = \")()())\"\n# Output: 4\n# Explanation: The longest valid parentheses substring is \"()()\".\n# \n# \n# Example 3:\n# Input: s = \"\"\n# Output: 0\n# \n# Constraints:\n# `0 <= s.length <= 3 * 104`\n# `s[i]` is `'('`, or `')'`.\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n ", "entry_point": "longestValidParentheses", "cannonical_solution": "", "test": ""}
{"task_id": "first-missing-positive", "prompt": "# Given an unsorted integer array `nums`, find the smallest missing positive integer.\n# \n# \n# Example 1:\n# Input: nums = [1,2,0]\n# Output: 3\n# \n# Example 2:\n# Input: nums = [3,4,-1,1]\n# Output: 2\n# \n# Example 3:\n# Input: nums = [7,8,9,11,12]\n# Output: 1\n# \n# Constraints:\n# `0 <= nums.length <= 300`\n# `-231 <= nums[i] <= 231 - 1`\n# Follow up: Could you implement an algorithm that runs in `O(n)` time and uses constant extra space?\nclass Solution:\n def firstMissingPositive(self, nums: List[int]) -> int:\n ", "entry_point": "firstMissingPositive", "cannonical_solution": "", "test": ""}
{"task_id": "trapping-rain-water", "prompt": "# Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining.\n# \n# \n# Example 1:\n# Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]\n# Output: 6\n# Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.\n# \n# \n# Example 2:\n# Input: height = [4,2,0,3,2,5]\n# Output: 9\n# \n# Constraints:\n# `n == height.length`\n# `0 <= n <= 3 * 104`\n# `0 <= height[i] <= 105`\nclass Solution:\n def trap(self, height: List[int]) -> int:\n ", "entry_point": "trap", "cannonical_solution": "", "test": ""}
{"task_id": "wildcard-matching", "prompt": "# Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where:\n# `'?'` Matches any single character.\n# \n# `'*'` Matches any sequence of characters (including the empty sequence).\n# \n# The matching should cover the entire input string (not partial).\n# \n# \n# Example 1:\n# Input: s = \"aa\", p = \"a\"\n# Output: false\n# Explanation: \"a\" does not match the entire string \"aa\".\n# \n# \n# Example 2:\n# Input: s = \"aa\", p = \"*\"\n# Output: true\n# Explanation: '*' matches any sequence.\n# \n# \n# Example 3:\n# Input: s = \"cb\", p = \"?a\"\n# Output: false\n# Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.\n# \n# \n# Example 4:\n# Input: s = \"adceb\", p = \"*a*b\"\n# Output: true\n# Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring \"dce\".\n# \n# \n# Example 5:\n# Input: s = \"acdcb\", p = \"a*c?b\"\n# Output: false\n# \n# Constraints:\n# `0 <= s.length, p.length <= 2000`\n# `s` contains only lowercase English letters.\n# \n# `p` contains only lowercase English letters, `'?'` or `'*'`.\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n ", "entry_point": "isMatch", "cannonical_solution": "", "test": ""}
{"task_id": "n-queens", "prompt": "# The n-queens puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.\n# \n# Given an integer `n`, return all distinct solutions to the n-queens puzzle.\n# \n# Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.\n# \n# \n# Example 1:\n# Input: n = 4\n# Output: [[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]\n# Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above\n# \n# Example 2:\n# Input: n = 1\n# Output: [[\"Q\"]]\n# \n# Constraints:\n# `1 <= n <= 9`\nclass Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n ", "entry_point": "solveNQueens", "cannonical_solution": "", "test": ""}
{"task_id": "n-queens-ii", "prompt": "# The n-queens puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.\n# \n# Given an integer `n`, return the number of distinct solutions to the n-queens puzzle.\n# \n# \n# Example 1:\n# Input: n = 4\n# Output: 2\n# Explanation: There are two distinct solutions to the 4-queens puzzle as shown.\n# \n# \n# Example 2:\n# Input: n = 1\n# Output: 1\n# \n# Constraints:\n# `1 <= n <= 9`\nclass Solution:\n def totalNQueens(self, n: int) -> int:\n ", "entry_point": "totalNQueens", "cannonical_solution": "", "test": ""}
{"task_id": "permutation-sequence", "prompt": "# The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations.\n# \n# By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`:\n# `\"123\"`\n# `\"132\"`\n# `\"213\"`\n# `\"231\"`\n# `\"312\"`\n# `\"321\"`\n# Given `n` and `k`, return the `kth` permutation sequence.\n# \n# \n# Example 1:\n# Input: n = 3, k = 3\n# Output: \"213\"\n# \n# Example 2:\n# Input: n = 4, k = 9\n# Output: \"2314\"\n# \n# Example 3:\n# Input: n = 3, k = 1\n# Output: \"123\"\n# \n# Constraints:\n# `1 <= n <= 9`\n# `1 <= k <= n!`\nclass Solution:\n def getPermutation(self, n: int, k: int) -> str:\n ", "entry_point": "getPermutation", "cannonical_solution": "", "test": ""}
{"task_id": "valid-number", "prompt": "# A valid number can be split up into these components (in order):\n# A decimal number or an integer.\n# \n# (Optional) An `'e'` or `'E'`, followed by an integer.\n# \n# A decimal number can be split up into these components (in order):\n# (Optional) A sign character (either `'+'` or `'-'`).\n# \n# One of the following formats:\n# \t\n# At least one digit, followed by a dot `'.'`.\n# \n# At least one digit, followed by a dot `'.'`, followed by at least one digit.\n# \n# A dot `'.'`, followed by at least one digit.\n# \n# An integer can be split up into these components (in order):\n# (Optional) A sign character (either `'+'` or `'-'`).\n# \n# At least one digit.\n# \n# For example, all the following are valid numbers: `[\"2\", \"0089\", \"-0.1\", \"+3.14\", \"4.\", \"-.9\", \"2e10\", \"-90E3\", \"3e+7\", \"+6e-1\", \"53.5e93\", \"-123.456e789\"]`, while the following are not valid numbers: `[\"abc\", \"1a\", \"1e\", \"e3\", \"99e2.5\", \"--6\", \"-+3\", \"95a54e53\"]`.\n# \n# Given a string `s`, return `true` if `s` is a valid number.\n# \n# \n# Example 1:\n# Input: s = \"0\"\n# Output: true\n# \n# Example 2:\n# Input: s = \"e\"\n# Output: false\n# \n# Example 3:\n# Input: s = \".\"\n# Output: false\n# \n# Example 4:\n# Input: s = \".1\"\n# Output: true\n# \n# Constraints:\n# `1 <= s.length <= 20`\n# `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.\nclass Solution:\n def isNumber(self, s: str) -> bool:\n ", "entry_point": "isNumber", "cannonical_solution": "", "test": ""}
{"task_id": "text-justification", "prompt": "# Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.\n# \n# You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly maxWidth characters.\n# \n# Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.\n# \n# For the last line of text, it should be left justified and no extra space is inserted between words.\n# \n# Note:\n# A word is defined as a character sequence consisting of non-space characters only.\n# \n# Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.\n# \n# The input array `words` contains at least one word.\n# \n# \n# Example 1:\n# Input: words = [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"], maxWidth = 16\n# Output:\n# [\n# \"This is an\",\n# \"example of text\",\n# \"justification. \"\n# ]\n# \n# Example 2:\n# Input: words = [\"What\",\"must\",\"be\",\"acknowledgment\",\"shall\",\"be\"], maxWidth = 16\n# Output:\n# [\n# \"What must be\",\n# \"acknowledgment \",\n# \"shall be \"\n# ]\n# Explanation: Note that the last line is \"shall be \" instead of \"shall be\", because the last line must be left-justified instead of fully-justified.\n# \n# Note that the second line is also left-justified becase it contains only one word.\n# \n# \n# Example 3:\n# Input: words = [\"Science\",\"is\",\"what\",\"we\",\"understand\",\"well\",\"enough\",\"to\",\"explain\",\"to\",\"a\",\"computer.\",\"Art\",\"is\",\"everything\",\"else\",\"we\",\"do\"], maxWidth = 20\n# Output:\n# [\n# \"Science is what we\",\n# \"understand well\",\n# \"enough to explain to\",\n# \"a computer. Art is\",\n# \"everything else we\",\n# \"do \"\n# ]\n# \n# Constraints:\n# `1 <= words.length <= 300`\n# `1 <= words[i].length <= 20`\n# `words[i]` consists of only English letters and symbols.\n# \n# `1 <= maxWidth <= 100`\n# `words[i].length <= maxWidth`\nclass Solution:\n def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:\n ", "entry_point": "fullJustify", "cannonical_solution": "", "test": ""}
{"task_id": "edit-distance", "prompt": "# Given two strings `word1` and `word2`, return the minimum number of operations required to convert `word1` to `word2`.\n# \n# You have the following three operations permitted on a word:\n# Insert a character\n# Delete a character\n# Replace a character\n# \n# Example 1:\n# Input: word1 = \"horse\", word2 = \"ros\"\n# Output: 3\n# Explanation: \n# horse -> rorse (replace 'h' with 'r')\n# rorse -> rose (remove 'r')\n# rose -> ros (remove 'e')\n# \n# Example 2:\n# Input: word1 = \"intention\", word2 = \"execution\"\n# Output: 5\n# Explanation: \n# intention -> inention (remove 't')\n# inention -> enention (replace 'i' with 'e')\n# enention -> exention (replace 'n' with 'x')\n# exention -> exection (replace 'n' with 'c')\n# exection -> execution (insert 'u')\n# \n# Constraints:\n# `0 <= word1.length, word2.length <= 500`\n# `word1` and `word2` consist of lowercase English letters.\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n ", "entry_point": "minDistance", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-window-substring", "prompt": "# Given two strings `s` and `t`, return the minimum window in `s` which will contain all the characters in `t`. If there is no such window in `s` that covers all characters in `t`, return the empty string `\"\"`.\n# \n# Note that If there is such a window, it is guaranteed that there will always be only one unique minimum window in `s`.\n# \n# \n# Example 1:\n# Input: s = \"ADOBECODEBANC\", t = \"ABC\"\n# Output: \"BANC\"\n# \n# Example 2:\n# Input: s = \"a\", t = \"a\"\n# Output: \"a\"\n# \n# Constraints:\n# `1 <= s.length, t.length <= 105`\n# `s` and `t` consist of English letters.\n# \n# Follow up: Could you find an algorithm that runs in `O(n)` time?\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n ", "entry_point": "minWindow", "cannonical_solution": "", "test": ""}
{"task_id": "largest-rectangle-in-histogram", "prompt": "# Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return the area of the largest rectangle in the histogram.\n# \n# \n# Example 1:\n# Input: heights = [2,1,5,6,2,3]\n# Output: 10\n# Explanation: The above is a histogram where width of each bar is 1.\n# \n# The largest rectangle is shown in the red area, which has an area = 10 units.\n# \n# \n# Example 2:\n# Input: heights = [2,4]\n# Output: 4\n# \n# Constraints:\n# `1 <= heights.length <= 105`\n# `0 <= heights[i] <= 104`\nclass Solution:\n def largestRectangleArea(self, heights: List[int]) -> int:\n ", "entry_point": "largestRectangleArea", "cannonical_solution": "", "test": ""}
{"task_id": "maximal-rectangle", "prompt": "# Given a `rows x cols` binary `matrix` filled with `0`'s and `1`'s, find the largest rectangle containing only `1`'s and return its area.\n# \n# \n# Example 1:\n# Input: matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\n# Output: 6\n# Explanation: The maximal rectangle is shown in the above picture.\n# \n# \n# Example 2:\n# Input: matrix = []\n# Output: 0\n# \n# Example 3:\n# Input: matrix = [[\"0\"]]\n# Output: 0\n# \n# Example 4:\n# Input: matrix = [[\"1\"]]\n# Output: 1\n# \n# Example 5:\n# Input: matrix = [[\"0\",\"0\"]]\n# Output: 0\n# \n# Constraints:\n# `rows == matrix.length`\n# `cols == matrix[i].length`\n# `0 <= row, cols <= 200`\n# `matrix[i][j]` is `'0'` or `'1'`.\nclass Solution:\n def maximalRectangle(self, matrix: List[List[str]]) -> int:\n ", "entry_point": "maximalRectangle", "cannonical_solution": "", "test": ""}
{"task_id": "scramble-string", "prompt": "# We can scramble a string s to get a string t using the following algorithm:\n# If the length of the string is 1, stop.\n# \n# If the length of the string is > 1, do the following:\n# \t\n# Split the string into two non-empty substrings at a random index, i.e., if the string is `s`, divide it to `x` and `y` where `s = x + y`.\n# \n# Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, `s` may become `s = x + y` or `s = y + x`.\n# \n# Apply step 1 recursively on each of the two substrings `x` and `y`.\n# \n# Given two strings `s1` and `s2` of the same length, return `true` if `s2` is a scrambled string of `s1`, otherwise, return `false`.\n# \n# \n# Example 1:\n# Input: s1 = \"great\", s2 = \"rgeat\"\n# Output: true\n# Explanation: One possible scenario applied on s1 is:\n# \"great\" --> \"gr/eat\" // divide at random index.\n# \n# \"gr/eat\" --> \"gr/eat\" // random decision is not to swap the two substrings and keep them in order.\n# \n# \"gr/eat\" --> \"g/r / e/at\" // apply the same algorithm recursively on both substrings. divide at ranom index each of them.\n# \n# \"g/r / e/at\" --> \"r/g / e/at\" // random decision was to swap the first substring and to keep the second substring in the same order.\n# \n# \"r/g / e/at\" --> \"r/g / e/ a/t\" // again apply the algorithm recursively, divide \"at\" to \"a/t\".\n# \n# \"r/g / e/ a/t\" --> \"r/g / e/ a/t\" // random decision is to keep both substrings in the same order.\n# \n# The algorithm stops now and the result string is \"rgeat\" which is s2.\n# \n# As there is one possible scenario that led s1 to be scrambled to s2, we return true.\n# \n# \n# Example 2:\n# Input: s1 = \"abcde\", s2 = \"caebd\"\n# Output: false\n# \n# Example 3:\n# Input: s1 = \"a\", s2 = \"a\"\n# Output: true\n# \n# Constraints:\n# `s1.length == s2.length`\n# `1 <= s1.length <= 30`\n# `s1` and `s2` consist of lower-case English letters.\nclass Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n ", "entry_point": "isScramble", "cannonical_solution": "", "test": ""}
{"task_id": "distinct-subsequences", "prompt": "# Given two strings `s` and `t`, return the number of distinct subsequences of `s` which equals `t`.\n# \n# A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., `\"ACE\"` is a subsequence of `\"ABCDE\"` while `\"AEC\"` is not).\n# \n# It is guaranteed the answer fits on a 32-bit signed integer.\n# \n# \n# Example 1:\n# Input: s = \"rabbbit\", t = \"rabbit\"\n# Output: 3\n# Explanation:\n# As shown below, there are 3 ways you can generate \"rabbit\" from S.\n# \n# `rabbbit`\n# `rabbbit`\n# `rabbbit`\n# \n# Example 2:\n# Input: s = \"babgbag\", t = \"bag\"\n# Output: 5\n# Explanation:\n# As shown below, there are 5 ways you can generate \"bag\" from S.\n# \n# `babgbag`\n# `babgbag`\n# `babgbag`\n# `babgbag`\n# `babgbag`\n# \n# Constraints:\n# `1 <= s.length, t.length <= 1000`\n# `s` and `t` consist of English letters.\nclass Solution:\n def numDistinct(self, s: str, t: str) -> int:\n ", "entry_point": "numDistinct", "cannonical_solution": "", "test": ""}
{"task_id": "best-time-to-buy-and-sell-stock-iii", "prompt": "# You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.\n# \n# Find the maximum profit you can achieve. You may complete at most two transactions.\n# \n# Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n# \n# \n# Example 1:\n# Input: prices = [3,3,5,0,0,3,1,4]\n# Output: 6\n# Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n# \n# Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.\n# \n# \n# Example 2:\n# Input: prices = [1,2,3,4,5]\n# Output: 4\n# Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\n# \n# Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.\n# \n# \n# Example 3:\n# Input: prices = [7,6,4,3,1]\n# Output: 0\n# Explanation: In this case, no transaction is done, i.e. max profit = 0.\n# \n# \n# Example 4:\n# Input: prices = [1]\n# Output: 0\n# \n# Constraints:\n# `1 <= prices.length <= 105`\n# `0 <= prices[i] <= 105`\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n ", "entry_point": "maxProfit", "cannonical_solution": "", "test": ""}
{"task_id": "word-ladder-ii", "prompt": "# A transformation sequence from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:\n# Every adjacent pair of words differs by a single letter.\n# \n# Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.\n# \n# `sk == endWord`\n# Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return all the shortest transformation sequences from `beginWord` to `endWord`, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words `[beginWord, s1, s2, ..., sk]`.\n# \n# \n# Example 1:\n# Input: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\n# Output: [[\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],[\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]]\n# Explanation: There are 2 shortest transformation sequences:\n# \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> \"cog\"\n# \"hit\" -> \"hot\" -> \"lot\" -> \"log\" -> \"cog\"\n# \n# Example 2:\n# Input: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n# Output: []\n# Explanation: The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.\n# \n# \n# Constraints:\n# `1 <= beginWord.length <= 10`\n# `endWord.length == beginWord.length`\n# `1 <= wordList.length <= 5000`\n# `wordList[i].length == beginWord.length`\n# `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.\n# \n# `beginWord != endWord`\n# All the words in `wordList` are unique.\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n ", "entry_point": "findLadders", "cannonical_solution": "", "test": ""}
{"task_id": "word-ladder", "prompt": "# A transformation sequence from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:\n# Every adjacent pair of words differs by a single letter.\n# \n# Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.\n# \n# `sk == endWord`\n# Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return the number of words in the shortest transformation sequence from `beginWord` to `endWord`, or `0` if no such sequence exists.\n# \n# \n# Example 1:\n# Input: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\n# Output: 5\n# Explanation: One shortest transformation sequence is \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> cog\", which is 5 words long.\n# \n# \n# Example 2:\n# Input: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n# Output: 0\n# Explanation: The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.\n# \n# \n# Constraints:\n# `1 <= beginWord.length <= 10`\n# `endWord.length == beginWord.length`\n# `1 <= wordList.length <= 5000`\n# `wordList[i].length == beginWord.length`\n# `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.\n# \n# `beginWord != endWord`\n# All the words in `wordList` are unique.\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n ", "entry_point": "ladderLength", "cannonical_solution": "", "test": ""}
{"task_id": "longest-consecutive-sequence", "prompt": "# Given an unsorted array of integers `nums`, return the length of the longest consecutive elements sequence.\n# \n# \n# Example 1:\n# Input: nums = [100,4,200,1,3,2]\n# Output: 4\n# Explanation: The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4.\n# \n# \n# Example 2:\n# Input: nums = [0,3,7,2,5,8,4,6,0,1]\n# Output: 9\n# \n# Constraints:\n# `0 <= nums.length <= 104`\n# `-109 <= nums[i] <= 109`\n# Follow up: Could you implement the `O(n)` solution?\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n ", "entry_point": "longestConsecutive", "cannonical_solution": "", "test": ""}
{"task_id": "palindrome-partitioning-ii", "prompt": "# Given a string `s`, partition `s` such that every substring of the partition is a palindrome.\n# \n# Return the minimum cuts needed for a palindrome partitioning of `s`.\n# \n# \n# Example 1:\n# Input: s = \"aab\"\n# Output: 1\n# Explanation: The palindrome partitioning [\"aa\",\"b\"] could be produced using 1 cut.\n# \n# \n# Example 2:\n# Input: s = \"a\"\n# Output: 0\n# \n# Example 3:\n# Input: s = \"ab\"\n# Output: 1\n# \n# Constraints:\n# `1 <= s.length <= 2000`\n# `s` consists of lower-case English letters only.\nclass Solution:\n def minCut(self, s: str) -> int:\n ", "entry_point": "minCut", "cannonical_solution": "", "test": ""}
{"task_id": "candy", "prompt": "# There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`.\n# \n# You are giving candies to these children subjected to the following requirements:\n# Each child must have at least one candy.\n# \n# Children with a higher rating get more candies than their neighbors.\n# \n# Return the minimum number of candies you need to have to distribute the candies to the children.\n# \n# \n# Example 1:\n# Input: ratings = [1,0,2]\n# Output: 5\n# Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.\n# \n# \n# Example 2:\n# Input: ratings = [1,2,2]\n# Output: 4\n# Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.\n# \n# The third child gets 1 candy because it satisfies the above two conditions.\n# \n# \n# Constraints:\n# `n == ratings.length`\n# `1 <= n <= 2 * 104`\n# `0 <= ratings[i] <= 2 * 104`\nclass Solution:\n def candy(self, ratings: List[int]) -> int:\n ", "entry_point": "candy", "cannonical_solution": "", "test": ""}
{"task_id": "word-break-ii", "prompt": "# Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.\n# \n# Note that the same word in the dictionary may be reused multiple times in the segmentation.\n# \n# \n# Example 1:\n# Input: s = \"catsanddog\", wordDict = [\"cat\",\"cats\",\"and\",\"sand\",\"dog\"]\n# Output: [\"cats and dog\",\"cat sand dog\"]\n# \n# Example 2:\n# Input: s = \"pineapplepenapple\", wordDict = [\"apple\",\"pen\",\"applepen\",\"pine\",\"pineapple\"]\n# Output: [\"pine apple pen apple\",\"pineapple pen apple\",\"pine applepen apple\"]\n# Explanation: Note that you are allowed to reuse a dictionary word.\n# \n# \n# Example 3:\n# Input: s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]\n# Output: []\n# \n# Constraints:\n# `1 <= s.length <= 20`\n# `1 <= wordDict.length <= 1000`\n# `1 <= wordDict[i].length <= 10`\n# `s` and `wordDict[i]` consist of only lowercase English letters.\n# \n# All the strings of `wordDict` are unique.\nclass Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:\n ", "entry_point": "wordBreak", "cannonical_solution": "", "test": ""}
{"task_id": "max-points-on-a-line", "prompt": "# Given an array of `points` where `points[i] = [xi, yi]` represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.\n# \n# \n# Example 1:\n# Input: points = [[1,1],[2,2],[3,3]]\n# Output: 3\n# \n# Example 2:\n# Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\n# Output: 4\n# \n# Constraints:\n# `1 <= points.length <= 300`\n# `points[i].length == 2`\n# `-104 <= xi, yi <= 104`\n# All the `points` are unique.\nclass Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n ", "entry_point": "maxPoints", "cannonical_solution": "", "test": ""}
{"task_id": "find-minimum-in-rotated-sorted-array-ii", "prompt": "# Suppose an array of length `n` sorted in ascending order is rotated between `1` and `n` times. For example, the array `nums = [0,1,4,4,5,6,7]` might become:\n# `[4,5,6,7,0,1,4]` if it was rotated `4` times.\n# \n# `[0,1,4,4,5,6,7]` if it was rotated `7` times.\n# \n# Notice that rotating an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.\n# \n# Given the sorted rotated array `nums` that may contain duplicates, return the minimum element of this array.\n# \n# \n# Example 1:\n# Input: nums = [1,3,5]\n# Output: 1\n# \n# Example 2:\n# Input: nums = [2,2,2,0,1]\n# Output: 0\n# \n# Constraints:\n# `n == nums.length`\n# `1 <= n <= 5000`\n# `-5000 <= nums[i] <= 5000`\n# `nums` is sorted and rotated between `1` and `n` times.\n# \n# Follow up: This is the same as Find Minimum in Rotated Sorted Array but with duplicates. Would allow duplicates affect the run-time complexity? How and why?\nclass Solution:\n def findMin(self, nums: List[int]) -> int:\n ", "entry_point": "findMin", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-gap", "prompt": "# Given an integer array `nums`, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return `0`.\n# \n# \n# Example 1:\n# Input: nums = [3,6,9,1]\n# Output: 3\n# Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.\n# \n# \n# Example 2:\n# Input: nums = [10]\n# Output: 0\n# Explanation: The array contains less than 2 elements, therefore return 0.\n# \n# \n# Constraints:\n# `1 <= nums.length <= 104`\n# `0 <= nums[i] <= 109`\n# Follow up: Could you solve it in linear time/space?\nclass Solution:\n def maximumGap(self, nums: List[int]) -> int:\n ", "entry_point": "maximumGap", "cannonical_solution": "", "test": ""}
{"task_id": "dungeon-game", "prompt": "# The demons had captured the princess and imprisoned her in the bottom-right corner of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through `dungeon` to rescue the princess.\n# \n# The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately.\n# \n# Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).\n# \n# To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.\n# \n# Return the knight's minimum initial health so that he can rescue the princess.\n# \n# Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.\n# \n# \n# Example 1:\n# Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]\n# Output: 7\n# Explanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.\n# \n# \n# Example 2:\n# Input: dungeon = [[0]]\n# Output: 1\n# \n# Constraints:\n# `m == dungeon.length`\n# `n == dungeon[i].length`\n# `1 <= m, n <= 200`\n# `-1000 <= dungeon[i][j] <= 1000`\nclass Solution:\n def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:\n ", "entry_point": "calculateMinimumHP", "cannonical_solution": "", "test": ""}
{"task_id": "best-time-to-buy-and-sell-stock-iv", "prompt": "# You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `k`.\n# \n# Find the maximum profit you can achieve. You may complete at most `k` transactions.\n# \n# Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n# \n# \n# Example 1:\n# Input: k = 2, prices = [2,4,1]\n# Output: 2\n# Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.\n# \n# \n# Example 2:\n# Input: k = 2, prices = [3,2,6,5,0,3]\n# Output: 7\n# Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n# \n# \n# Constraints:\n# `0 <= k <= 100`\n# `0 <= prices.length <= 1000`\n# `0 <= prices[i] <= 1000`\nclass Solution:\n def maxProfit(self, k: int, prices: List[int]) -> int:\n ", "entry_point": "maxProfit", "cannonical_solution": "", "test": ""}
{"task_id": "word-search-ii", "prompt": "# Given an `m x n` `board` of characters and a list of strings `words`, return all words on the board.\n# \n# Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.\n# \n# \n# Example 1:\n# Input: board = [[\"o\",\"a\",\"a\",\"n\"],[\"e\",\"t\",\"a\",\"e\"],[\"i\",\"h\",\"k\",\"r\"],[\"i\",\"f\",\"l\",\"v\"]], words = [\"oath\",\"pea\",\"eat\",\"rain\"]\n# Output: [\"eat\",\"oath\"]\n# \n# Example 2:\n# Input: board = [[\"a\",\"b\"],[\"c\",\"d\"]], words = [\"abcb\"]\n# Output: []\n# \n# Constraints:\n# `m == board.length`\n# `n == board[i].length`\n# `1 <= m, n <= 12`\n# `board[i][j]` is a lowercase English letter.\n# \n# `1 <= words.length <= 3 * 104`\n# `1 <= words[i].length <= 10`\n# `words[i]` consists of lowercase English letters.\n# \n# All the strings of `words` are unique.\nclass Solution:\n def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n ", "entry_point": "findWords", "cannonical_solution": "", "test": ""}
{"task_id": "shortest-palindrome", "prompt": "# You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it.\n# \n# Return the shortest palindrome you can find by performing this transformation.\n# \n# \n# Example 1:\n# Input: s = \"aacecaaa\"\n# Output: \"aaacecaaa\"\n# \n# Example 2:\n# Input: s = \"abcd\"\n# Output: \"dcbabcd\"\n# \n# Constraints:\n# `0 <= s.length <= 5 * 104`\n# `s` consists of lowercase English letters only.\nclass Solution:\n def shortestPalindrome(self, s: str) -> str:\n ", "entry_point": "shortestPalindrome", "cannonical_solution": "", "test": ""}
{"task_id": "the-skyline-problem", "prompt": "# A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.\n# \n# The geometric information of each building is given in the array `buildings` where `buildings[i] = [lefti, righti, heighti]`:\n# `lefti` is the x coordinate of the left edge of the `ith` building.\n# \n# `righti` is the x coordinate of the right edge of the `ith` building.\n# \n# `heighti` is the height of the `ith` building.\n# \n# You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height `0`.\n# \n# The skyline should be represented as a list of \"key points\" sorted by their x-coordinate in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate `0` and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.\n# \n# Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is not acceptable; the three lines of height 5 should be merged into one in the final output as such: `[...,[2 3],[4 5],[12 7],...]`\n# \n# Example 1:\n# Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]\n# Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]\n# Explanation:\n# Figure A shows the buildings of the input.\n# \n# Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.\n# \n# \n# Example 2:\n# Input: buildings = [[0,2,3],[2,5,3]]\n# Output: [[0,3],[5,0]]\n# \n# Constraints:\n# `1 <= buildings.length <= 104`\n# `0 <= lefti < righti <= 231 - 1`\n# `1 <= heighti <= 231 - 1`\n# `buildings` is sorted by `lefti` in non-decreasing order.\nclass Solution:\n def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:\n ", "entry_point": "getSkyline", "cannonical_solution": "", "test": ""}
{"task_id": "basic-calculator", "prompt": "# Given a string `s` representing an expression, implement a basic calculator to evaluate it.\n# \n# \n# Example 1:\n# Input: s = \"1 + 1\"\n# Output: 2\n# \n# Example 2:\n# Input: s = \" 2-1 + 2 \"\n# Output: 3\n# \n# Example 3:\n# Input: s = \"(1+(4+5+2)-3)+(6+8)\"\n# Output: 23\n# \n# Constraints:\n# `1 <= s.length <= 3 * 105`\n# `s` consists of digits, `'+'`, `'-'`, `'('`, `')'`, and `' '`.\n# \n# `s` represents a valid expression.\nclass Solution:\n def calculate(self, s: str) -> int:\n ", "entry_point": "calculate", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-digit-one", "prompt": "# Given an integer `n`, count the total number of digit `1` appearing in all non-negative integers less than or equal to `n`.\n# \n# \n# Example 1:\n# Input: n = 13\n# Output: 6\n# \n# Example 2:\n# Input: n = 0\n# Output: 0\n# \n# Constraints:\n# `0 <= n <= 2 * 109`\nclass Solution:\n def countDigitOne(self, n: int) -> int:\n ", "entry_point": "countDigitOne", "cannonical_solution": "", "test": ""}
{"task_id": "sliding-window-maximum", "prompt": "# You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.\n# \n# Return the max sliding window.\n# \n# \n# Example 1:\n# Input: nums = [1,3,-1,-3,5,3,6,7], k = 3\n# Output: [3,3,5,5,6,7]\n# Explanation: \n# Window position Max\n# --------------- -----\n# [1 3 -1] -3 5 3 6 7 3\n# 1 [3 -1 -3] 5 3 6 7 3\n# 1 3 [-1 -3 5] 3 6 7 5\n# 1 3 -1 [-3 5 3] 6 7 5\n# 1 3 -1 -3 [5 3 6] 7 6\n# 1 3 -1 -3 5 [3 6 7] 7\n# \n# Example 2:\n# Input: nums = [1], k = 1\n# Output: [1]\n# \n# Example 3:\n# Input: nums = [1,-1], k = 1\n# Output: [1,-1]\n# \n# Example 4:\n# Input: nums = [9,11], k = 2\n# Output: [11]\n# \n# Example 5:\n# Input: nums = [4,-2], k = 2\n# Output: [4]\n# \n# Constraints:\n# `1 <= nums.length <= 105`\n# `-104 <= nums[i] <= 104`\n# `1 <= k <= nums.length`\nclass Solution:\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n ", "entry_point": "maxSlidingWindow", "cannonical_solution": "", "test": ""}
{"task_id": "integer-to-english-words", "prompt": "# Convert a non-negative integer `num` to its English words representation.\n# \n# \n# Example 1:\n# Input: num = 123\n# Output: \"One Hundred Twenty Three\"\n# \n# Example 2:\n# Input: num = 12345\n# Output: \"Twelve Thousand Three Hundred Forty Five\"\n# \n# Example 3:\n# Input: num = 1234567\n# Output: \"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven\"\n# \n# Example 4:\n# Input: num = 1234567891\n# Output: \"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One\"\n# \n# Constraints:\n# `0 <= num <= 231 - 1`\nclass Solution:\n def numberToWords(self, num: int) -> str:\n ", "entry_point": "numberToWords", "cannonical_solution": "", "test": ""}
{"task_id": "expression-add-operators", "prompt": "# Given a string `num` that contains only digits and an integer `target`, return all possibilities to add the binary operators `'+'`, `'-'`, or `'*'` between the digits of `num` so that the resultant expression evaluates to the `target` value.\n# \n# \n# Example 1:\n# Input: num = \"123\", target = 6\n# Output: [\"1*2*3\",\"1+2+3\"]\n# \n# Example 2:\n# Input: num = \"232\", target = 8\n# Output: [\"2*3+2\",\"2+3*2\"]\n# \n# Example 3:\n# Input: num = \"105\", target = 5\n# Output: [\"1*0+5\",\"10-5\"]\n# \n# Example 4:\n# Input: num = \"00\", target = 0\n# Output: [\"0*0\",\"0+0\",\"0-0\"]\n# \n# Example 5:\n# Input: num = \"3456237490\", target = 9191\n# Output: []\n# \n# Constraints:\n# `1 <= num.length <= 10`\n# `num` consists of only digits.\n# \n# `-231 <= target <= 231 - 1`\nclass Solution:\n def addOperators(self, num: str, target: int) -> List[str]:\n ", "entry_point": "addOperators", "cannonical_solution": "", "test": ""}
{"task_id": "find-median-from-data-stream", "prompt": "# The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.\n# \n# For example, for `arr = [2,3,4]`, the median is `3`.\n# \n# For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`.\n# \n# Implement the MedianFinder class:\n# `MedianFinder()` initializes the `MedianFinder` object.\n# \n# `void addNum(int num)` adds the integer `num` from the data stream to the data structure.\n# \n# `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted.\n# \n# \n# Example 1:\n# Input\n# [\"MedianFinder\", \"addNum\", \"addNum\", \"findMedian\", \"addNum\", \"findMedian\"]\n# [[], [1], [2], [], [3], []]\n# Output\n# [null, null, null, 1.5, null, 2.0]\n# Explanation\n# MedianFinder medianFinder = new MedianFinder();\n# medianFinder.addNum(1); // arr = [1]\n# medianFinder.addNum(2); // arr = [1, 2]\n# medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\n# medianFinder.addNum(3); // arr[1, 2, 3]\n# medianFinder.findMedian(); // return 2.0\n# \n# Constraints:\n# `-105 <= num <= 105`\n# There will be at least one element in the data structure before calling `findMedian`.\n# \n# At most `5 * 104` calls will be made to `addNum` and `findMedian`.\n# \n# Follow up:\n# If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?\n# If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?\nclass MedianFinder:\n\n def __init__(self):\n \n\n def addNum(self, num: int) -> None:\n \n\n def findMedian(self) -> float:\n \n\n\n# Your MedianFinder object will be instantiated and called as such:\n# obj = MedianFinder()\n# obj.addNum(num)\n# param_2 = obj.findMedian()", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "remove-invalid-parentheses", "prompt": "# Given a string `s` that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.\n# \n# Return all the possible results. You may return the answer in any order.\n# \n# \n# Example 1:\n# Input: s = \"()())()\"\n# Output: [\"(())()\",\"()()()\"]\n# \n# Example 2:\n# Input: s = \"(a)())()\"\n# Output: [\"(a())()\",\"(a)()()\"]\n# \n# Example 3:\n# Input: s = \")(\"\n# Output: [\"\"]\n# \n# Constraints:\n# `1 <= s.length <= 25`\n# `s` consists of lowercase English letters and parentheses `'('` and `')'`.\n# \n# There will be at most `20` parentheses in `s`.\nclass Solution:\n def removeInvalidParentheses(self, s: str) -> List[str]:\n ", "entry_point": "removeInvalidParentheses", "cannonical_solution": "", "test": ""}
{"task_id": "burst-balloons", "prompt": "# You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons.\n# \n# If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, then treat it as if there is a balloon with a `1` painted on it.\n# \n# Return the maximum coins you can collect by bursting the balloons wisely.\n# \n# \n# Example 1:\n# Input: nums = [3,1,5,8]\n# Output: 167\n# Explanation:\n# nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []\n# coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167\n# \n# Example 2:\n# Input: nums = [1,5]\n# Output: 10\n# \n# Constraints:\n# `n == nums.length`\n# `1 <= n <= 500`\n# `0 <= nums[i] <= 100`\nclass Solution:\n def maxCoins(self, nums: List[int]) -> int:\n ", "entry_point": "maxCoins", "cannonical_solution": "", "test": ""}
{"task_id": "count-of-smaller-numbers-after-self", "prompt": "# You are given an integer array `nums` and you have to return a new `counts` array. The `counts` array has the property where `counts[i]` is the number of smaller elements to the right of `nums[i]`.\n# \n# \n# Example 1:\n# Input: nums = [5,2,6,1]\n# Output: [2,1,1,0]\n# Explanation:\n# To the right of 5 there are 2 smaller elements (2 and 1).\n# \n# To the right of 2 there is only 1 smaller element (1).\n# \n# To the right of 6 there is 1 smaller element (1).\n# \n# To the right of 1 there is 0 smaller element.\n# \n# \n# Example 2:\n# Input: nums = [-1]\n# Output: [0]\n# \n# Example 3:\n# Input: nums = [-1,-1]\n# Output: [0,0]\n# \n# Constraints:\n# `1 <= nums.length <= 105`\n# `-104 <= nums[i] <= 104`\nclass Solution:\n def countSmaller(self, nums: List[int]) -> List[int]:\n ", "entry_point": "countSmaller", "cannonical_solution": "", "test": ""}
{"task_id": "create-maximum-number", "prompt": "# You are given two integer arrays `nums1` and `nums2` of lengths `m` and `n` respectively. `nums1` and `nums2` represent the digits of two numbers. You are also given an integer `k`.\n# \n# Create the maximum number of length `k <= m + n` from digits of the two numbers. The relative order of the digits from the same array must be preserved.\n# \n# Return an array of the `k` digits representing the answer.\n# \n# \n# Example 1:\n# Input: nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5\n# Output: [9,8,6,5,3]\n# \n# Example 2:\n# Input: nums1 = [6,7], nums2 = [6,0,4], k = 5\n# Output: [6,7,6,0,4]\n# \n# Example 3:\n# Input: nums1 = [3,9], nums2 = [8,9], k = 3\n# Output: [9,8,9]\n# \n# Constraints:\n# `m == nums1.length`\n# `n == nums2.length`\n# `1 <= m, n <= 500`\n# `0 <= nums1[i], nums2[i] <= 9`\n# `1 <= k <= m + n`\n# Follow up: Try to optimize your time and space complexity.\nclass Solution:\n def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:\n ", "entry_point": "maxNumber", "cannonical_solution": "", "test": ""}
{"task_id": "count-of-range-sum", "prompt": "# Given an integer array `nums` and two integers `lower` and `upper`, return the number of range sums that lie in `[lower, upper]` inclusive.\n# \n# Range sum `S(i, j)` is defined as the sum of the elements in `nums` between indices `i` and `j` inclusive, where `i <= j`.\n# \n# \n# Example 1:\n# Input: nums = [-2,5,-1], lower = -2, upper = 2\n# Output: 3\n# Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.\n# \n# \n# Example 2:\n# Input: nums = [0], lower = 0, upper = 0\n# Output: 1\n# \n# Constraints:\n# `1 <= nums.length <= 104`\n# `-231 <= nums[i] <= 231 - 1`\n# `-3 * 104 <= lower <= upper <= 3 * 104`\n# Follow up: A naive algorithm of `O(n2)` is trivial, Could you do better than that?\nclass Solution:\n def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:\n ", "entry_point": "countRangeSum", "cannonical_solution": "", "test": ""}
{"task_id": "longest-increasing-path-in-a-matrix", "prompt": "# Given an `m x n` integers `matrix`, return the length of the longest increasing path in `matrix`.\n# \n# From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).\n# \n# \n# Example 1:\n# Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]\n# Output: 4\n# Explanation: The longest increasing path is `[1, 2, 6, 9]`.\n# \n# \n# Example 2:\n# Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]\n# Output: 4\n# Explanation: The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed.\n# \n# \n# Example 3:\n# Input: matrix = [[1]]\n# Output: 1\n# \n# Constraints:\n# `m == matrix.length`\n# `n == matrix[i].length`\n# `1 <= m, n <= 200`\n# `0 <= matrix[i][j] <= 231 - 1`\nclass Solution:\n def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n ", "entry_point": "longestIncreasingPath", "cannonical_solution": "", "test": ""}
{"task_id": "patching-array", "prompt": "# Given a sorted integer array `nums` and an integer `n`, add/patch elements to the array such that any number in the range `[1, n]` inclusive can be formed by the sum of some elements in the array.\n# \n# Return the minimum number of patches required.\n# \n# \n# Example 1:\n# Input: nums = [1,3], n = 6\n# Output: 1\n# Explanation:\n# Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\n# \n# Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\n# \n# Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\n# \n# So we only need 1 patch.\n# \n# \n# Example 2:\n# Input: nums = [1,5,10], n = 20\n# Output: 2\n# Explanation: The two patches can be [2, 4].\n# \n# \n# Example 3:\n# Input: nums = [1,2,2], n = 5\n# Output: 0\n# \n# Constraints:\n# `1 <= nums.length <= 1000`\n# `1 <= nums[i] <= 104`\n# `nums` is sorted in ascending order.\n# \n# `1 <= n <= 231 - 1`\nclass Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n ", "entry_point": "minPatches", "cannonical_solution": "", "test": ""}
{"task_id": "self-crossing", "prompt": "# You are given an array of integers `distance`.\n# \n# You start at point `(0,0)` on an X-Y plane and you move `distance[0]` meters to the north, then `distance[1]` meters to the west, `distance[2]` meters to the south, `distance[3]` meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.\n# \n# Return `true` if your path crosses itself, and `false` if it does not.\n# \n# \n# Example 1:\n# Input: distance = [2,1,1,2]\n# Output: true\n# \n# Example 2:\n# Input: distance = [1,2,3,4]\n# Output: false\n# \n# Example 3:\n# Input: distance = [1,1,1,1]\n# Output: true\n# \n# Constraints:\n# `1 <= distance.length <= 500`\n# `1 <= distance[i] <= 500`\n# Follow up: Could you write a one-pass algorithm with `O(1)` extra space?\nclass Solution:\n def isSelfCrossing(self, distance: List[int]) -> bool:\n ", "entry_point": "isSelfCrossing", "cannonical_solution": "", "test": ""}
{"task_id": "palindrome-pairs", "prompt": "# Given a list of unique words, return all the pairs of the distinct indices `(i, j)` in the given list, so that the concatenation of the two words `words[i] + words[j]` is a palindrome.\n# \n# \n# Example 1:\n# Input: words = [\"abcd\",\"dcba\",\"lls\",\"s\",\"sssll\"]\n# Output: [[0,1],[1,0],[3,2],[2,4]]\n# Explanation: The palindromes are [\"dcbaabcd\",\"abcddcba\",\"slls\",\"llssssll\"]\n# \n# Example 2:\n# Input: words = [\"bat\",\"tab\",\"cat\"]\n# Output: [[0,1],[1,0]]\n# Explanation: The palindromes are [\"battab\",\"tabbat\"]\n# \n# Example 3:\n# Input: words = [\"a\",\"\"]\n# Output: [[0,1],[1,0]]\n# \n# Constraints:\n# `1 <= words.length <= 5000`\n# `0 <= words[i].length <= 300`\n# `words[i]` consists of lower-case English letters.\nclass Solution:\n def palindromePairs(self, words: List[str]) -> List[List[int]]:\n ", "entry_point": "palindromePairs", "cannonical_solution": "", "test": ""}
{"task_id": "data-stream-as-disjoint-intervals", "prompt": "# Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals.\n# \n# Implement the `SummaryRanges` class:\n# `SummaryRanges()` Initializes the object with an empty stream.\n# \n# `void addNum(int val)` Adds the integer `val` to the stream.\n# \n# `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`.\n# \n# \n# Example 1:\n# Input\n# [\"SummaryRanges\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\"]\n# [[], [1], [], [3], [], [7], [], [2], [], [6], []]\n# Output\n# [null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]\n# Explanation\n# SummaryRanges summaryRanges = new SummaryRanges();\n# summaryRanges.addNum(1); // arr = [1]\n# summaryRanges.getIntervals(); // return [[1, 1]]\n# summaryRanges.addNum(3); // arr = [1, 3]\n# summaryRanges.getIntervals(); // return [[1, 1], [3, 3]]\n# summaryRanges.addNum(7); // arr = [1, 3, 7]\n# summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]\n# summaryRanges.addNum(2); // arr = [1, 2, 3, 7]\n# summaryRanges.getIntervals(); // return [[1, 3], [7, 7]]\n# summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]\n# summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]\n# \n# Constraints:\n# `0 <= val <= 104`\n# At most `3 * 104` calls will be made to `addNum` and `getIntervals`.\n# \n# Follow up: What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?\nclass SummaryRanges:\n\n def __init__(self):\n \n\n def addNum(self, value: int) -> None:\n \n\n def getIntervals(self) -> List[List[int]]:\n \n\n\n# Your SummaryRanges object will be instantiated and called as such:\n# obj = SummaryRanges()\n# obj.addNum(value)\n# param_2 = obj.getIntervals()", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "russian-doll-envelopes", "prompt": "# You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope.\n# \n# One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.\n# \n# Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).\n# \n# Note: You cannot rotate an envelope.\n# \n# \n# Example 1:\n# Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]\n# Output: 3\n# Explanation: The maximum number of envelopes you can Russian doll is `3` ([2,3] => [5,4] => [6,7]).\n# \n# \n# Example 2:\n# Input: envelopes = [[1,1],[1,1],[1,1]]\n# Output: 1\n# \n# Constraints:\n# `1 <= envelopes.length <= 5000`\n# `envelopes[i].length == 2`\n# `1 <= wi, hi <= 104`\nclass Solution:\n def maxEnvelopes(self, envelopes: List[List[int]]) -> int:\n ", "entry_point": "maxEnvelopes", "cannonical_solution": "", "test": ""}
{"task_id": "max-sum-of-rectangle-no-larger-than-k", "prompt": "# Given an `m x n` matrix `matrix` and an integer `k`, return the max sum of a rectangle in the matrix such that its sum is no larger than `k`.\n# \n# It is guaranteed that there will be a rectangle with a sum no larger than `k`.\n# \n# \n# Example 1:\n# Input: matrix = [[1,0,1],[0,-2,3]], k = 2\n# Output: 2\n# Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).\n# \n# \n# Example 2:\n# Input: matrix = [[2,2,-1]], k = 3\n# Output: 3\n# \n# Constraints:\n# `m == matrix.length`\n# `n == matrix[i].length`\n# `1 <= m, n <= 100`\n# `-100 <= matrix[i][j] <= 100`\n# `-105 <= k <= 105`\n# Follow up: What if the number of rows is much larger than the number of columns?\nclass Solution:\n def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:\n ", "entry_point": "maxSumSubmatrix", "cannonical_solution": "", "test": ""}
{"task_id": "perfect-rectangle", "prompt": "# Given an array `rectangles` where `rectangles[i] = [xi, yi, ai, bi]` represents an axis-aligned rectangle. The bottom-left point of the rectangle is `(xi, yi)` and the top-right point of it is `(ai, bi)`.\n# \n# Return `true` if all the rectangles together form an exact cover of a rectangular region.\n# \n# \n# Example 1:\n# Input: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]\n# Output: true\n# Explanation: All 5 rectangles together form an exact cover of a rectangular region.\n# \n# \n# Example 2:\n# Input: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]\n# Output: false\n# Explanation: Because there is a gap between the two rectangular regions.\n# \n# \n# Example 3:\n# Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[3,2,4,4]]\n# Output: false\n# Explanation: Because there is a gap in the top center.\n# \n# \n# Example 4:\n# Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]\n# Output: false\n# Explanation: Because two of the rectangles overlap with each other.\n# \n# \n# Constraints:\n# `1 <= rectangles.length <= 2 * 104`\n# `rectangles[i].length == 4`\n# `-105 <= xi, yi, ai, bi <= 105`\nclass Solution:\n def isRectangleCover(self, rectangles: List[List[int]]) -> bool:\n ", "entry_point": "isRectangleCover", "cannonical_solution": "", "test": ""}
{"task_id": "frog-jump", "prompt": "# A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.\n# \n# Given a list of `stones`' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be `1` unit.\n# \n# If the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units. The frog can only jump in the forward direction.\n# \n# \n# Example 1:\n# Input: stones = [0,1,3,5,6,8,12,17]\n# Output: true\n# Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.\n# \n# \n# Example 2:\n# Input: stones = [0,1,2,3,4,8,9,11]\n# Output: false\n# Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.\n# \n# \n# Constraints:\n# `2 <= stones.length <= 2000`\n# `0 <= stones[i] <= 231 - 1`\n# `stones[0] == 0`\nclass Solution:\n def canCross(self, stones: List[int]) -> bool:\n ", "entry_point": "canCross", "cannonical_solution": "", "test": ""}
{"task_id": "trapping-rain-water-ii", "prompt": "# Given an `m x n` matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.\n# \n# \n# Example:\n# Given the following 3x6 height map:\n# [\n# [1,4,3,1,3,2],\n# [3,2,1,3,2,4],\n# [2,3,3,2,3,1]\n# ]\n# Return 4.\n# \n# The above image represents the elevation map `[[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]` before the rain.\n# \n# After the rain, water is trapped between the blocks. The total volume of water trapped is 4.\n# \n# \n# Constraints:\n# `1 <= m, n <= 110`\n# `0 <= heightMap[i][j] <= 20000`\nclass Solution:\n def trapRainWater(self, heightMap: List[List[int]]) -> int:\n ", "entry_point": "trapRainWater", "cannonical_solution": "", "test": ""}
{"task_id": "split-array-largest-sum", "prompt": "# Given an array `nums` which consists of non-negative integers and an integer `m`, you can split the array into `m` non-empty continuous subarrays.\n# \n# Write an algorithm to minimize the largest sum among these `m` subarrays.\n# \n# \n# Example 1:\n# Input: nums = [7,2,5,10,8], m = 2\n# Output: 18\n# Explanation:\n# There are four ways to split nums into two subarrays.\n# \n# The best way is to split it into [7,2,5] and [10,8],\n# where the largest sum among the two subarrays is only 18.\n# \n# \n# Example 2:\n# Input: nums = [1,2,3,4,5], m = 2\n# Output: 9\n# \n# Example 3:\n# Input: nums = [1,4,4], m = 3\n# Output: 4\n# \n# Constraints:\n# `1 <= nums.length <= 1000`\n# `0 <= nums[i] <= 106`\n# `1 <= m <= min(50, nums.length)`\nclass Solution:\n def splitArray(self, nums: List[int], k: int) -> int:\n ", "entry_point": "splitArray", "cannonical_solution": "", "test": ""}
{"task_id": "strong-password-checker", "prompt": "# A password is considered strong if the below conditions are all met:\n# It has at least `6` characters and at most `20` characters.\n# \n# It contains at least one lowercase letter, at least one uppercase letter, and at least one digit.\n# \n# It does not contain three repeating characters in a row (i.e., `\"...aaa...\"` is weak, but `\"...aa...a...\"` is strong, assuming other conditions are met).\n# \n# Given a string `password`, return the minimum number of steps required to make `password` strong. if `password` is already strong, return `0`.\n# \n# In one step, you can:\n# Insert one character to `password`,\n# Delete one character from `password`, or\n# Replace one character of `password` with another character.\n# \n# \n# Example 1:\n# Input: password = \"a\"\n# Output: 5\n# \n# Example 2:\n# Input: password = \"aA1\"\n# Output: 3\n# \n# Example 3:\n# Input: password = \"1337C0d3\"\n# Output: 0\n# \n# Constraints:\n# `1 <= password.length <= 50`\n# `password` consists of letters, digits, dot `'.'` or exclamation mark `'!'`.\nclass Solution:\n def strongPasswordChecker(self, password: str) -> int:\n ", "entry_point": "strongPasswordChecker", "cannonical_solution": "", "test": ""}
{"task_id": "k-th-smallest-in-lexicographical-order", "prompt": "# Given integers `n` and `k`, find the lexicographically k-th smallest integer in the range from `1` to `n`.\n# \n# Note: 1 \u2264 k \u2264 n \u2264 109.\n# \n# \n# Example:\n# Input:\n# n: 13 k: 2\n# Output:\n# 10\n# Explanation:\n# The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.\nclass Solution:\n def findKthNumber(self, n: int, k: int) -> int:\n ", "entry_point": "findKthNumber", "cannonical_solution": "", "test": ""}
{"task_id": "poor-pigs", "prompt": "# There are `buckets` buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have `minutesToTest` minutes to determine which bucket is poisonous.\n# \n# You can feed the pigs according to these steps:\n# Choose some live pigs to feed.\n# \n# For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.\n# \n# Wait for `minutesToDie` minutes. You may not feed any other pigs during this time.\n# \n# After `minutesToDie` minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.\n# \n# Repeat this process until you run out of time.\n# \n# Given `buckets`, `minutesToDie`, and `minutesToTest`, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.\n# \n# \n# Example 1:\n# Input: buckets = 1000, minutesToDie = 15, minutesToTest = 60\n# Output: 5\n# \n# Example 2:\n# Input: buckets = 4, minutesToDie = 15, minutesToTest = 15\n# Output: 2\n# \n# Example 3:\n# Input: buckets = 4, minutesToDie = 15, minutesToTest = 30\n# Output: 2\n# \n# Constraints:\n# `1 <= buckets <= 1000`\n# `1 <= minutesToDie <= minutesToTest <= 100`\nclass Solution:\n def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:\n ", "entry_point": "poorPigs", "cannonical_solution": "", "test": ""}
{"task_id": "lfu-cache", "prompt": "# Design and implement a data structure for a Least Frequently Used (LFU) cache.\n# \n# Implement the `LFUCache` class:\n# `LFUCache(int capacity)` Initializes the object with the `capacity` of the data structure.\n# \n# `int get(int key)` Gets the value of the `key` if the `key` exists in the cache. Otherwise, returns `-1`.\n# \n# `void put(int key, int value)` Update the value of the `key` if present, or inserts the `key` if not already present. When the cache reaches its `capacity`, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used `key` would be invalidated.\n# \n# To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.\n# \n# When a key is first inserted into the cache, its use counter is set to `1` (due to the `put` operation). The use counter for a key in the cache is incremented either a `get` or `put` operation is called on it.\n# \n# \n# Example 1:\n# Input\n# [\"LFUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n# [[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]\n# Output\n# [null, null, null, 1, null, -1, 3, null, -1, 3, 4]\n# Explanation\n# // cnt(x) = the use counter for key x\n# // cache=[] will show the last used order for tiebreakers (leftmost element is most recent)\n# LFUCache lfu = new LFUCache(2);\n# lfu.put(1, 1); // cache=[1,_], cnt(1)=1\n# lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1\n# lfu.get(1); // return 1\n# // cache=[1,2], cnt(2)=1, cnt(1)=2\n# lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n# \n# // cache=[3,1], cnt(3)=1, cnt(1)=2\n# lfu.get(2); // return -1 (not found)\n# lfu.get(3); // return 3\n# // cache=[3,1], cnt(3)=2, cnt(1)=2\n# lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n# \n# // cache=[4,3], cnt(4)=1, cnt(3)=2\n# lfu.get(1); // return -1 (not found)\n# lfu.get(3); // return 3\n# // cache=[3,4], cnt(4)=1, cnt(3)=3\n# lfu.get(4); // return 4\n# // cache=[3,4], cnt(4)=2, cnt(3)=3\n# \n# Constraints:\n# `0 <= capacity, key, value <= 104`\n# At most `105` calls will be made to `get` and `put`.\n# \n# Follow up: Could you do both operations in `O(1)` time complexity?\nclass LFUCache:\n\n def __init__(self, capacity: int):\n \n\n def get(self, key: int) -> int:\n \n\n def put(self, key: int, value: int) -> None:\n \n\n\n# Your LFUCache object will be instantiated and called as such:\n# obj = LFUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "count-the-repetitions", "prompt": "# Define `S = [s,n]` as the string S which consists of n connected strings s. For example, `[\"abc\", 3]` =\"abcabcabc\". \n# On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, \u201cabc\u201d can be obtained from \u201cabdbec\u201d based on our definition, but it can not be obtained from \u201cacbbe\u201d.\n# \n# You are given two non-empty strings s1 and s2 (each at most 100 characters long) and two integers 0 \u2264 n1 \u2264 106 and 1 \u2264 n2 \u2264 106. Now consider the strings S1 and S2, where `S1=[s1,n1]` and `S2=[s2,n2]`. Find the maximum integer M such that `[S2,M]` can be obtained from `S1`.\n# \n# \n# Example:\n# Input:\n# s1=\"acb\", n1=4\n# s2=\"ab\", n2=2\n# Return:\n# 2\nclass Solution:\n def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:\n ", "entry_point": "getMaxRepetitions", "cannonical_solution": "", "test": ""}
{"task_id": "concatenated-words", "prompt": "# Given an array of strings `words` (without duplicates), return all the concatenated words in the given list of `words`.\n# \n# A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.\n# \n# \n# Example 1:\n# Input: words = [\"cat\",\"cats\",\"catsdogcats\",\"dog\",\"dogcatsdog\",\"hippopotamuses\",\"rat\",\"ratcatdogcat\"]\n# Output: [\"catsdogcats\",\"dogcatsdog\",\"ratcatdogcat\"]\n# Explanation: \"catsdogcats\" can be concatenated by \"cats\", \"dog\" and \"cats\"; \n# \"dogcatsdog\" can be concatenated by \"dog\", \"cats\" and \"dog\"; \n# \"ratcatdogcat\" can be concatenated by \"rat\", \"cat\", \"dog\" and \"cat\".\n# \n# \n# Example 2:\n# Input: words = [\"cat\",\"dog\",\"catdog\"]\n# Output: [\"catdog\"]\n# \n# Constraints:\n# `1 <= words.length <= 104`\n# `0 <= words[i].length <= 1000`\n# `words[i]` consists of only lowercase English letters.\n# \n# `0 <= sum(words[i].length) <= 6 * 105`\nclass Solution:\n def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:\n ", "entry_point": "findAllConcatenatedWordsInADict", "cannonical_solution": "", "test": ""}
{"task_id": "largest-palindrome-product", "prompt": "# Find the largest palindrome made from the product of two n-digit numbers.\n# \n# Since the result could be very large, you should return the largest palindrome mod 1337.\n# \n# \n# Example:\n# Input: 2\n# Output: 987\n# Explanation: 99 x 91 = 9009, 9009 % 1337 = 987\n# Note:\n# The range of n is [1,8].\nclass Solution:\n def largestPalindrome(self, n: int) -> int:\n ", "entry_point": "largestPalindrome", "cannonical_solution": "", "test": ""}
{"task_id": "sliding-window-median", "prompt": "# Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.\n# \n# \n# Examples:\n# `[2,3,4]` , the median is `3`\n# `[2,3]`, the median is `(2 + 3) / 2 = 2.5`\n# Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Your job is to output the median array for each window in the original array.\n# \n# For example,\n# Given nums = `[1,3,-1,-3,5,3,6,7]`, and k = 3.\n# \n# Window position Median\n# --------------- -----\n# [1 3 -1] -3 5 3 6 7 1\n# 1 [3 -1 -3] 5 3 6 7 -1\n# 1 3 [-1 -3 5] 3 6 7 -1\n# 1 3 -1 [-3 5 3] 6 7 3\n# 1 3 -1 -3 [5 3 6] 7 5\n# 1 3 -1 -3 5 [3 6 7] 6\n# Therefore, return the median sliding window as `[1,-1,-1,3,5,6]`.\n# \n# Note: \n# You may assume `k` is always valid, ie: `k` is always smaller than input array's size for non-empty array.\n# \n# Answers within `10^-5` of the actual value will be accepted as correct.\nclass Solution:\n def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n ", "entry_point": "medianSlidingWindow", "cannonical_solution": "", "test": ""}
{"task_id": "smallest-good-base", "prompt": "# For an integer n, we call k>=2 a good base of n, if all digits of n base k are 1.\n# \n# Now given a string representing n, you should return the smallest good base of n in string format.\n# \n# \n# Example 1:\n# Input: \"13\"\n# Output: \"3\"\n# Explanation: 13 base 3 is 111.\n# \n# \n# Example 2:\n# Input: \"4681\"\n# Output: \"8\"\n# Explanation: 4681 base 8 is 11111.\n# \n# \n# Example 3:\n# Input: \"1000000000000000000\"\n# Output: \"999999999999999999\"\n# Explanation: 1000000000000000000 base 999999999999999999 is 11.\n# \n# Note:\n# The range of n is [3, 10^18].\n# \n# The string representing n is always valid and will not have leading zeros.\nclass Solution:\n def smallestGoodBase(self, n: str) -> str:\n ", "entry_point": "smallestGoodBase", "cannonical_solution": "", "test": ""}
{"task_id": "zuma-game", "prompt": "# Think about Zuma Game. You have a row of balls on the table, colored red(R), yellow(Y), blue(B), green(G), and white(W). You also have several balls in your hand.\n# \n# Each time, you may choose a ball in your hand, and insert it into the row (including the leftmost place and rightmost place). Then, if there is a group of 3 or more balls in the same color touching, remove these balls. Keep doing this until no more balls can be removed.\n# \n# Find the minimal balls you have to insert to remove all the balls on the table. If you cannot remove all the balls, output -1.\n# \n# \n# Example 1:\n# Input: board = \"WRRBBW\", hand = \"RB\"\n# Output: -1\n# Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW\n# \n# Example 2:\n# Input: board = \"WWRRBBWW\", hand = \"WRBRW\"\n# Output: 2\n# Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> empty\n# \n# Example 3:\n# Input: board = \"G\", hand = \"GGGGG\"\n# Output: 2\n# Explanation: G -> G[G] -> GG[G] -> empty \n# \n# Example 4:\n# Input: board = \"RBYYBBRRB\", hand = \"YRBGB\"\n# Output: 3\n# Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty \n# \n# Constraints:\n# You may assume that the initial row of balls on the table won\u2019t have any 3 or more consecutive balls with the same color.\n# \n# `1 <= board.length <= 16`\n# `1 <= hand.length <= 5`\n# Both input strings will be non-empty and only contain characters 'R','Y','B','G','W'.\nclass Solution:\n def findMinStep(self, board: str, hand: str) -> int:\n ", "entry_point": "findMinStep", "cannonical_solution": "", "test": ""}
{"task_id": "reverse-pairs", "prompt": "# Given an array `nums`, we call `(i, j)` an important reverse pair if `i < j` and `nums[i] > 2*nums[j]`.\n# \n# You need to return the number of important reverse pairs in the given array.\n# \n# \n# Example1:\n# Input: [1,3,2,3,1]\n# Output: 2\n# \n# Example2:\n# Input: [2,4,3,5,1]\n# Output: 3\n# Note:\n# The length of the given array will not exceed `50,000`.\n# \n# All the numbers in the input array are in the range of 32-bit integer.\nclass Solution:\n def reversePairs(self, nums: List[int]) -> int:\n ", "entry_point": "reversePairs", "cannonical_solution": "", "test": ""}
{"task_id": "ipo", "prompt": "# Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. \n# You are given several projects. For each project i, it has a pure profit Pi and a minimum capital of Ci is needed to start the corresponding project. Initially, you have W capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.\n# \n# To sum up, pick a list of at most k distinct projects from given projects to maximize your final capital, and output your final maximized capital.\n# \n# \n# Example 1:\n# Input: k=2, W=0, Profits=[1,2,3], Capital=[0,1,1].\n# Output: 4\n# Explanation: Since your initial capital is 0, you can only start the project indexed 0.\n# \n# After finishing it you will obtain profit 1 and your capital becomes 1.\n# \n# With capital 1, you can either start the project indexed 1 or the project indexed 2.\n# \n# Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\n# \n# Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.\n# \n# Note:\n# You may assume all numbers in the input are non-negative integers.\n# \n# The length of Profits array and Capital array will not exceed 50,000.\n# \n# The answer is guaranteed to fit in a 32-bit signed integer.\nclass Solution:\n def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:\n ", "entry_point": "findMaximizedCapital", "cannonical_solution": "", "test": ""}
{"task_id": "freedom-trail", "prompt": "# In the video game Fallout 4, the quest \"Road to Freedom\" requires players to reach a metal dial called the \"Freedom Trail Ring\", and use the dial to spell a specific keyword in order to open the door.\n# \n# Given a string ring, which represents the code engraved on the outer ring and another string key, which represents the keyword needs to be spelled. You need to find the minimum number of steps in order to spell all the characters in the keyword.\n# \n# Initially, the first character of the ring is aligned at 12:00 direction. You need to spell all the characters in the string key one by one by rotating the ring clockwise or anticlockwise to make each character of the string key aligned at 12:00 direction and then by pressing the center button.\n# \n# At the stage of rotating the ring to spell the key character key[i]:\n# You can rotate the ring clockwise or anticlockwise one place, which counts as 1 step. The final purpose of the rotation is to align one of the string ring's characters at the 12:00 direction, where this character must equal to the character key[i].\n# \n# If the character key[i] has been aligned at the 12:00 direction, you need to press the center button to spell, which also counts as 1 step. After the pressing, you could begin to spell the next character in the key (next stage), otherwise, you've finished all the spelling.\n# \n# \n# Example:\n# Input: ring = \"godding\", key = \"gd\"\n# Output: 4\n# Explanation:\n# For the first key character 'g', since it is already in place, we just need 1 step to spell this character. \n# For the second key character 'd', we need to rotate the ring \"godding\" anticlockwise by two steps to make it become \"ddinggo\".\n# \n# Also, we need 1 more step for spelling.\n# \n# So the final output is 4.\n# \n# Note:\n# Length of both ring and key will be in range 1 to 100.\n# \n# There are only lowercase letters in both strings and might be some duplcate characters in both strings.\n# \n# It's guaranteed that string key could always be spelled by rotating the string ring.\nclass Solution:\n def findRotateSteps(self, ring: str, key: str) -> int:\n ", "entry_point": "findRotateSteps", "cannonical_solution": "", "test": ""}
{"task_id": "super-washing-machines", "prompt": "# You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty. \n# For each move, you could choose any m (1 \u2264 m \u2264 n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time . \n# Given an integer array representing the number of dresses in each washing machine from left to right on the line, you should find the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1.\n# \n# \n# Example1\n# Input: [1,0,5]\n# Output: 3\n# Explanation: \n# 1st move: 1 0 <-- 5 => 1 1 4\n# 2nd move: 1 <-- 1 <-- 4 => 2 1 3 \n# 3rd move: 2 1 <-- 3 => 2 2 2 \n# \n# Example2\n# Input: [0,3,0]\n# Output: 2\n# Explanation: \n# 1st move: 0 <-- 3 0 => 1 2 0 \n# 2nd move: 1 2 --> 0 => 1 1 1 \n# \n# Example3\n# Input: [0,2,0]\n# Output: -1\n# Explanation: \n# It's impossible to make all the three washing machines have the same number of dresses. \n# Note:\n# The range of n is [1, 10000].\n# \n# The range of dresses number in a super washing machine is [0, 1e5].\nclass Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n ", "entry_point": "findMinMoves", "cannonical_solution": "", "test": ""}
{"task_id": "remove-boxes", "prompt": "# You are given several `boxes` with different colors represented by different positive numbers.\n# \n# You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points.\n# \n# Return the maximum points you can get.\n# \n# \n# Example 1:\n# Input: boxes = [1,3,2,2,2,3,4,3,1]\n# Output: 23\n# Explanation:\n# [1, 3, 2, 2, 2, 3, 4, 3, 1] \n# ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) \n# ----> [1, 3, 3, 3, 1] (1*1=1 points) \n# ----> [1, 1] (3*3=9 points) \n# ----> [] (2*2=4 points)\n# \n# Example 2:\n# Input: boxes = [1,1,1]\n# Output: 9\n# \n# Example 3:\n# Input: boxes = [1]\n# Output: 1\n# \n# Constraints:\n# `1 <= boxes.length <= 100`\n# `1 <= boxes[i] <= 100`\nclass Solution:\n def removeBoxes(self, boxes: List[int]) -> int:\n ", "entry_point": "removeBoxes", "cannonical_solution": "", "test": ""}
{"task_id": "student-attendance-record-ii", "prompt": "# An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:\n# `'A'`: Absent.\n# \n# `'L'`: Late.\n# \n# `'P'`: Present.\n# \n# Any student is eligible for an attendance award if they meet both of the following criteria:\n# The student was absent (`'A'`) for strictly fewer than 2 days total.\n# \n# The student was never late (`'L'`) for 3 or more consecutive days.\n# \n# Given an integer `n`, return the number of possible attendance records of length `n` that make a student eligible for an attendance award. The answer may be very large, so return it modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: n = 2\n# Output: 8\n# Explanation: There are 8 records with length 2 that are eligible for an award:\n# \"PP\", \"AP\", \"PA\", \"LP\", \"PL\", \"AL\", \"LA\", \"LL\"\n# Only \"AA\" is not eligible because there are 2 absences (there need to be fewer than 2).\n# \n# \n# Example 2:\n# Input: n = 1\n# Output: 3\n# \n# Example 3:\n# Input: n = 10101\n# Output: 183236316\n# \n# Constraints:\n# `1 <= n <= 105`\nclass Solution:\n def checkRecord(self, n: int) -> int:\n ", "entry_point": "checkRecord", "cannonical_solution": "", "test": ""}
{"task_id": "find-the-closest-palindrome", "prompt": "# Given an integer n, find the closest integer (not including itself), which is a palindrome. \n# The 'closest' is defined as absolute difference minimized between two integers.\n# \n# \n# Example 1:\n# Input: \"123\"\n# Output: \"121\"\n# Note:\n# The input n is a positive integer represented by string, whose length will not exceed 18.\n# \n# If there is a tie, return the smaller one as answer.\nclass Solution:\n def nearestPalindromic(self, n: str) -> str:\n ", "entry_point": "nearestPalindromic", "cannonical_solution": "", "test": ""}
{"task_id": "erect-the-fence", "prompt": "# There are some trees, where each tree is represented by (x,y) coordinate in a two-dimensional garden. Your job is to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed. Your task is to help find the coordinates of trees which are exactly located on the fence perimeter.\n# \n# \n# Example 1:\n# Input: [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]\n# Output: [[1,1],[2,0],[4,2],[3,3],[2,4]]\n# Explanation:\n# \n# Example 2:\n# Input: [[1,2],[2,2],[4,2]]\n# Output: [[1,2],[2,2],[4,2]]\n# Explanation:\n# Even you only have trees in a line, you need to use rope to enclose them. \n# Note:\n# All trees should be enclosed together. You cannot cut the rope to enclose trees that will separate them in more than one group.\n# \n# All input integers will range from 0 to 100.\n# \n# The garden has at least one tree.\n# \n# All coordinates are distinct.\n# \n# Input points have NO order. No order required for output.\n# input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.\nclass Solution:\n def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:\n ", "entry_point": "outerTrees", "cannonical_solution": "", "test": ""}
{"task_id": "tag-validator", "prompt": "# Given a string representing a code snippet, you need to implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold:\n# The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.\n# \n# A closed tag (not necessarily valid) has exactly the following format : `<TAG_NAME>TAG_CONTENT</TAG_NAME>`. Among them, `<TAG_NAME>` is the start tag, and `</TAG_NAME>` 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.\n# \n# A valid `TAG_NAME` only contain upper-case letters, and has length in range [1,9]. Otherwise, the `TAG_NAME` is invalid.\n# \n# 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.\n# \n# 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.\n# \n# A `<` is unmatched if you cannot find a subsequent `>`. And when you find a `<` or `</`, all the subsequent characters until the next `>` should be parsed as TAG_NAME (not necessarily valid).\n# \n# The cdata has the following format : `<![CDATA[CDATA_CONTENT]]>`. The range of `CDATA_CONTENT` is defined as the characters between `<![CDATA[` and the first subsequent `]]>`. \n# `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# Valid Code Examples:\n# Input: \"<DIV>This is the first line <![CDATA[<div>]]></DIV>\"\n# Output: True\n# Explanation: \n# The code is wrapped in a closed tag : <DIV> and </DIV>. \n# The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. \n# Although CDATA_CONTENT has unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as tag.\n# \n# So TAG_CONTENT is valid, and then the code is valid. Thus return true.\n# \n# Input: \"<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>\"\n# Output: True\n# Explanation:\n# We first separate the code into : start_tag|tag_content|end_tag.\n# \n# start_tag -> \"<DIV>\"\n# end_tag -> \"</DIV>\"\n# tag_content could also be separated into : text1|cdata|text2.\n# \n# text1 -> \">> ![cdata[]] \"\n# cdata -> \"<![CDATA[<div>]>]]>\", where the CDATA_CONTENT is \"<div>]>\"\n# text2 -> \"]]>>]\"\n# The reason why start_tag is NOT \"<DIV>>>\" is because of the rule 6.\n# \n# The reason why cdata is NOT \"<![CDATA[<div>]>]]>]]>\" is because of the rule 7.\n# \n# \n# Invalid Code Examples:\n# Input: \"<A> <B> </A> </B>\"\n# Output: False\n# Explanation: Unbalanced. If \"<A>\" is closed, then \"<B>\" must be unmatched, and vice versa.\n# \n# Input: \"<DIV> div tag is not closed <DIV>\"\n# Output: False\n# Input: \"<DIV> unmatched < </DIV>\"\n# Output: False\n# Input: \"<DIV> closed tags with invalid tag name <b>123</b> </DIV>\"\n# Output: False\n# Input: \"<DIV> unmatched tags with invalid tag name </1234567890> and <CDATA[[]]> </DIV>\"\n# Output: False\n# Input: \"<DIV> unmatched start tag <B> and unmatched end tag </C> </DIV>\"\n# Output: False\n# Note:\n# For simplicity, you could assume the input code (including the any characters mentioned above) only contain `letters`, `digits`, `'<'`,`'>'`,`'/'`,`'!'`,`'['`,`']'` and `' '`.\nclass Solution:\n def isValid(self, code: str) -> bool:\n ", "entry_point": "isValid", "cannonical_solution": "", "test": ""}
{"task_id": "non-negative-integers-without-consecutive-ones", "prompt": "# Given a positive integer n, find the number of non-negative integers less than or equal to n, whose binary representations do NOT contain consecutive ones.\n# \n# \n# Example 1:\n# Input: 5\n# Output: 5\n# Explanation: \n# Here are the non-negative integers <= 5 with their corresponding binary representations:\n# 0 : 0\n# 1 : 1\n# 2 : 10\n# 3 : 11\n# 4 : 100\n# 5 : 101\n# Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. \n# Note:\n# 1 <= n <= 109\nclass Solution:\n def findIntegers(self, n: int) -> int:\n ", "entry_point": "findIntegers", "cannonical_solution": "", "test": ""}
{"task_id": "k-inverse-pairs-array", "prompt": "# Given two integers `n` and `k`, find how many different arrays consist of numbers from `1` to `n` such that there are exactly `k` inverse pairs.\n# \n# We define an inverse pair as following: For `ith` and `jth` element in the array, if `i` < `j` and `a[i]` > `a[j]` then it's an inverse pair; Otherwise, it's not.\n# \n# Since the answer may be very large, the answer should be modulo 109 + 7.\n# \n# \n# Example 1:\n# Input: n = 3, k = 0\n# Output: 1\n# Explanation: \n# Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pair.\n# \n# \n# Example 2:\n# Input: n = 3, k = 1\n# Output: 2\n# Explanation: \n# The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.\n# \n# Note:\n# The integer `n` is in the range [1, 1000] and `k` is in the range [0, 1000].\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n ", "entry_point": "kInversePairs", "cannonical_solution": "", "test": ""}
{"task_id": "course-schedule-iii", "prompt": "# There are `n` different online courses numbered from `1` to `n`. Each course has some duration(course length) `t` and closed on `dth` day. A course should be taken continuously for `t` days and must be finished before or on the `dth` day. You will start at the `1st` day.\n# \n# Given `n` online courses represented by pairs `(t,d)`, your task is to find the maximal number of courses that can be taken.\n# \n# \n# Example:\n# Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]\n# Output: 3\n# Explanation: \n# There're totally 4 courses, but you can take 3 courses at most:\n# First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.\n# \n# Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. \n# Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. \n# The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.\n# \n# Note:\n# The integer 1 <= d, t, n <= 10,000.\n# \n# You can't take two courses simultaneously.\nclass Solution:\n def scheduleCourse(self, courses: List[List[int]]) -> int:\n ", "entry_point": "scheduleCourse", "cannonical_solution": "", "test": ""}
{"task_id": "smallest-range-covering-elements-from-k-lists", "prompt": "# You have `k` lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the `k` lists.\n# \n# We define the range `[a, b]` is smaller than range `[c, d]` if `b - a < d - c` or `a < c` if `b - a == d - c`.\n# \n# \n# Example 1:\n# Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]\n# Output: [20,24]\n# Explanation: \n# List 1: [4, 10, 15, 24,26], 24 is in range [20,24].\n# \n# List 2: [0, 9, 12, 20], 20 is in range [20,24].\n# \n# List 3: [5, 18, 22, 30], 22 is in range [20,24].\n# \n# \n# Example 2:\n# Input: nums = [[1,2,3],[1,2,3],[1,2,3]]\n# Output: [1,1]\n# \n# Example 3:\n# Input: nums = [[10,10],[11,11]]\n# Output: [10,11]\n# \n# Example 4:\n# Input: nums = [[10],[11]]\n# Output: [10,11]\n# \n# Example 5:\n# Input: nums = [[1],[2],[3],[4],[5],[6],[7]]\n# Output: [1,7]\n# \n# Constraints:\n# `nums.length == k`\n# `1 <= k <= 3500`\n# `1 <= nums[i].length <= 50`\n# `-105 <= nums[i][j] <= 105`\n# `nums[i]` is sorted in non-decreasing order.\nclass Solution:\n def smallestRange(self, nums: List[List[int]]) -> List[int]:\n ", "entry_point": "smallestRange", "cannonical_solution": "", "test": ""}
{"task_id": "decode-ways-ii", "prompt": "# A message containing letters from `A-Z` can be encoded into numbers using the following mapping:\n# 'A' -> \"1\"\n# 'B' -> \"2\"\n# ...\n# \n# 'Z' -> \"26\"\n# To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `\"11106\"` can be mapped into:\n# `\"AAJF\"` with the grouping `(1 1 10 6)`\n# `\"KJF\"` with the grouping `(11 10 6)`\n# Note that the grouping `(1 11 06)` is invalid because `\"06\"` cannot be mapped into `'F'` since `\"6\"` is different from `\"06\"`.\n# \n# In addition to the mapping above, an encoded message may contain the `'*'` character, which can represent any digit from `'1'` to `'9'` (`'0'` is excluded). For example, the encoded message `\"1*\"` may represent any of the encoded messages `\"11\"`, `\"12\"`, `\"13\"`, `\"14\"`, `\"15\"`, `\"16\"`, `\"17\"`, `\"18\"`, or `\"19\"`. Decoding `\"1*\"` is equivalent to decoding any of the encoded messages it can represent.\n# \n# Given a string `s` containing digits and the `'*'` character, return the number of ways to decode it.\n# \n# Since the answer may be very large, return it modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: s = \"*\"\n# Output: 9\n# Explanation: The encoded message can represent any of the encoded messages \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", or \"9\".\n# \n# Each of these can be decoded to the strings \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", and \"I\" respectively.\n# \n# Hence, there are a total of 9 ways to decode \"*\".\n# \n# \n# Example 2:\n# Input: s = \"1*\"\n# Output: 18\n# Explanation: The encoded message can represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\".\n# \n# Each of these encoded messages have 2 ways to be decoded (e.g. \"11\" can be decoded to \"AA\" or \"K\").\n# \n# Hence, there are a total of 9 * 2 = 18 ways to decode \"1*\".\n# \n# \n# Example 3:\n# Input: s = \"2*\"\n# Output: 15\n# Explanation: The encoded message can represent any of the encoded messages \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", or \"29\".\n# \n# \"21\", \"22\", \"23\", \"24\", \"25\", and \"26\" have 2 ways of being decoded, but \"27\", \"28\", and \"29\" only have 1 way.\n# \n# Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode \"2*\".\n# \n# \n# Constraints:\n# `1 <= s.length <= 105`\n# `s[i]` is a digit or `'*'`.\nclass Solution:\n def numDecodings(self, s: str) -> int:\n ", "entry_point": "numDecodings", "cannonical_solution": "", "test": ""}
{"task_id": "strange-printer", "prompt": "# There is a strange printer with the following two special requirements:\n# The printer can only print a sequence of the same character each time.\n# \n# At each turn, the printer can print new characters starting from and ending at any places, and will cover the original existing characters.\n# \n# Given a string consists of lower English letters only, your job is to count the minimum number of turns the printer needed in order to print it.\n# \n# \n# Example 1:\n# Input: \"aaabbb\"\n# Output: 2\n# Explanation: Print \"aaa\" first and then print \"bbb\".\n# \n# \n# Example 2:\n# Input: \"aba\"\n# Output: 2\n# Explanation: Print \"aaa\" first and then print \"b\" from the second place of the string, which will cover the existing character 'a'.\n# \n# Hint: Length of the given string will not exceed 100.\nclass Solution:\n def strangePrinter(self, s: str) -> int:\n ", "entry_point": "strangePrinter", "cannonical_solution": "", "test": ""}
{"task_id": "kth-smallest-number-in-multiplication-table", "prompt": "# Nearly every one have used the Multiplication Table. But could you find out the `k-th` smallest number quickly from the multiplication table?\n# Given the height `m` and the length `n` of a `m * n` Multiplication Table, and a positive integer `k`, you need to return the `k-th` smallest number in this table.\n# \n# \n# Example 1:\n# Input: m = 3, n = 3, k = 5\n# Output: \n# Explanation: \n# The Multiplication Table:\n# 1\t2\t3\n# 2\t4\t6\n# 3\t6\t9\n# The 5-th smallest number is 3 (1, 2, 2, 3, 3).\n# \n# \n# Example 2:\n# Input: m = 2, n = 3, k = 6\n# Output: \n# Explanation: \n# The Multiplication Table:\n# 1\t2\t3\n# 2\t4\t6\n# The 6-th smallest number is 6 (1, 2, 2, 3, 4, 6).\n# \n# Note:\n# The `m` and `n` will be in the range [1, 30000].\n# \n# The `k` will be in the range [1, m * n]\nclass Solution:\n def findKthNumber(self, m: int, n: int, k: int) -> int:\n ", "entry_point": "findKthNumber", "cannonical_solution": "", "test": ""}
{"task_id": "cut-off-trees-for-golf-event", "prompt": "# You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an `m x n` matrix. In this matrix:\n# `0` means the cell cannot be walked through.\n# \n# `1` represents an empty cell that can be walked through.\n# \n# A number greater than `1` represents a tree in a cell that can be walked through, and this number is the tree's height.\n# \n# In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.\n# \n# You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes `1` (an empty cell).\n# \n# Starting from the point `(0, 0)`, return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return `-1`.\n# \n# You are guaranteed that no two trees have the same height, and there is at least one tree needs to be cut off.\n# \n# \n# Example 1:\n# Input: forest = [[1,2,3],[0,0,4],[7,6,5]]\n# Output: 6\n# Explanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.\n# \n# \n# Example 2:\n# Input: forest = [[1,2,3],[0,0,0],[7,6,5]]\n# Output: -1\n# Explanation: The trees in the bottom row cannot be accessed as the middle row is blocked.\n# \n# \n# Example 3:\n# Input: forest = [[2,3,4],[0,0,5],[8,7,6]]\n# Output: 6\n# \n# Explanation: You can follow the same path as Example 1 to cut off all the trees.\n# \n# Note that you can cut off the first tree at (0, 0) before making any steps.\n# \n# \n# Constraints:\n# `m == forest.length`\n# `n == forest[i].length`\n# `1 <= m, n <= 50`\n# `0 <= forest[i][j] <= 109`\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n ", "entry_point": "cutOffTree", "cannonical_solution": "", "test": ""}
{"task_id": "24-game", "prompt": "# You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through `*`, `/`, `+`, `-`, `(`, `)` to get the value of 24.\n# \n# \n# Example 1:\n# Input: [4, 1, 8, 7]\n# Output: True\n# Explanation: (8-4) * (7-1) = 24\n# \n# Example 2:\n# Input: [1, 2, 1, 2]\n# Output: False\n# Note:\n# The division operator `/` represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.\n# \n# Every operation done is between two numbers. In particular, we cannot use `-` as a unary operator. For example, with `[1, 1, 1, 1]` as input, the expression `-1 - 1 - 1 - 1` is not allowed.\n# \n# You cannot concatenate numbers together. For example, if the input is `[1, 2, 1, 2]`, we cannot write this as 12 + 12.\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n ", "entry_point": "judgePoint24", "cannonical_solution": "", "test": ""}
{"task_id": "redundant-connection-ii", "prompt": "# In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.\n# \n# The given input is a directed graph that started as a rooted tree with `n` nodes (with distinct values from `1` to `n`), with one additional directed edge added. The added edge has two different vertices chosen from `1` to `n`, and was not an edge that already existed.\n# \n# The resulting graph is given as a 2D-array of `edges`. Each element of `edges` is a pair `[ui, vi]` that represents a directed edge connecting nodes `ui` and `vi`, where `ui` is a parent of child `vi`.\n# \n# Return an edge that can be removed so that the resulting graph is a rooted tree of `n` nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.\n# \n# \n# Example 1:\n# Input: edges = [[1,2],[1,3],[2,3]]\n# Output: [2,3]\n# \n# Example 2:\n# Input: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]\n# Output: [4,1]\n# \n# Constraints:\n# `n == edges.length`\n# `3 <= n <= 1000`\n# `edges[i].length == 2`\n# `1 <= ui, vi <= n`\nclass Solution:\n def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:\n ", "entry_point": "findRedundantDirectedConnection", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-sum-of-3-non-overlapping-subarrays", "prompt": "# In a given array `nums` of positive integers, find three non-overlapping subarrays with maximum sum.\n# \n# Each subarray will be of size `k`, and we want to maximize the sum of all `3*k` entries.\n# \n# Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.\n# \n# \n# Example:\n# Input: [1,2,1,2,6,7,5,1], 2\n# Output: [0, 3, 5]\n# Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\n# \n# We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.\n# \n# Note:\n# `nums.length` will be between 1 and 20000.\n# \n# `nums[i]` will be between 1 and 65535.\n# \n# `k` will be between 1 and floor(nums.length / 3).\nclass Solution:\n def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:\n ", "entry_point": "maxSumOfThreeSubarrays", "cannonical_solution": "", "test": ""}
{"task_id": "stickers-to-spell-word", "prompt": "# We are given N different types of stickers. Each sticker has a lowercase English word on it.\n# \n# You would like to spell out the given `target` string by cutting individual letters from your collection of stickers and rearranging them.\n# \n# You can use each sticker more than once if you want, and you have infinite quantities of each sticker.\n# \n# What is the minimum number of stickers that you need to spell out the `target`? If the task is impossible, return -1.\n# \n# \n# Example 1:\n# Input:[\"with\", \"example\", \"science\"], \"thehat\"\n# Output:3\n# Explanation:We can use 2 \"with\" stickers, and 1 \"example\" sticker.\n# \n# After cutting and rearrange the letters of those stickers, we can form the target \"thehat\".\n# \n# Also, this is the minimum number of stickers necessary to form the target string.\n# \n# \n# Example 2:\n# Input:[\"notice\", \"possible\"], \"basicbasic\"\n# Output:-1\n# Explanation:We can't form the target \"basicbasic\" from cutting letters from the given stickers.\n# \n# Note:\n# `stickers` has length in the range `[1, 50]`.\n# \n# `stickers` consists of lowercase English words (without apostrophes).\n# \n# `target` has length in the range `[1, 15]`, and consists of lowercase English letters.\n# \n# In all test cases, all words were chosen randomly from the 1000 most common US English words, and the target was chosen as a concatenation of two random words.\n# \n# The time limit may be more challenging than usual. It is expected that a 50 sticker test case can be solved within 35ms on average.\nclass Solution:\n def minStickers(self, stickers: List[str], target: str) -> int:\n ", "entry_point": "minStickers", "cannonical_solution": "", "test": ""}
{"task_id": "falling-squares", "prompt": "# On an infinite number line (x-axis), we drop given squares in the order they are given.\n# \n# The `i`-th square dropped (`positions[i] = (left, side_length)`) is a square with the left-most point being `positions[i][0]` and sidelength `positions[i][1]`.\n# \n# The square is dropped with the bottom edge parallel to the number line, and from a higher height than all currently landed squares. We wait for each square to stick before dropping the next.\n# \n# The squares are infinitely sticky on their bottom edge, and will remain fixed to any positive length surface they touch (either the number line or another square). Squares dropped adjacent to each other will not stick together prematurely.\n# \n# Return a list `ans` of heights. Each height `ans[i]` represents the current highest height of any square we have dropped, after dropping squares represented by `positions[0], positions[1], ..., positions[i]`.\n# \n# \n# Example 1:\n# Input: [[1, 2], [2, 3], [6, 1]]\n# Output: [2, 5, 5]\n# Explanation:\n# After the first drop of `positions[0] = [1, 2]: _aa _aa ------- `The maximum height of any square is 2.\n# \n# After the second drop of `positions[1] = [2, 3]: __aaa __aaa __aaa _aa__ _aa__ -------------- `The maximum height of any square is 5. The larger square stays on top of the smaller square despite where its center of gravity is, because squares are infinitely sticky on their bottom edge.\n# \n# After the third drop of `positions[1] = [6, 1]: __aaa __aaa __aaa _aa _aa___a -------------- `The maximum height of any square is still 5. Thus, we return an answer of `[2, 5, 5]`.\n# \n# \n# Example 2:\n# Input: [[100, 100], [200, 100]]\n# Output: [100, 100]\n# Explanation: Adjacent squares don't get stuck prematurely - only their bottom edge can stick to surfaces.\n# \n# Note:\n# `1 <= positions.length <= 1000`.\n# \n# `1 <= positions[i][0] <= 10^8`.\n# \n# `1 <= positions[i][1] <= 10^6`.\nclass Solution:\n def fallingSquares(self, positions: List[List[int]]) -> List[int]:\n ", "entry_point": "fallingSquares", "cannonical_solution": "", "test": ""}
{"task_id": "random-pick-with-blacklist", "prompt": "# Given a blacklist `B` containing unique integers from `[0, N)`, write a function to return a uniform random integer from `[0, N)` which is NOT in `B`.\n# \n# Optimize it such that it minimizes the call to system\u2019s `Math.random()`.\n# \n# Note:\n# `1 <= N <= 1000000000`\n# `0 <= B.length < min(100000, N)`\n# `[0, N)` does NOT include N. See interval notation.\n# \n# \n# Example 1:\n# Input: \n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[1,[]],[],[],[]]\n# Output: [null,0,0,0]\n# \n# Example 2:\n# Input: \n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[2,[]],[],[],[]]\n# Output: [null,1,1,1]\n# \n# Example 3:\n# Input: \n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[3,[1]],[],[],[]]\n# Output: [null,0,0,2]\n# \n# Example 4:\n# Input: \n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[4,[2]],[],[],[]]\n# Output: [null,1,3,1]\n# Explanation of Input Syntax:\n# The input is two lists: the subroutines called and their arguments. `Solution`'s constructor has two arguments, `N` and the blacklist `B`. `pick` has no arguments. Arguments are always wrapped with a list, even if there aren't any.\nclass Solution:\n\n def __init__(self, n: int, blacklist: List[int]):\n \n\n def pick(self) -> int:\n \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(n, blacklist)\n# param_1 = obj.pick()", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "range-module", "prompt": "# A Range Module is a module that tracks ranges of numbers. Your task is to design and implement the following interfaces in an efficient manner.\n# \n# `addRange(int left, int right)` Adds the half-open interval `[left, right)`, tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval `[left, right)` that are not already tracked.\n# \n# `queryRange(int left, int right)` Returns true if and only if every real number in the interval `[left, right)`\n# is currently being tracked.\n# \n# `removeRange(int left, int right)` Stops tracking every real number currently being tracked in the interval `[left, right)`.\n# \n# \n# Example 1:\n# addRange(10, 20): null\n# removeRange(14, 16): null\n# queryRange(10, 14): true (Every number in [10, 14) is being tracked)\n# queryRange(13, 15): false (Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)\n# queryRange(16, 17): true (The number 16 in [16, 17) is still being tracked, despite the remove operation)\n# Note:\n# A half open interval `[left, right)` denotes all real numbers `left <= x < right`.\n# \n# `0 < left < right < 10^9` in all calls to `addRange, queryRange, removeRange`.\n# \n# The total number of calls to `addRange` in a single test case is at most `1000`.\n# \n# The total number of calls to `queryRange` in a single test case is at most `5000`.\n# \n# The total number of calls to `removeRange` in a single test case is at most `1000`.\nclass RangeModule:\n\n def __init__(self):\n \n\n def addRange(self, left: int, right: int) -> None:\n \n\n def queryRange(self, left: int, right: int) -> bool:\n \n\n def removeRange(self, left: int, right: int) -> None:\n \n\n\n# Your RangeModule object will be instantiated and called as such:\n# obj = RangeModule()\n# obj.addRange(left,right)\n# param_2 = obj.queryRange(left,right)\n# obj.removeRange(left,right)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "find-k-th-smallest-pair-distance", "prompt": "# Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B. \n# \n# Example 1:\n# Input:\n# nums = [1,3,1]\n# k = 1\n# Output: 0 \n# Explanation:\n# Here are all the pairs:\n# (1,3) -> 2\n# (1,1) -> 0\n# (3,1) -> 2\n# Then the 1st smallest distance pair is (1,1), and its distance is 0.\n# \n# Note:\n# `2 <= len(nums) <= 10000`.\n# \n# `0 <= nums[i] < 1000000`.\n# \n# `1 <= k <= len(nums) * (len(nums) - 1) / 2`.\nclass Solution:\n def smallestDistancePair(self, nums: List[int], k: int) -> int:\n ", "entry_point": "smallestDistancePair", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-atoms", "prompt": "# Given a chemical `formula` (given as a string), return the count of each atom.\n# \n# The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.\n# \n# One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow. For example, H2O and H2O2 are possible, but H1O2 is impossible.\n# \n# Two formulas concatenated together to produce another formula. For example, H2O2He3Mg4 is also a formula.\n# \n# A formula placed in parentheses, and a count (optionally added) is also a formula. For example, (H2O2) and (H2O2)3 are formulas.\n# \n# Given a `formula`, return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.\n# \n# \n# Example 1:\n# Input: formula = \"H2O\"\n# Output: \"H2O\"\n# Explanation: The count of elements are {'H': 2, 'O': 1}.\n# \n# \n# Example 2:\n# Input: formula = \"Mg(OH)2\"\n# Output: \"H2MgO2\"\n# Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.\n# \n# \n# Example 3:\n# Input: formula = \"K4(ON(SO3)2)2\"\n# Output: \"K4N2O14S4\"\n# Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.\n# \n# \n# Example 4:\n# Input: formula = \"Be32\"\n# Output: \"Be32\"\n# \n# Constraints:\n# `1 <= formula.length <= 1000`\n# `formula` consists of English letters, digits, `'('`, and `')'`.\n# \n# `formula` is always valid.\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n ", "entry_point": "countOfAtoms", "cannonical_solution": "", "test": ""}
{"task_id": "count-different-palindromic-subsequences", "prompt": "# Given a string S, find the number of different non-empty palindromic subsequences in S, and return that number modulo `10^9 + 7`.\n# \n# A subsequence of a string S is obtained by deleting 0 or more characters from S.\n# \n# A sequence is palindromic if it is equal to the sequence reversed.\n# \n# Two sequences `A_1, A_2, ...` and `B_1, B_2, ...` are different if there is some `i` for which `A_i != B_i`.\n# \n# \n# Example 1:\n# Input: \n# S = 'bccb'\n# Output: 6\n# Explanation: \n# The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.\n# \n# Note that 'bcb' is counted only once, even though it occurs twice.\n# \n# \n# Example 2:\n# Input: \n# S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba'\n# Output: 104860361\n# Explanation: \n# There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.\n# \n# Note:\n# The length of `S` will be in the range `[1, 1000]`.\n# \n# Each character `S[i]` will be in the set `{'a', 'b', 'c', 'd'}`.\nclass Solution:\n def countPalindromicSubsequences(self, s: str) -> int:\n ", "entry_point": "countPalindromicSubsequences", "cannonical_solution": "", "test": ""}
{"task_id": "my-calendar-iii", "prompt": "# A `k`-booking happens when `k` events have some non-empty intersection (i.e., there is some time that is common to all `k` events.)\n# You are given some events `[start, end)`, after each given event, return an integer `k` representing the maximum `k`-booking between all the previous events.\n# \n# Implement the `MyCalendarThree` class:\n# `MyCalendarThree()` Initializes the object.\n# \n# `int book(int start, int end)` Returns an integer `k` representing the largest integer such that there exists a `k`-booking in the calendar.\n# \n# \n# Example 1:\n# Input\n# [\"MyCalendarThree\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n# [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]\n# Output\n# [null, 1, 1, 2, 3, 3, 3]\n# Explanation\n# MyCalendarThree myCalendarThree = new MyCalendarThree();\n# myCalendarThree.book(10, 20); // return 1, The first event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\n# \n# myCalendarThree.book(50, 60); // return 1, The second event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\n# \n# myCalendarThree.book(10, 40); // return 2, The third event [10, 40) intersects the first event, and the maximum k-booking is a 2-booking.\n# \n# myCalendarThree.book(5, 15); // return 3, The remaining events cause the maximum K-booking to be only a 3-booking.\n# \n# myCalendarThree.book(5, 10); // return 3\n# myCalendarThree.book(25, 55); // return 3\n# \n# Constraints:\n# `0 <= start < end <= 109`\n# At most `400` calls will be made to `book`.\nclass MyCalendarThree:\n\n def __init__(self):\n \n\n def book(self, startTime: int, endTime: int) -> int:\n \n\n\n# Your MyCalendarThree object will be instantiated and called as such:\n# obj = MyCalendarThree()\n# param_1 = obj.book(startTime,endTime)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "parse-lisp-expression", "prompt": "# You are given a string `expression` representing a Lisp-like expression to return the integer value of.\n# \n# The syntax for these expressions is given as follows.\n# \n# An expression is either an integer, a let-expression, an add-expression, a mult-expression, or an assigned variable. Expressions always evaluate to a single integer.\n# \n# (An integer could be positive or negative.)\n# A let-expression takes the form `(let v1 e1 v2 e2 ... vn en expr)`, where `let` is always the string `\"let\"`, then there are 1 or more pairs of alternating variables and expressions, meaning that the first variable `v1` is assigned the value of the expression `e1`, the second variable `v2` is assigned the value of the expression `e2`, and so on sequentially; and then the value of this let-expression is the value of the expression `expr`.\n# \n# An add-expression takes the form `(add e1 e2)` where `add` is always the string `\"add\"`, there are always two expressions `e1, e2`, and this expression evaluates to the addition of the evaluation of `e1` and the evaluation of `e2`.\n# \n# A mult-expression takes the form `(mult e1 e2)` where `mult` is always the string `\"mult\"`, there are always two expressions `e1, e2`, and this expression evaluates to the multiplication of the evaluation of `e1` and the evaluation of `e2`.\n# \n# For the purposes of this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally for your convenience, the names \"add\", \"let\", or \"mult\" are protected and will never be used as variable names.\n# \n# Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on scope.\n# \n# \n# Evaluation Examples:\n# Input: (add 1 2)\n# Output: 3\n# Input: (mult 3 (add 2 3))\n# Output: 15\n# Input: (let x 2 (mult x 5))\n# Output: 10\n# Input: (let x 2 (mult x (let x 3 y 4 (add x y))))\n# Output: 14\n# Explanation: In the expression (add x y), when checking for the value of the variable x,\n# we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\n# \n# Since x = 3 is found first, the value of x is 3.\n# \n# Input: (let x 3 x 2 x)\n# Output: 2\n# Explanation: Assignment in let statements is processed sequentially.\n# \n# Input: (let x 1 y 2 x (add x y) (add x y))\n# Output: 5\n# Explanation: The first (add x y) evaluates as 3, and is assigned to x.\n# \n# The second (add x y) evaluates as 3+2 = 5.\n# \n# Input: (let x 2 (add (let x 3 (let x 4 x)) x))\n# Output: 6\n# Explanation: Even though (let x 4 x) has a deeper scope, it is outside the context\n# of the final x in the add-expression. That final x will equal 2.\n# \n# Input: (let a1 3 b2 (add a1 1) b2) \n# Output 4\n# Explanation: Variable names can contain digits after the first character.\n# \n# Note:\n# The given string `expression` is well formatted: There are no leading or trailing spaces, there is only a single space separating different components of the string, and no space between adjacent parentheses. The expression is guaranteed to be legal and evaluate to an integer.\n# \n# The length of `expression` is at most 2000. (It is also non-empty, as that would not be a legal expression.)\n# The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.\nclass Solution:\n def evaluate(self, expression: str) -> int:\n ", "entry_point": "evaluate", "cannonical_solution": "", "test": ""}
{"task_id": "cherry-pickup", "prompt": "# You are given an `n x n` `grid` representing a field of cherries, each cell is one of three possible integers.\n# \n# `0` means the cell is empty, so you can pass through,\n# `1` means the cell contains a cherry that you can pick up and pass through, or\n# `-1` means the cell contains a thorn that blocks your way.\n# \n# Return the maximum number of cherries you can collect by following the rules below:\n# Starting at the position `(0, 0)` and reaching `(n - 1, n - 1)` by moving right or down through valid path cells (cells with value `0` or `1`).\n# \n# After reaching `(n - 1, n - 1)`, returning to `(0, 0)` by moving left or up through valid path cells.\n# \n# When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell `0`.\n# \n# If there is no valid path between `(0, 0)` and `(n - 1, n - 1)`, then no cherries can be collected.\n# \n# \n# Example 1:\n# Input: grid = [[0,1,-1],[1,0,-1],[1,1,1]]\n# Output: 5\n# Explanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).\n# \n# 4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].\n# \n# Then, the player went left, up, up, left to return home, picking up one more cherry.\n# \n# The total number of cherries picked up is 5, and this is the maximum possible.\n# \n# \n# Example 2:\n# Input: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]\n# Output: 0\n# \n# Constraints:\n# `n == grid.length`\n# `n == grid[i].length`\n# `1 <= n <= 50`\n# `grid[i][j]` is `-1`, `0`, or `1`.\n# \n# `grid[0][0] != -1`\n# `grid[n - 1][n - 1] != -1`\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n ", "entry_point": "cherryPickup", "cannonical_solution": "", "test": ""}
{"task_id": "prefix-and-suffix-search", "prompt": "# Design a special dictionary which has some words and allows you to search the words in it by a prefix and a suffix.\n# \n# Implement the `WordFilter` class:\n# `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.\n# \n# `f(string prefix, string suffix)` Returns the index of the word in the dictionary which has the prefix `prefix` and the suffix `suffix`. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return `-1`.\n# \n# \n# Example 1:\n# Input\n# [\"WordFilter\", \"f\"]\n# [[[\"apple\"]], [\"a\", \"e\"]]\n# Output\n# [null, 0]\n# Explanation\n# WordFilter wordFilter = new WordFilter([\"apple\"]);\n# wordFilter.f(\"a\", \"e\"); // return 0, because the word at index 0 has prefix = \"a\" and suffix = 'e\".\n# \n# \n# Constraints:\n# `1 <= words.length <= 15000`\n# `1 <= words[i].length <= 10`\n# `1 <= prefix.length, suffix.length <= 10`\n# `words[i]`, `prefix` and `suffix` consist of lower-case English letters only.\n# \n# At most `15000` calls will be made to the function `f`.\nclass WordFilter:\n\n def __init__(self, words: List[str]):\n \n\n def f(self, pref: str, suff: str) -> int:\n \n\n\n# Your WordFilter object will be instantiated and called as such:\n# obj = WordFilter(words)\n# param_1 = obj.f(pref,suff)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "contain-virus", "prompt": "# A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.\n# \n# The world is modeled as a 2-D array of cells, where `0` represents uninfected cells, and `1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary.\n# \n# Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall.\n# \n# Resources are limited. Each day, you can install walls around only one region -- the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night. There will never be a tie.\n# \n# Can you save the day? If so, what is the number of walls required? If not, and the world becomes fully infected, return the number of walls used.\n# \n# \n# Example 1:\n# Input: grid = \n# [[0,1,0,0,0,0,0,1],\n# [0,1,0,0,0,0,0,1],\n# [0,0,0,0,0,0,0,1],\n# [0,0,0,0,0,0,0,0]]\n# Output: 10\n# Explanation:\n# There are 2 contaminated regions.\n# \n# On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:\n# [[0,1,0,0,0,0,1,1],\n# [0,1,0,0,0,0,1,1],\n# [0,0,0,0,0,0,1,1],\n# [0,0,0,0,0,0,0,1]]\n# On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.\n# \n# \n# Example 2:\n# Input: grid = \n# [[1,1,1],\n# [1,0,1],\n# [1,1,1]]\n# Output: 4\n# Explanation: Even though there is only one cell saved, there are 4 walls built.\n# \n# Notice that walls are only built on the shared boundary of two different cells.\n# \n# \n# Example 3:\n# Input: grid = \n# [[1,1,1,0,0,0,0,0,0],\n# [1,0,1,0,1,1,1,1,1],\n# [1,1,1,0,0,0,0,0,0]]\n# Output: 13\n# Explanation: The region on the left only builds two new walls.\n# \n# Note:\n# The number of rows and columns of `grid` will each be in the range `[1, 50]`.\n# \n# Each `grid[i][j]` will be either `0` or `1`.\n# \n# Throughout the described process, there is always a contiguous viral region that will infect strictly more uncontaminated squares in the next round.\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n ", "entry_point": "containVirus", "cannonical_solution": "", "test": ""}
{"task_id": "cracking-the-safe", "prompt": "# There is a box protected by a password. The password is a sequence of `n` digits where each digit can be one of the first `k` digits `0, 1, ..., k-1`.\n# \n# While entering a password, the last `n` digits entered will automatically be matched against the correct password.\n# \n# For example, assuming the correct password is `\"345\"`, if you type `\"012345\"`, the box will open because the correct password matches the suffix of the entered password.\n# \n# Return any password of minimum length that is guaranteed to open the box at some point of entering it.\n# \n# \n# Example 1:\n# Input: n = 1, k = 2\n# Output: \"01\"\n# Note: \"10\" will be accepted too.\n# \n# \n# Example 2:\n# Input: n = 2, k = 2\n# Output: \"00110\"\n# Note: \"01100\", \"10011\", \"11001\" will be accepted too.\n# \n# Note:\n# `n` will be in the range `[1, 4]`.\n# \n# `k` will be in the range `[1, 10]`.\n# \n# `k^n` will be at most `4096`.\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n ", "entry_point": "crackSafe", "cannonical_solution": "", "test": ""}
{"task_id": "set-intersection-size-at-least-two", "prompt": "# An integer interval `[a, b]` (for integers `a < b`) is a set of all consecutive integers from `a` to `b`, including `a` and `b`.\n# \n# Find the minimum size of a set S such that for every integer interval A in `intervals`, the intersection of S with A has a size of at least two.\n# \n# \n# Example 1:\n# Input: intervals = [[1,3],[1,4],[2,5],[3,5]]\n# Output: 3\n# Explanation: Consider the set S = {2, 3, 4}. For each interval, there are at least 2 elements from S in the interval.\n# \n# Also, there isn't a smaller size set that fulfills the above condition.\n# \n# Thus, we output the size of this set, which is 3.\n# \n# \n# Example 2:\n# Input: intervals = [[1,2],[2,3],[2,4],[4,5]]\n# Output: 5\n# Explanation: An example of a minimum sized set is {1, 2, 3, 4, 5}.\n# \n# \n# Constraints:\n# `1 <= intervals.length <= 3000`\n# `intervals[i].length == 2`\n# `0 <= ai < bi <= 108`\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n ", "entry_point": "intersectionSizeTwo", "cannonical_solution": "", "test": ""}
{"task_id": "special-binary-string", "prompt": "# Special binary strings are binary strings with the following two properties:\n# The number of 0's is equal to the number of 1's.\n# \n# Every prefix of the binary string has at least as many 1's as 0's.\n# \n# Given a special string `S`, a move consists of choosing two consecutive, non-empty, special substrings of `S`, and swapping them. (Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.)\n# At the end of any number of moves, what is the lexicographically largest resulting string possible?\n# \n# Example 1:\n# Input: S = \"11011000\"\n# Output: \"11100100\"\n# Explanation:\n# The strings \"10\" [occuring at S[1]] and \"1100\" [at S[3]] are swapped.\n# \n# This is the lexicographically largest string possible after some number of swaps.\n# \n# Note:\n# `S` has length at most `50`.\n# \n# `S` is guaranteed to be a special binary string as defined above.\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n ", "entry_point": "makeLargestSpecial", "cannonical_solution": "", "test": ""}
{"task_id": "couples-holding-hands", "prompt": "# N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats. \n# The people and seats are represented by an integer from `0` to `2N-1`, the couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, and so on with the last couple being `(2N-2, 2N-1)`.\n# \n# The couples' initial seating is given by `row[i]` being the value of the person who is initially sitting in the i-th seat.\n# \n# \n# Example 1:Input: row = [0, 2, 1, 3]\n# Output: 1\n# Explanation: We only need to swap the second (row[1]) and third (row[2]) person.\n# \n# \n# Example 2:Input: row = [3, 2, 0, 1]\n# Output: 0\n# Explanation: All couples are already seated side by side.\n# \n# Note:\n# `len(row)` is even and in the range of `[4, 60]`.\n# \n# `row` is guaranteed to be a permutation of `0...len(row)-1`.\nclass Solution:\n def minSwapsCouples(self, row: List[int]) -> int:\n ", "entry_point": "minSwapsCouples", "cannonical_solution": "", "test": ""}
{"task_id": "max-chunks-to-make-sorted-ii", "prompt": "# This question is the same as \"Max Chunks to Make Sorted\" except the integers of the given array are not necessarily distinct, the input array could be up to length `2000`, and the elements could be up to `10**8`.\n# \n# Given an array `arr` of integers (not necessarily distinct), we split the array into some number of \"chunks\" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.\n# \n# What is the most number of chunks we could have made?\n# \n# Example 1:\n# Input: arr = [5,4,3,2,1]\n# Output: 1\n# Explanation:\n# Splitting into two or more chunks will not return the required result.\n# \n# For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.\n# \n# \n# Example 2:\n# Input: arr = [2,1,3,4,4]\n# Output: 4\n# Explanation:\n# We can split into two chunks, such as [2, 1], [3, 4, 4].\n# \n# However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.\n# \n# Note:\n# `arr` will have length in range `[1, 2000]`.\n# \n# `arr[i]` will be an integer in range `[0, 10**8]`.\nclass Solution:\n def maxChunksToSorted(self, arr: List[int]) -> int:\n ", "entry_point": "maxChunksToSorted", "cannonical_solution": "", "test": ""}
{"task_id": "basic-calculator-iv", "prompt": "# Given an `expression` such as `expression = \"e + 8 - a + 5\"` and an evaluation map such as `{\"e\": 1}` (given in terms of `evalvars = [\"e\"]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `[\"-1*a\",\"14\"]`\n# An expression alternates chunks and symbols, with a space separating each chunk and symbol.\n# \n# A chunk is either an expression in parentheses, a variable, or a non-negative integer.\n# \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# \n# Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. For example, `expression = \"1 + 2 * 3\"` has an answer of `[\"7\"]`.\n# \n# The format of the output is as follows:\n# For each term of free variables with non-zero coefficient, we write the free variables within a term in sorted order lexicographically. For example, we would never write a term like `\"b*a*c\"`, only `\"a*b*c\"`.\n# \n# Terms have degree equal to the number of free variables being multiplied, counting multiplicity. (For example, `\"a*a*b*c\"` has degree 4.) We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.\n# \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# \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. For example, an expression of \"0\" has an output of [].\n# \n# \n# Examples:\n# Input: expression = \"e + 8 - a + 5\", evalvars = [\"e\"], evalints = [1]\n# Output: [\"-1*a\",\"14\"]\n# Input: expression = \"e - 8 + temperature - pressure\",\n# evalvars = [\"e\", \"temperature\"], evalints = [1, 12]\n# Output: [\"-1*pressure\",\"5\"]\n# Input: expression = \"(e + 8) * (e - 8)\", evalvars = [], evalints = []\n# Output: [\"1*e*e\",\"-64\"]\n# Input: expression = \"7 - 7\", evalvars = [], evalints = []\n# Output: []\n# Input: expression = \"a * b * c + b * a * c * 4\", evalvars = [], evalints = []\n# Output: [\"5*a*b*c\"]\n# Input: expression = \"((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))\",\n# evalvars = [], evalints = []\n# Output: [\"-1*a*a*b*b\",\"2*a*a*b*c\",\"-1*a*a*c*c\",\"1*a*b*b*b\",\"-1*a*b*b*c\",\"-1*a*b*c*c\",\"1*a*c*c*c\",\"-1*b*b*b*c\",\"2*b*b*c*c\",\"-1*b*c*c*c\",\"2*a*a*b\",\"-2*a*a*c\",\"-2*a*b*b\",\"2*a*c*c\",\"1*b*b*b\",\"-1*b*b*c\",\"1*b*c*c\",\"-1*c*c*c\",\"-1*a*a\",\"1*a*b\",\"1*a*c\",\"-1*b*c\"]\n# Note:\n# `expression` will have length in range `[1, 250]`.\n# \n# `evalvars, evalints` will have equal lengths in range `[0, 100]`.\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n ", "entry_point": "basicCalculatorIV", "cannonical_solution": "", "test": ""}
{"task_id": "sliding-puzzle", "prompt": "# On a 2x3 `board`, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0.\n# \n# A move consists of choosing `0` and a 4-directionally adjacent number and swapping it.\n# \n# The state of the board is solved if and only if the `board` is `[[1,2,3],[4,5,0]].`\n# Given a puzzle board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.\n# \n# \n# Examples:\n# Input: board = [[1,2,3],[4,0,5]]\n# Output: 1\n# Explanation: Swap the 0 and the 5 in one move.\n# \n# Input: board = [[1,2,3],[5,4,0]]\n# Output: -1\n# Explanation: No number of moves will make the board solved.\n# \n# Input: board = [[4,1,2],[5,0,3]]\n# Output: 5\n# Explanation: 5 is the smallest number of moves that solves the board.\n# \n# An example path:\n# After move 0: [[4,1,2],[5,0,3]]\n# After move 1: [[4,1,2],[0,5,3]]\n# After move 2: [[0,1,2],[4,5,3]]\n# After move 3: [[1,0,2],[4,5,3]]\n# After move 4: [[1,2,0],[4,5,3]]\n# After move 5: [[1,2,3],[4,5,0]]\n# Input: board = [[3,2,4],[1,5,0]]\n# Output: 14\n# Note:\n# `board` will be a 2 x 3 array as described above.\n# \n# `board[i][j]` will be a permutation of `[0, 1, 2, 3, 4, 5]`.\nclass Solution:\n def slidingPuzzle(self, board: List[List[int]]) -> int:\n ", "entry_point": "slidingPuzzle", "cannonical_solution": "", "test": ""}
{"task_id": "swim-in-rising-water", "prompt": "# On an N x N `grid`, each square `grid[i][j]` represents the elevation at that point `(i,j)`.\n# \n# Now rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distance in zero time. Of course, you must stay within the boundaries of the grid during your swim.\n# \n# You start at the top left square `(0, 0)`. What is the least time until you can reach the bottom right square `(N-1, N-1)`?\n# \n# Example 1:\n# Input: [[0,2],[1,3]]\n# Output: 3\n# Explanation:\n# At time `0`, you are in grid location `(0, 0)`.\n# \n# You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\n# \n# You cannot reach point `(1, 1)` until time `3`.\n# \n# When the depth of water is `3`, we can swim anywhere inside the grid.\n# \n# \n# Example 2:\n# Input: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]\n# Output: 16\n# Explanation:\n# 0 1 2 3 4\n# 24 23 22 21 5\n# 12 13 14 15 16\n# 11 17 18 19 20\n# 10 9 8 7 6\n# The final route is marked in bold.\n# \n# We need to wait until time 16 so that (0, 0) and (4, 4) are connected.\n# \n# Note:\n# `2 <= N <= 50`.\n# \n# grid[i][j] is a permutation of [0, ..., N*N - 1].\nclass Solution:\n def swimInWater(self, grid: List[List[int]]) -> int:\n ", "entry_point": "swimInWater", "cannonical_solution": "", "test": ""}
{"task_id": "reaching-points", "prompt": "# A move consists of taking a point `(x, y)` and transforming it to either `(x, x+y)` or `(x+y, y)`.\n# \n# Given a starting point `(sx, sy)` and a target point `(tx, ty)`, return `True` if and only if a sequence of moves exists to transform the point `(sx, sy)` to `(tx, ty)`. Otherwise, return `False`.\n# \n# \n# Examples:\n# Input: sx = 1, sy = 1, tx = 3, ty = 5\n# Output: True\n# Explanation:\n# One series of moves that transforms the starting point to the target is:\n# (1, 1) -> (1, 2)\n# (1, 2) -> (3, 2)\n# (3, 2) -> (3, 5)\n# Input: sx = 1, sy = 1, tx = 2, ty = 2\n# Output: False\n# Input: sx = 1, sy = 1, tx = 1, ty = 1\n# Output: True\n# Note:\n# `sx, sy, tx, ty` will all be integers in the range `[1, 10^9]`.\nclass Solution:\n def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:\n ", "entry_point": "reachingPoints", "cannonical_solution": "", "test": ""}
{"task_id": "transform-to-chessboard", "prompt": "# An N x N `board` contains only `0`s and `1`s. In each move, you can swap any 2 rows with each other, or any 2 columns with each other.\n# \n# What is the minimum number of moves to transform the board into a \"chessboard\" - a board where no `0`s and no `1`s are 4-directionally adjacent? If the task is impossible, return -1.\n# \n# \n# Examples:\n# Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]\n# Output: 2\n# Explanation:\n# One potential sequence of moves is shown below, from left to right:\n# 0110 1010 1010\n# 0110 --> 1010 --> 0101\n# 1001 0101 1010\n# 1001 0101 0101\n# The first move swaps the first and second column.\n# \n# The second move swaps the second and third row.\n# \n# Input: board = [[0, 1], [1, 0]]\n# Output: 0\n# Explanation:\n# Also note that the board with 0 in the top left corner,\n# 01\n# 10\n# is also a valid chessboard.\n# \n# Input: board = [[1, 0], [1, 0]]\n# Output: -1\n# Explanation:\n# No matter what sequence of moves you make, you cannot end with a valid chessboard.\n# \n# Note:\n# `board` will have the same number of rows and columns, a number in the range `[2, 30]`.\n# \n# `board[i][j]` will be only `0`s or `1`s.\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n ", "entry_point": "movesToChessboard", "cannonical_solution": "", "test": ""}
{"task_id": "k-th-smallest-prime-fraction", "prompt": "# You are given a sorted integer array `arr` containing `1` and prime numbers, where all the integers of `arr` are unique. You are also given an integer `k`.\n# \n# For every `i` and `j` where `0 <= i < j < arr.length`, we consider the fraction `arr[i] / arr[j]`.\n# \n# Return the `kth` smallest fraction considered. Return your answer as an array of integers of size `2`, where `answer[0] == arr[i]` and `answer[1] == arr[j]`.\n# \n# \n# Example 1:\n# Input: arr = [1,2,3,5], k = 3\n# Output: [2,5]\n# Explanation: The fractions to be considered in sorted order are:\n# 1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.\n# \n# The third fraction is 2/5.\n# \n# \n# Example 2:\n# Input: arr = [1,7], k = 1\n# Output: [1,7]\n# \n# Constraints:\n# `2 <= arr.length <= 1000`\n# `1 <= arr[i] <= 3 * 104`\n# `arr[0] == 1`\n# `arr[i]` is a prime number for `i > 0`.\n# \n# All the numbers of `arr` are unique and sorted in strictly increasing order.\n# \n# `1 <= k <= arr.length * (arr.length - 1) / 2`\nclass Solution:\n def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]:\n ", "entry_point": "kthSmallestPrimeFraction", "cannonical_solution": "", "test": ""}
{"task_id": "preimage-size-of-factorial-zeroes-function", "prompt": "# Let `f(x)` be the number of zeroes at the end of `x!`. (Recall that `x! = 1 * 2 * 3 * ... * x`, and by convention, `0! = 1`.)\n# For example, `f(3) = 0` because 3! = 6 has no zeroes at the end, while `f(11) = 2` because 11! = 39916800 has 2 zeroes at the end. Given `K`, find how many non-negative integers `x` have the property that `f(x) = K`.\n# \n# \n# Example 1:\n# Input: K = 0\n# Output: 5\n# Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes.\n# \n# \n# Example 2:\n# Input: K = 5\n# Output: 0\n# Explanation: There is no x such that x! ends in K = 5 zeroes.\n# \n# Note:\n# `K` will be an integer in the range `[0, 10^9]`.\nclass Solution:\n def preimageSizeFZF(self, k: int) -> int:\n ", "entry_point": "preimageSizeFZF", "cannonical_solution": "", "test": ""}
{"task_id": "smallest-rotation-with-highest-score", "prompt": "# Given an array `A`, we may rotate it by a non-negative integer `K` so that the array becomes `A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1]`. Afterward, any entries that are less than or equal to their index are worth 1 point. \n# For example, if we have `[2, 4, 1, 3, 0]`, and we rotate by `K = 2`, it becomes `[1, 3, 0, 2, 4]`. This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point].\n# \n# Over all possible rotations, return the rotation index K that corresponds to the highest score we could receive. If there are multiple answers, return the smallest such index K.\n# \n# \n# Example 1:\n# Input: [2, 3, 1, 4, 0]\n# Output: 3\n# Explanation: \n# Scores for each K are listed below: \n# K = 0, A = [2,3,1,4,0], score 2\n# K = 1, A = [3,1,4,0,2], score 3\n# K = 2, A = [1,4,0,2,3], score 3\n# K = 3, A = [4,0,2,3,1], score 4\n# K = 4, A = [0,2,3,1,4], score 3\n# So we should choose K = 3, which has the highest score.\n# \n# \n# Example 2:\n# Input: [1, 3, 0, 2, 4]\n# Output: 0\n# Explanation: A will always have 3 points no matter how it shifts.\n# \n# So we will choose the smallest K, which is 0.\n# \n# Note:\n# `A` will have length at most `20000`.\n# \n# `A[i]` will be in the range `[0, A.length]`.\nclass Solution:\n def bestRotation(self, nums: List[int]) -> int:\n ", "entry_point": "bestRotation", "cannonical_solution": "", "test": ""}
{"task_id": "bricks-falling-when-hit", "prompt": "# You are given an `m x n` binary `grid`, where each `1` represents a brick and `0` represents an empty space. A brick is stable if:\n# It is directly connected to the top of the grid, or\n# At least one other brick in its four adjacent cells is stable.\n# \n# You are also given an array `hits`, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location `hits[i] = (rowi, coli)`. The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the `grid` (i.e., it does not land on other stable bricks).\n# \n# Return an array `result`, where each `result[i]` is the number of bricks that will fall after the `ith` erasure is applied.\n# \n# Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.\n# \n# \n# Example 1:\n# Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]\n# Output: [2]\n# Explanation: Starting with the grid:\n# [[1,0,0,0],\n# [1,1,1,0]]\n# We erase the underlined brick at (1,0), resulting in the grid:\n# [[1,0,0,0],\n# [0,1,1,0]]\n# The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:\n# [[1,0,0,0],\n# [0,0,0,0]]\n# Hence the result is [2].\n# \n# \n# Example 2:\n# Input: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]\n# Output: [0,0]\n# Explanation: Starting with the grid:\n# [[1,0,0,0],\n# [1,1,0,0]]\n# We erase the underlined brick at (1,1), resulting in the grid:\n# [[1,0,0,0],\n# [1,0,0,0]]\n# All remaining bricks are still stable, so no bricks fall. The grid remains the same:\n# [[1,0,0,0],\n# [1,0,0,0]]\n# Next, we erase the underlined brick at (1,0), resulting in the grid:\n# [[1,0,0,0],\n# [0,0,0,0]]\n# Once again, all remaining bricks are still stable, so no bricks fall.\n# \n# Hence the result is [0,0].\n# \n# \n# Constraints:\n# `m == grid.length`\n# `n == grid[i].length`\n# `1 <= m, n <= 200`\n# `grid[i][j]` is `0` or `1`.\n# \n# `1 <= hits.length <= 4 * 104`\n# `hits[i].length == 2`\n# `0 <= xi <= m - 1`\n# `0 <= yi <= n - 1`\n# All `(xi, yi)` are unique.\nclass Solution:\n def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:\n ", "entry_point": "hitBricks", "cannonical_solution": "", "test": ""}
{"task_id": "split-array-with-same-average", "prompt": "# You are given an integer array `nums`.\n# \n# You should move each element of `nums` into one of the two arrays `A` and `B` such that `A` and `B` are non-empty, and `average(A) == average(B)`.\n# \n# Return `true` if it is possible to achieve that and `false` otherwise.\n# \n# Note that for an array `arr`, `average(arr)` is the sum of all the elements of `arr` over the length of `arr`.\n# \n# \n# Example 1:\n# Input: nums = [1,2,3,4,5,6,7,8]\n# Output: true\n# Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.\n# \n# \n# Example 2:\n# Input: nums = [3,1]\n# Output: false\n# \n# Constraints:\n# `1 <= nums.length <= 30`\n# `0 <= nums[i] <= 104`\nclass Solution:\n def splitArraySameAverage(self, nums: List[int]) -> bool:\n ", "entry_point": "splitArraySameAverage", "cannonical_solution": "", "test": ""}
{"task_id": "chalkboard-xor-game", "prompt": "# We are given non-negative integers nums[i] which are written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. (Also, we'll say the bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.)\n# Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.\n# \n# Return True if and only if Alice wins the game, assuming both players play optimally.\n# \n# \n# Example:\n# Input: nums = [1, 1, 2]\n# Output: false\n# Explanation: \n# Alice has two choices: erase 1 or erase 2. \n# If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. \n# If Alice erases 2 first, now nums becomes [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.\n# \n# Notes: \n# `1 <= N <= 1000`. \n# `0 <= nums[i] <= 2^16`.\nclass Solution:\n def xorGame(self, nums: List[int]) -> bool:\n ", "entry_point": "xorGame", "cannonical_solution": "", "test": ""}
{"task_id": "bus-routes", "prompt": "# You are given an array `routes` representing bus routes where `routes[i]` is a bus 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# \n# You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only.\n# \n# Return the least number of buses you must take to travel from `source` to `target`. Return `-1` if it is not possible.\n# \n# \n# Example 1:\n# Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6\n# Output: 2\n# Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.\n# \n# \n# Example 2:\n# Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12\n# Output: -1\n# \n# Constraints:\n# `1 <= routes.length <= 500`.\n# \n# `1 <= routes[i].length <= 105`\n# All the values of `routes[i]` are unique.\n# \n# `sum(routes[i].length) <= 105`\n# `0 <= routes[i][j] < 106`\n# `0 <= source, target < 106`\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n ", "entry_point": "numBusesToDestination", "cannonical_solution": "", "test": ""}
{"task_id": "race-car", "prompt": "# Your car starts at position 0 and speed +1 on an infinite number line. (Your car can go into negative positions.)\n# Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse).\n# \n# When you get an instruction \"A\", your car does the following: `position += speed, speed *= 2`.\n# \n# When you get an instruction \"R\", your car does the following: if your speed is positive then `speed = -1` , otherwise `speed = 1`. (Your position stays the same.)\n# For example, after commands \"AAR\", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1.\n# \n# Now for some target position, say the length of the shortest sequence of instructions to get there.\n# \n# \n# Example 1:\n# Input: \n# target = 3\n# Output: 2\n# Explanation: \n# The shortest instruction sequence is \"AA\".\n# \n# Your position goes from 0->1->3.\n# \n# \n# Example 2:\n# Input: \n# target = 6\n# Output: 5\n# Explanation: \n# The shortest instruction sequence is \"AAARA\".\n# \n# Your position goes from 0->1->3->7->7->6.\n# \n# Note: \n# `1 <= target <= 10000`.\nclass Solution:\n def racecar(self, target: int) -> int:\n ", "entry_point": "racecar", "cannonical_solution": "", "test": ""}
{"task_id": "making-a-large-island", "prompt": "# You are given an `n x n` binary matrix `grid`. You are allowed to change at most one `0` to be `1`.\n# \n# Return the size of the largest island in `grid` after applying this operation.\n# \n# An island is a 4-directionally connected group of `1`s.\n# \n# \n# Example 1:\n# Input: grid = [[1,0],[0,1]]\n# Output: 3\n# Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.\n# \n# \n# Example 2:\n# Input: grid = [[1,1],[1,0]]\n# Output: 4\n# Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.\n# \n# \n# Example 3:\n# Input: grid = [[1,1],[1,1]]\n# Output: 4\n# Explanation: Can't change any 0 to 1, only one island with area = 4.\n# \n# \n# Constraints:\n# `n == grid.length`\n# `n == grid[i].length`\n# `1 <= n <= 500`\n# `grid[i][j]` is either `0` or `1`.\nclass Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n ", "entry_point": "largestIsland", "cannonical_solution": "", "test": ""}
{"task_id": "count-unique-characters-of-all-substrings-of-a-given-string", "prompt": "# Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`, for example if `s = \"LEETCODE\"` then `\"L\"`, `\"T\"`,`\"C\"`,`\"O\"`,`\"D\"` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`.\n# \n# On this problem given a string `s` we need to return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. Notice that some substrings can be repeated so on this case you have to count the repeated ones too.\n# \n# Since the answer can be very large, return the answer modulo `10 ^ 9 + 7`.\n# \n# \n# Example 1:\n# Input: s = \"ABC\"\n# Output: 10\n# Explanation: All possible substrings are: \"A\",\"B\",\"C\",\"AB\",\"BC\" and \"ABC\".\n# \n# Evey substring is composed with only unique letters.\n# \n# Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10\n# \n# Example 2:\n# Input: s = \"ABA\"\n# Output: 8\n# Explanation: The same as example 1, except `countUniqueChars`(\"ABA\") = 1.\n# \n# \n# Example 3:\n# Input: s = \"LEETCODE\"\n# Output: 92\n# \n# Constraints:\n# `0 <= s.length <= 10^4`\n# `s` contain upper-case English letters only.\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n ", "entry_point": "uniqueLetterString", "cannonical_solution": "", "test": ""}
{"task_id": "consecutive-numbers-sum", "prompt": "# Given a positive integer `N`, how many ways can we write it as a sum of consecutive positive integers?\n# \n# Example 1:\n# Input: 5\n# Output: 2\n# Explanation: 5 = 5 = 2 + 3\n# \n# Example 2:\n# Input: 9\n# Output: 3\n# Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4\n# \n# Example 3:\n# Input: 15\n# Output: 4\n# Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5\n# Note: `1 <= N <= 10 ^ 9`.\nclass Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n ", "entry_point": "consecutiveNumbersSum", "cannonical_solution": "", "test": ""}
{"task_id": "sum-of-distances-in-tree", "prompt": "# An undirected, connected tree with `N` nodes labelled `0...N-1` and `N-1` `edges` are given.\n# \n# The `i`th edge connects nodes `edges[i][0] `and` edges[i][1]` together.\n# \n# Return a list `ans`, where `ans[i]` is the sum of the distances between node `i` and all other nodes.\n# \n# \n# Example 1:\n# Input: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]\n# Output: [8,12,6,10,10,10]\n# Explanation: \n# Here is a diagram of the given tree:\n# 0\n# / \\\n# 1 2\n# /|\\\n# 3 4 5\n# We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\n# equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer[0] = 8, and so on.\n# \n# Note: `1 <= N <= 10000`\nclass Solution:\n def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n ", "entry_point": "sumOfDistancesInTree", "cannonical_solution": "", "test": ""}
{"task_id": "similar-string-groups", "prompt": "# Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal.\n# \n# For example, `\"tars\"` and `\"rats\"` are similar (swapping at positions `0` and `2`), and `\"rats\"` and `\"arts\"` are similar, but `\"star\"` is not similar to `\"tars\"`, `\"rats\"`, or `\"arts\"`.\n# \n# Together, these form two connected groups by similarity: `{\"tars\", \"rats\", \"arts\"}` and `{\"star\"}`. Notice that `\"tars\"` and `\"arts\"` are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.\n# \n# We are given a list `strs` of strings where every string in `strs` is an anagram of every other string in `strs`. How many groups are there?\n# \n# Example 1:\n# Input: strs = [\"tars\",\"rats\",\"arts\",\"star\"]\n# Output: 2\n# \n# Example 2:\n# Input: strs = [\"omv\",\"ovm\"]\n# Output: 1\n# \n# Constraints:\n# `1 <= strs.length <= 300`\n# `1 <= strs[i].length <= 300`\n# `strs[i]` consists of lowercase letters only.\n# \n# All words in `strs` have the same length and are anagrams of each other.\nclass Solution:\n def numSimilarGroups(self, strs: List[str]) -> int:\n ", "entry_point": "numSimilarGroups", "cannonical_solution": "", "test": ""}
{"task_id": "shortest-path-visiting-all-nodes", "prompt": "# An undirected, connected graph of N nodes (labeled `0, 1, 2, ..., N-1`) is given as `graph`.\n# \n# `graph.length = N`, and `j != i` is in the list `graph[i]` exactly once, if and only if nodes `i` and `j` are connected.\n# \n# Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.\n# \n# \n# Example 1:\n# Input: [[1,2,3],[0],[0],[0]]\n# Output: 4\n# Explanation: One possible path is [1,0,2,0,3]\n# \n# Example 2:\n# Input: [[1],[0,2,4],[1,3,4],[2],[1,2]]\n# Output: 4\n# Explanation: One possible path is [0,1,4,2,3]\n# Note:\n# `1 <= graph.length <= 12`\n# `0 <= graph[i].length < graph.length`\nclass Solution:\n def shortestPathLength(self, graph: List[List[int]]) -> int:\n ", "entry_point": "shortestPathLength", "cannonical_solution": "", "test": ""}
{"task_id": "rectangle-area-ii", "prompt": "# We are given a list of (axis-aligned) `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2] `, where `(xi1, yi1)` are the coordinates of the bottom-left corner, and `(xi2, yi2)` are the coordinates of the top-right corner of the `ith` rectangle.\n# \n# Find the total area covered by all `rectangles` in the plane. Since the answer may be too large, return it modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]\n# Output: 6\n# Explanation: As illustrated in the picture.\n# \n# \n# Example 2:\n# Input: rectangles = [[0,0,1000000000,1000000000]]\n# Output: 49\n# Explanation: The answer is 1018 modulo (109 + 7), which is (109)2 = (-7)2 = 49.\n# \n# \n# Constraints:\n# `1 <= rectangles.length <= 200`\n# `rectanges[i].length = 4`\n# `0 <= rectangles[i][j] <= 109`\n# The total area covered by all rectangles will never exceed `263 - 1` and thus will fit in a 64-bit signed integer.\nclass Solution:\n def rectangleArea(self, rectangles: List[List[int]]) -> int:\n ", "entry_point": "rectangleArea", "cannonical_solution": "", "test": ""}
{"task_id": "k-similar-strings", "prompt": "# Strings `s1` and `s2` are `k`-similar (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`.\n# \n# Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`-similar.\n# \n# \n# Example 1:\n# Input: s1 = \"ab\", s2 = \"ba\"\n# Output: 1\n# \n# Example 2:\n# Input: s1 = \"abc\", s2 = \"bca\"\n# Output: 2\n# \n# Example 3:\n# Input: s1 = \"abac\", s2 = \"baca\"\n# Output: 2\n# \n# Example 4:\n# Input: s1 = \"aabc\", s2 = \"abca\"\n# Output: 2\n# \n# Constraints:\n# `1 <= s1.length <= 20`\n# `s2.length == s1.length`\n# `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`.\n# \n# `s2` is an anagram of `s1`.\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n ", "entry_point": "kSimilarity", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-cost-to-hire-k-workers", "prompt": "# There are `N` workers. The `i`-th worker has a `quality[i]` and a minimum wage expectation `wage[i]`.\n# \n# Now we want to hire exactly `K` workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:\n# Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.\n# \n# Every worker in the paid group must be paid at least their minimum wage expectation.\n# \n# Return the least amount of money needed to form a paid group satisfying the above conditions.\n# \n# \n# Example 1:\n# Input: quality = [10,20,5], wage = [70,50,30], K = 2\n# Output: 105.00000\n# Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.\n# \n# \n# Example 2:\n# Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3\n# Output: 30.66667\n# Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately. \n# Note:\n# `1 <= K <= N <= 10000`, where `N = quality.length = wage.length`\n# `1 <= quality[i] <= 10000`\n# `1 <= wage[i] <= 10000`\n# Answers within `10^-5` of the correct answer will be considered correct.\nclass Solution:\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:\n ", "entry_point": "mincostToHireWorkers", "cannonical_solution": "", "test": ""}
{"task_id": "shortest-subarray-with-sum-at-least-k", "prompt": "# Return the length of the shortest, non-empty, contiguous subarray of `A` with sum at least `K`.\n# \n# If there is no non-empty subarray with sum at least `K`, return `-1`.\n# \n# \n# Example 1:\n# Input: A = [1], K = 1\n# Output: 1\n# \n# Example 2:\n# Input: A = [1,2], K = 4\n# Output: -1\n# \n# Example 3:\n# Input: A = [2,-1,2], K = 3\n# Output: 3\n# Note:\n# `1 <= A.length <= 50000`\n# `-10 ^ 5 <= A[i] <= 10 ^ 5`\n# `1 <= K <= 10 ^ 9`\nclass Solution:\n def shortestSubarray(self, nums: List[int], k: int) -> int:\n ", "entry_point": "shortestSubarray", "cannonical_solution": "", "test": ""}
{"task_id": "shortest-path-to-get-all-keys", "prompt": "# We are given a 2-dimensional `grid`. `\".\"` is an empty cell, `\"#\"` is a wall, `\"@\"` is the starting point, (`\"a\"`, `\"b\"`, ...) are keys, and (`\"A\"`, `\"B\"`, ...) are locks.\n# \n# We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions. We cannot walk outside the grid, or walk into a wall. If we walk over a key, we pick it up. We can't walk over a lock unless we have the corresponding key.\n# \n# For some 1 <= K <= 6, there is exactly one lowercase and one uppercase letter of the first `K` letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.\n# \n# Return the lowest number of moves to acquire all keys. If it's impossible, return `-1`.\n# \n# \n# Example 1:\n# Input: [\"@.a.#\",\"###.#\",\"b.A.B\"]\n# Output: 8\n# \n# Example 2:\n# Input: [\"@..aA\",\"..B#.\",\"....b\"]\n# Output: 6\n# Note:\n# `1 <= grid.length <= 30`\n# `1 <= grid[0].length <= 30`\n# `grid[i][j]` contains only` '.'`, `'#'`, `'@'`, `'a'-``'f``'` and `'A'-'F'`\n# The number of keys is in `[1, 6]`. Each key has a different letter and opens exactly one lock.\nclass Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n ", "entry_point": "shortestPathAllKeys", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-number-of-refueling-stops", "prompt": "# A car travels from a starting position to a destination which is `target` miles east of the starting position.\n# \n# Along the way, there are gas stations. Each `station[i]` represents a gas station that is `station[i][0]` miles east of the starting position, and has `station[i][1]` liters of gas.\n# \n# The car starts with an infinite tank of gas, which initially has `startFuel` liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.\n# \n# When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.\n# \n# What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return `-1`.\n# \n# Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.\n# \n# \n# Example 1:\n# Input: target = 1, startFuel = 1, stations = []\n# Output: 0\n# Explanation: We can reach the target without refueling.\n# \n# \n# Example 2:\n# Input: target = 100, startFuel = 1, stations = [[10,100]]\n# Output: -1\n# Explanation: We can't reach the target (or even the first gas station).\n# \n# \n# Example 3:\n# Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]\n# Output: 2\n# Explanation: \n# We start with 10 liters of fuel.\n# \n# We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\n# \n# Then, we drive from position 10 to position 60 (expending 50 liters of fuel),\n# and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\n# \n# We made 2 refueling stops along the way, so we return 2.\n# \n# Note:\n# `1 <= target, startFuel, stations[i][1] <= 10^9`\n# `0 <= stations.length <= 500`\n# `0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target`\nclass Solution:\n def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:\n ", "entry_point": "minRefuelStops", "cannonical_solution": "", "test": ""}
{"task_id": "nth-magical-number", "prompt": "# A positive integer is magical if it is divisible by either `a` or `b`.\n# \n# Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, return it modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: n = 1, a = 2, b = 3\n# Output: 2\n# \n# Example 2:\n# Input: n = 4, a = 2, b = 3\n# Output: 6\n# \n# Example 3:\n# Input: n = 5, a = 2, b = 4\n# Output: 10\n# \n# Example 4:\n# Input: n = 3, a = 6, b = 4\n# Output: 8\n# \n# Constraints:\n# `1 <= n <= 109`\n# `2 <= a, b <= 4 * 104`\nclass Solution:\n def nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n ", "entry_point": "nthMagicalNumber", "cannonical_solution": "", "test": ""}
{"task_id": "profitable-schemes", "prompt": "# There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime.\n# \n# Let's call a profitable scheme any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`.\n# \n# Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: n = 5, minProfit = 3, group = [2,2], profit = [2,3]\n# Output: 2\n# Explanation: To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.\n# \n# In total, there are 2 schemes.\n# \n# \n# Example 2:\n# Input: n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]\n# Output: 7\n# Explanation: To make a profit of at least 5, the group could commit any crimes, as long as they commit one.\n# \n# There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).\n# \n# \n# Constraints:\n# `1 <= n <= 100`\n# `0 <= minProfit <= 100`\n# `1 <= group.length <= 100`\n# `1 <= group[i] <= 100`\n# `profit.length == group.length`\n# `0 <= profit[i] <= 100`\nclass Solution:\n def profitableSchemes(self, n: int, minProfit: int, group: List[int], profit: List[int]) -> int:\n ", "entry_point": "profitableSchemes", "cannonical_solution": "", "test": ""}
{"task_id": "reachable-nodes-in-subdivided-graph", "prompt": "# You are given an undirected graph (the \"original graph\") with `n` nodes labeled from `0` to `n - 1`. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.\n# \n# The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indicates that there is an edge between nodes `ui` and `vi` in the original graph, and `cnti` is the total number of new nodes that you will subdivide the edge into. Note that `cnti == 0` means you will not subdivide the edge.\n# \n# To subdivide the edge `[ui, vi]`, replace it with `(cnti + 1)` new edges and `cnti` new nodes. The new nodes are `x1`, `x2`, ..., `xcnti`, and the new edges are `[ui, x1]`, `[x1, x2]`, `[x2, x3]`, ..., `[xcnti+1, xcnti]`, `[xcnti, vi]`.\n# \n# In this new graph, you want to know how many nodes are reachable from the node `0`, where a node is reachable if the distance is `maxMoves` or less.\n# \n# Given the original graph and `maxMoves`, return the number of nodes that are reachable from node `0` in the new graph.\n# \n# \n# Example 1:\n# Input: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3\n# Output: 13\n# Explanation: The edge subdivisions are shown in the image above.\n# \n# The nodes that are reachable are highlighted in yellow.\n# \n# \n# Example 2:\n# Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4\n# Output: 23\n# \n# Example 3:\n# Input: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5\n# Output: 1\n# Explanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.\n# \n# \n# Constraints:\n# `0 <= edges.length <= min(n * (n - 1) / 2, 104)`\n# `edges[i].length == 3`\n# `0 <= ui < vi < n`\n# There are no multiple edges in the graph.\n# \n# `0 <= cnti <= 104`\n# `0 <= maxMoves <= 109`\n# `1 <= n <= 3000`\nclass Solution:\n def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:\n ", "entry_point": "reachableNodes", "cannonical_solution": "", "test": ""}
{"task_id": "super-egg-drop", "prompt": "# You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`.\n# \n# You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor higher than `f` will break, and any egg dropped at or below floor `f` will not break.\n# \n# Each move, you may take an unbroken egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.\n# \n# Return the minimum number of moves that you need to determine with certainty what the value of `f` is.\n# \n# \n# Example 1:\n# Input: k = 1, n = 2\n# Output: 2\n# Explanation: \n# Drop the egg from floor 1. If it breaks, we know that f = 0.\n# \n# Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1.\n# \n# If it does not break, then we know f = 2.\n# \n# Hence, we need at minimum 2 moves to determine with certainty what the value of f is.\n# \n# \n# Example 2:\n# Input: k = 2, n = 6\n# Output: 3\n# \n# Example 3:\n# Input: k = 3, n = 14\n# Output: 4\n# \n# Constraints:\n# `1 <= k <= 100`\n# `1 <= n <= 104`\nclass Solution:\n def superEggDrop(self, k: int, n: int) -> int:\n ", "entry_point": "superEggDrop", "cannonical_solution": "", "test": ""}
{"task_id": "sum-of-subsequence-widths", "prompt": "# Given an array of integers `A`, consider all non-empty subsequences of `A`.\n# \n# For any sequence S, let the width of S be the difference between the maximum and minimum element of S.\n# \n# Return the sum of the widths of all subsequences of A. \n# As the answer may be very large, return the answer modulo 10^9 + 7.\n# \n# \n# Example 1:\n# Input: [2,1,3]\n# Output: 6\n# Explanation:\n# Subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\n# \n# The corresponding widths are 0, 0, 0, 1, 1, 2, 2.\n# \n# The sum of these widths is 6.\n# \n# Note:\n# `1 <= A.length <= 20000`\n# `1 <= A[i] <= 20000`\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n ", "entry_point": "sumSubseqWidths", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-frequency-stack", "prompt": "# Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.\n# \n# Implement the `FreqStack` class:\n# `FreqStack()` constructs an empty frequency stack.\n# \n# `void push(int val)` pushes an integer `val` onto the top of the stack.\n# \n# `int pop()` removes and returns the most frequent element in the stack.\n# \n# \t\n# If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.\n# \n# \n# Example 1:\n# Input\n# [\"FreqStack\", \"push\", \"push\", \"push\", \"push\", \"push\", \"push\", \"pop\", \"pop\", \"pop\", \"pop\"]\n# [[], [5], [7], [5], [7], [4], [5], [], [], [], []]\n# Output\n# [null, null, null, null, null, null, null, 5, 7, 5, 4]\n# Explanation\n# FreqStack freqStack = new FreqStack();\n# freqStack.push(5); // The stack is [5]\n# freqStack.push(7); // The stack is [5,7]\n# freqStack.push(5); // The stack is [5,7,5]\n# freqStack.push(7); // The stack is [5,7,5,7]\n# freqStack.push(4); // The stack is [5,7,5,7,4]\n# freqStack.push(5); // The stack is [5,7,5,7,4,5]\n# freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].\n# \n# freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].\n# \n# freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4].\n# \n# freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].\n# \n# \n# Constraints:\n# `0 <= val <= 109`\n# At most `2 * 104` calls will be made to `push` and `pop`.\n# \n# It is guaranteed that there will be at least one element in the stack before calling `pop`.\nclass FreqStack:\n\n def __init__(self):\n \n\n def push(self, val: int) -> None:\n \n\n def pop(self) -> int:\n \n\n\n# Your FreqStack object will be instantiated and called as such:\n# obj = FreqStack()\n# obj.push(val)\n# param_2 = obj.pop()", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "orderly-queue", "prompt": "# A string `S` of lowercase letters is given. Then, we may make any number of moves.\n# \n# In each move, we choose one of the first `K` letters (starting from the left), remove it, and place it at the end of the string.\n# \n# Return the lexicographically smallest string we could have after any number of moves.\n# \n# \n# Example 1:\n# Input: S = \"cba\", K = 1\n# Output: \"acb\"\n# Explanation: \n# In the first move, we move the 1st character (\"c\") to the end, obtaining the string \"bac\".\n# \n# In the second move, we move the 1st character (\"b\") to the end, obtaining the final result \"acb\".\n# \n# \n# Example 2:\n# Input: S = \"baaca\", K = 3\n# Output: \"aaabc\"\n# Explanation: \n# In the first move, we move the 1st character (\"b\") to the end, obtaining the string \"aacab\".\n# \n# In the second move, we move the 3rd character (\"c\") to the end, obtaining the final result \"aaabc\".\n# \n# Note:\n# `1 <= K <= S.length <= 1000`\n# `S` consists of lowercase letters only.\nclass Solution:\n def orderlyQueue(self, s: str, k: int) -> str:\n ", "entry_point": "orderlyQueue", "cannonical_solution": "", "test": ""}
{"task_id": "numbers-at-most-n-given-digit-set", "prompt": "# Given an array of `digits` which is sorted in non-decreasing order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`.\n# \n# Return the number of positive integers that can be generated that are less than or equal to a given integer `n`.\n# \n# \n# Example 1:\n# Input: digits = [\"1\",\"3\",\"5\",\"7\"], n = 100\n# Output: 20\n# Explanation: \n# The 20 numbers that can be written are:\n# 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.\n# \n# \n# Example 2:\n# Input: digits = [\"1\",\"4\",\"9\"], n = 1000000000\n# Output: 29523\n# Explanation: \n# We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,\n# 81 four digit numbers, 243 five digit numbers, 729 six digit numbers,\n# 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.\n# \n# In total, this is 29523 integers that can be written using the digits array.\n# \n# \n# Example 3:\n# Input: digits = [\"7\"], n = 8\n# Output: 1\n# \n# Constraints:\n# `1 <= digits.length <= 9`\n# `digits[i].length == 1`\n# `digits[i]` is a digit from `'1'` to `'9'`.\n# \n# All the values in `digits` are unique.\n# \n# `digits` is sorted in non-decreasing order.\n# \n# `1 <= n <= 109`\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n ", "entry_point": "atMostNGivenDigitSet", "cannonical_solution": "", "test": ""}
{"task_id": "valid-permutations-for-di-sequence", "prompt": "# We are given `S`, a length `n` string of characters from the set `{'D', 'I'}`. (These letters stand for \"decreasing\" and \"increasing\".)\n# A valid permutation is a permutation `P[0], P[1], ..., P[n]` of integers `{0, 1, ..., n}`, such that for all `i`:\n# If `S[i] == 'D'`, then `P[i] > P[i+1]`, and;\n# If `S[i] == 'I'`, then `P[i] < P[i+1]`.\n# \n# How many valid permutations are there? Since the answer may be large, return your answer modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: \"DID\"\n# Output: 5\n# Explanation: \n# The 5 valid permutations of (0, 1, 2, 3) are:\n# (1, 0, 3, 2)\n# (2, 0, 3, 1)\n# (2, 1, 3, 0)\n# (3, 0, 2, 1)\n# (3, 1, 2, 0)\n# Note:\n# `1 <= S.length <= 200`\n# `S` consists only of characters from the set `{'D', 'I'}`.\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n ", "entry_point": "numPermsDISequence", "cannonical_solution": "", "test": ""}
{"task_id": "super-palindromes", "prompt": "# Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.\n# \n# Given two positive integers `left` and `right` represented as strings, return the number of super-palindromes integers in the inclusive range `[left, right]`.\n# \n# \n# Example 1:\n# Input: left = \"4\", right = \"1000\"\n# Output: 4\n# Explanation: 4, 9, 121, and 484 are superpalindromes.\n# \n# Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.\n# \n# \n# Example 2:\n# Input: left = \"1\", right = \"2\"\n# Output: 1\n# \n# Constraints:\n# `1 <= left.length, right.length <= 18`\n# `left` and `right` consist of only digits.\n# \n# `left` and `right` cannot have leading zeros.\n# \n# `left` and `right` represent integers in the range `[1, 1018]`.\n# \n# `left` is less than or equal to `right`.\nclass Solution:\n def superpalindromesInRange(self, left: str, right: str) -> int:\n ", "entry_point": "superpalindromesInRange", "cannonical_solution": "", "test": ""}
{"task_id": "cat-and-mouse", "prompt": "# A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.\n# \n# The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph.\n# \n# The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`.\n# \n# During each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in `graph[1]`.\n# \n# Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)\n# Then, the game can end in three ways:\n# If ever the Cat occupies the same node as the Mouse, the Cat wins.\n# \n# If ever the Mouse reaches the Hole, the Mouse wins.\n# \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# \n# Given a `graph`, and assuming both players play optimally, return\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# \n# Example 1:\n# Input: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]\n# Output: 0\n# \n# Example 2:\n# Input: graph = [[1,3],[0],[3],[0,2]]\n# Output: 1\n# \n# Constraints:\n# `3 <= graph.length <= 50`\n# `1 <= graph[i].length < graph.length`\n# `0 <= graph[i][j] < graph.length`\n# `graph[i][j] != i`\n# `graph[i]` is unique.\n# \n# The mouse and the cat can always move.\nclass Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n ", "entry_point": "catMouseGame", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-music-playlists", "prompt": "# Your music player contains `N` different songs and she wants to listen to `L` (not necessarily different) songs during your trip. You create a playlist so that:\n# Every song is played at least once\n# A song can only be played again only if `K` other songs have been played\n# Return the number of possible playlists. As the answer can be very large, return it modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: N = 3, L = 3, K = 1\n# Output: 6\n# Explanation: There are 6 possible playlists. [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1].\n# \n# \n# Example 2:\n# Input: N = 2, L = 3, K = 0\n# Output: 6\n# Explanation: There are 6 possible playlists. [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], [1, 2, 2]\n# \n# Example 3:\n# Input: N = 2, L = 3, K = 1\n# Output: 2\n# Explanation: There are 2 possible playlists. [1, 2, 1], [2, 1, 2]\n# Note:\n# `0 <= K < N <= L <= 100`\nclass Solution:\n def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:\n ", "entry_point": "numMusicPlaylists", "cannonical_solution": "", "test": ""}
{"task_id": "minimize-malware-spread", "prompt": "# You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.\n# \n# Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.\n# \n# Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from `initial`.\n# \n# Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with the smallest index.\n# \n# Note that if a node was removed from the `initial` list of infected nodes, it might still be infected later due to the malware spread.\n# \n# \n# Example 1:\n# Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\n# Output: 0\n# \n# Example 2:\n# Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]\n# Output: 0\n# \n# Example 3:\n# Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]\n# Output: 1\n# \n# Constraints:\n# `n == graph.length`\n# `n == graph[i].length`\n# `2 <= n <= 300`\n# `graph[i][j]` is `0` or `1`.\n# \n# `graph[i][j] == graph[j][i]`\n# `graph[i][i] == 1`\n# `1 <= initial.length <= n`\n# `0 <= initial[i] <= n - 1`\n# All the integers in `initial` are unique.\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n ", "entry_point": "minMalwareSpread", "cannonical_solution": "", "test": ""}
{"task_id": "three-equal-parts", "prompt": "# You are given an array `arr` which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value.\n# \n# If it is possible, return any `[i, j]` with `i + 1 < j`, such that:\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# \n# All three parts have equal binary values.\n# \n# If it is not possible, return `[-1, -1]`.\n# \n# Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros are allowed, so `[0,1,1]` and `[1,1]` represent the same value.\n# \n# \n# Example 1:\n# Input: arr = [1,0,1,0,1]\n# Output: [0,3]\n# \n# Example 2:\n# Input: arr = [1,1,0,1,1]\n# Output: [-1,-1]\n# \n# Example 3:\n# Input: arr = [1,1,0,0,1]\n# Output: [0,2]\n# \n# Constraints:\n# `3 <= arr.length <= 3 * 104`\n# `arr[i]` is `0` or `1`\nclass Solution:\n def threeEqualParts(self, arr: List[int]) -> List[int]:\n ", "entry_point": "threeEqualParts", "cannonical_solution": "", "test": ""}
{"task_id": "minimize-malware-spread-ii", "prompt": "# You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.\n# \n# Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.\n# \n# Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops.\n# \n# We will remove exactly one node from `initial`, completely removing it and any connections from this node to any other node.\n# \n# Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with the smallest index.\n# \n# \n# Example 1:\n# Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\n# Output: 0\n# \n# Example 2:\n# Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]\n# Output: 1\n# \n# Example 3:\n# Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]\n# Output: 1\n# \n# Constraints:\n# `n == graph.length`\n# `n == graph[i].length`\n# `2 <= n <= 300`\n# `graph[i][j]` is `0` or `1`.\n# \n# `graph[i][j] == graph[j][i]`\n# `graph[i][i] == 1`\n# `1 <= initial.length < n`\n# `0 <= initial[i] <= n - 1`\n# All the integers in `initial` are unique.\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n ", "entry_point": "minMalwareSpread", "cannonical_solution": "", "test": ""}
{"task_id": "stamping-the-sequence", "prompt": "# You want to form a `target` string of lowercase letters.\n# \n# At the beginning, your sequence is `target.length` `'?'` marks. You also have a `stamp` of lowercase letters.\n# \n# On each turn, you may place the stamp over the sequence, and replace every letter in the sequence with the corresponding letter from the stamp. You can make up to `10 * target.length` turns.\n# \n# For example, if the initial sequence is \"?????\", and your stamp is `\"abc\"`, then you may make \"abc??\", \"?abc?\", \"??abc\" in the first turn. (Note that the stamp must be fully contained in the boundaries of the sequence in order to stamp.)\n# If the sequence is possible to stamp, then return an array of the index of the left-most letter being stamped at each turn. If the sequence is not possible to stamp, return an empty array.\n# \n# For example, if the sequence is \"ababc\", and the stamp is `\"abc\"`, then we could return the answer `[0, 2]`, corresponding to the moves \"?????\" -> \"abc??\" -> \"ababc\".\n# \n# Also, if the sequence is possible to stamp, it is guaranteed it is possible to stamp within `10 * target.length` moves. Any answers specifying more than this number of moves will not be accepted.\n# \n# \n# Example 1:\n# Input: stamp = \"abc\", target = \"ababc\"\n# Output: [0,2]\n# ([1,0,2] would also be accepted as an answer, as well as some other answers.)\n# \n# Example 2:\n# Input: stamp = \"abca\", target = \"aabcaca\"\n# Output: [3,0,1]\n# Note:\n# `1 <= stamp.length <= target.length <= 1000`\n# `stamp` and `target` only contain lowercase letters.\nclass Solution:\n def movesToStamp(self, stamp: str, target: str) -> List[int]:\n ", "entry_point": "movesToStamp", "cannonical_solution": "", "test": ""}
{"task_id": "distinct-subsequences-ii", "prompt": "# Given a string `S`, count the number of distinct, non-empty subsequences of `S` .\n# \n# Since the result may be large, return the answer modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: \"abc\"\n# Output: 7\n# Explanation: The 7 distinct subsequences are \"a\", \"b\", \"c\", \"ab\", \"ac\", \"bc\", and \"abc\".\n# \n# \n# Example 2:\n# Input: \"aba\"\n# Output: 6\n# Explanation: The 6 distinct subsequences are \"a\", \"b\", \"ab\", \"ba\", \"aa\" and \"aba\".\n# \n# \n# Example 3:\n# Input: \"aaa\"\n# Output: 3\n# Explanation: The 3 distinct subsequences are \"a\", \"aa\" and \"aaa\".\n# \n# Note:\n# `S` contains only lowercase letters.\n# \n# `1 <= S.length <= 2000`\nclass Solution:\n def distinctSubseqII(self, s: str) -> int:\n ", "entry_point": "distinctSubseqII", "cannonical_solution": "", "test": ""}
{"task_id": "find-the-shortest-superstring", "prompt": "# Given an array of strings `words`, return the smallest string that contains each string in `words` as a substring. If there are multiple valid strings of the smallest length, return any of them.\n# \n# You may assume that no string in `words` is a substring of another string in `words`.\n# \n# \n# Example 1:\n# Input: words = [\"alex\",\"loves\",\"leetcode\"]\n# Output: \"alexlovesleetcode\"\n# Explanation: All permutations of \"alex\",\"loves\",\"leetcode\" would also be accepted.\n# \n# \n# Example 2:\n# Input: words = [\"catg\",\"ctaagt\",\"gcta\",\"ttca\",\"atgcatc\"]\n# Output: \"gctaagttcatgcatc\"\n# \n# Constraints:\n# `1 <= words.length <= 12`\n# `1 <= words[i].length <= 20`\n# `words[i]` consists of lowercase English letters.\n# \n# All the strings of `words` are unique.\nclass Solution:\n def shortestSuperstring(self, words: List[str]) -> str:\n ", "entry_point": "shortestSuperstring", "cannonical_solution": "", "test": ""}
{"task_id": "largest-component-size-by-common-factor", "prompt": "# Given a non-empty array of unique positive integers `A`, consider the following graph:\n# There are `A.length` nodes, labelled `A[0]` to `A[A.length - 1];`\n# There is an edge between `A[i]` and `A[j]` if and only if `A[i]` and `A[j]` share a common factor greater than 1.\n# \n# Return the size of the largest connected component in the graph.\n# \n# \n# Example 1:\n# Input: [4,6,15,35]\n# Output: 4\n# \n# Example 2:\n# Input: [20,50,9,63]\n# Output: 2\n# \n# Example 3:\n# Input: [2,3,6,7,4,12,21,39]\n# Output: 8\n# Note:\n# `1 <= A.length <= 20000`\n# `1 <= A[i] <= 100000`\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n ", "entry_point": "largestComponentSize", "cannonical_solution": "", "test": ""}
{"task_id": "tallest-billboard", "prompt": "# You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.\n# \n# You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`.\n# \n# Return the largest possible height of your billboard installation. If you cannot support the billboard, return `0`.\n# \n# \n# Example 1:\n# Input: rods = [1,2,3,6]\n# Output: 6\n# Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.\n# \n# \n# Example 2:\n# Input: rods = [1,2,3,4,5,6]\n# Output: 10\n# Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.\n# \n# \n# Example 3:\n# Input: rods = [1,2]\n# Output: 0\n# Explanation: The billboard cannot be supported, so we return 0.\n# \n# \n# Constraints:\n# `1 <= rods.length <= 20`\n# `1 <= rods[i] <= 1000`\n# `sum(rods[i]) <= 5000`\nclass Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n ", "entry_point": "tallestBillboard", "cannonical_solution": "", "test": ""}
{"task_id": "delete-columns-to-make-sorted-iii", "prompt": "# You are given an array of `n` strings `strs`, all of the same length.\n# \n# We may choose any deletion indices, and we delete all the characters in those indices for each string.\n# \n# For example, if we have `strs = [\"abcdef\",\"uvwxyz\"]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[\"bef\", \"vyz\"]`.\n# \n# Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has every string (row) in lexicographic order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return the minimum possible value of `answer.length`.\n# \n# \n# Example 1:\n# Input: strs = [\"babca\",\"bbazb\"]\n# Output: 3\n# Explanation: After deleting columns 0, 1, and 4, the final array is strs = [\"bc\", \"az\"].\n# \n# Both these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]).\n# \n# Note that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order.\n# \n# \n# Example 2:\n# Input: strs = [\"edcba\"]\n# Output: 4\n# Explanation: If we delete less than 4 columns, the only row will not be lexicographically sorted.\n# \n# \n# Example 3:\n# Input: strs = [\"ghi\",\"def\",\"abc\"]\n# Output: 0\n# Explanation: All rows are already lexicographically sorted.\n# \n# \n# Constraints:\n# `n == strs.length`\n# `1 <= n <= 100`\n# `1 <= strs[i].length <= 100`\n# `strs[i]` consists of lowercase English letters.\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n ", "entry_point": "minDeletionSize", "cannonical_solution": "", "test": ""}
{"task_id": "least-operators-to-express-number", "prompt": "# Given a single positive integer `x`, we will write an expression of the form `x (op1) x (op2) x (op3) x ...` where each operator `op1`, `op2`, etc. is either addition, subtraction, multiplication, or division (`+`, `-`, `*`, or `/)`. For example, with `x = 3`, we might write `3 * 3 / 3 + 3 - 3` which is a value of 3.\n# \n# When writing such an expression, we adhere to the following conventions:\n# The division operator (`/`) returns rational numbers.\n# \n# There are no parentheses placed anywhere.\n# \n# We use the usual order of operations: multiplication and division happen before addition and subtraction.\n# \n# It is not allowed to use the unary negation operator (`-`). For example, \"`x - x`\" is a valid expression as it only uses subtraction, but \"`-x + x`\" is not because it uses negation.\n# \n# We would like to write an expression with the least number of operators such that the expression equals the given `target`. Return the least number of operators used.\n# \n# \n# Example 1:\n# Input: x = 3, target = 19\n# Output: 5\n# Explanation: 3 * 3 + 3 * 3 + 3 / 3.\n# \n# The expression contains 5 operations.\n# \n# \n# Example 2:\n# Input: x = 5, target = 501\n# Output: 8\n# Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.\n# \n# The expression contains 8 operations.\n# \n# \n# Example 3:\n# Input: x = 100, target = 100000000\n# Output: 3\n# Explanation: 100 * 100 * 100 * 100.\n# \n# The expression contains 3 operations.\n# \n# \n# Constraints:\n# `2 <= x <= 100`\n# `1 <= target <= 2 * 108`\nclass Solution:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n ", "entry_point": "leastOpsExpressTarget", "cannonical_solution": "", "test": ""}
{"task_id": "equal-rational-numbers", "prompt": "# Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.\n# \n# A rational number can be represented using up to three parts: `<IntegerPart>`, `<NonRepeatingPart>`, and a `<RepeatingPart>`. The number will be represented in one of the following three ways:\n# `<IntegerPart>`\n# \t\n# For example, `12`, `0`, and `123`.\n# \n# `<IntegerPart><.><NonRepeatingPart>`\n# \t\n# For example, `0.5`, `1.`, `2.12`, and `123.0001`.\n# \n# `<IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)>`\n# \t\n# For example, `0.1(6)`, `1.(9)`, `123.00(1212)`.\n# \n# The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:\n# `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`.\n# \n# \n# Example 1:\n# Input: s = \"0.(52)\", t = \"0.5(25)\"\n# Output: true\n# Explanation: Because \"0.(52)\" represents 0.52525252..., and \"0.5(25)\" represents 0.52525252525..... , the strings represent the same number.\n# \n# \n# Example 2:\n# Input: s = \"0.1666(6)\", t = \"0.166(66)\"\n# Output: true\n# \n# Example 3:\n# Input: s = \"0.9(9)\", t = \"1.\"\n# Output: true\n# Explanation: \"0.9(9)\" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.]\n# \"1.\" represents the number 1, which is formed correctly: (IntegerPart) = \"1\" and (NonRepeatingPart) = \"\".\n# \n# \n# Constraints:\n# Each part consists only of digits.\n# \n# The `<IntegerPart>` does not have leading zeros (except for the zero itself).\n# \n# `1 <= <IntegerPart>.length <= 4`\n# `0 <= <NonRepeatingPart>.length <= 4`\n# `1 <= <RepeatingPart>.length <= 4`\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n ", "entry_point": "isRationalEqual", "cannonical_solution": "", "test": ""}
{"task_id": "odd-even-jump", "prompt": "# You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices.\n# \n# You may jump forward from index `i` to index `j` (with `i < j`) in the following way:\n# During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index `j` such that `arr[i] <= arr[j]` and `arr[j]` is the smallest possible value. If there are multiple such indices `j`, you can only jump to the smallest such index `j`.\n# \n# During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index `j` such that `arr[i] >= arr[j]` and `arr[j]` is the largest possible value. If there are multiple such indices `j`, you can only jump to the smallest such index `j`.\n# \n# It may be the case that for some index `i`, there are no legal jumps.\n# \n# A starting index is good if, starting from that index, you can reach the end of the array (index `arr.length - 1`) by jumping some number of times (possibly 0 or more than once).\n# \n# Return the number of good starting indices.\n# \n# \n# Example 1:\n# Input: arr = [10,13,12,14,15]\n# Output: 2\n# Explanation: \n# From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.\n# \n# From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.\n# \n# From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.\n# \n# From starting index i = 4, we have reached the end already.\n# \n# In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of\n# jumps.\n# \n# \n# Example 2:\n# Input: arr = [2,3,1,1,4]\n# Output: 3\n# Explanation: \n# From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:\n# During our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].\n# \n# During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3\n# During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].\n# \n# We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.\n# \n# In a similar manner, we can deduce that:\n# From starting index i = 1, we jump to i = 4, so we reach the end.\n# \n# From starting index i = 2, we jump to i = 3, and then we can't jump anymore.\n# \n# From starting index i = 3, we jump to i = 4, so we reach the end.\n# \n# From starting index i = 4, we are already at the end.\n# \n# In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some\n# number of jumps.\n# \n# \n# Example 3:\n# Input: arr = [5,1,3,4,2]\n# Output: 3\n# Explanation: We can reach the end from starting indices 1, 2, and 4.\n# \n# \n# Constraints:\n# `1 <= arr.length <= 2 * 104`\n# `0 <= arr[i] < 105`\nclass Solution:\n def oddEvenJumps(self, arr: List[int]) -> int:\n ", "entry_point": "oddEvenJumps", "cannonical_solution": "", "test": ""}
{"task_id": "unique-paths-iii", "prompt": "# On a 2-dimensional `grid`, there are 4 types of squares:\n# `1` represents the starting square. There is exactly one starting square.\n# \n# `2` represents the ending square. There is exactly one ending square.\n# \n# `0` represents empty squares we can walk over.\n# \n# `-1` represents obstacles that we cannot walk over.\n# \n# Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.\n# \n# \n# Example 1:\n# Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]\n# Output: 2\n# Explanation: We have the following two paths: \n# 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n# 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)\n# \n# Example 2:\n# Input: [[1,0,0,0],[0,0,0,0],[0,0,0,2]]\n# Output: 4\n# Explanation: We have the following four paths: \n# 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n# 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n# 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n# 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)\n# \n# Example 3:\n# Input: [[0,1],[2,0]]\n# Output: 0\n# Explanation: \n# There is no path that walks over every empty square exactly once.\n# \n# Note that the starting and ending square can be anywhere in the grid.\n# \n# Note:\n# `1 <= grid.length * grid[0].length <= 20`\nclass Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n ", "entry_point": "uniquePathsIII", "cannonical_solution": "", "test": ""}
{"task_id": "triples-with-bitwise-and-equal-to-zero", "prompt": "# Given an array of integers `A`, find the number of triples of indices (i, j, k) such that:\n# `0 <= i < A.length`\n# `0 <= j < A.length`\n# `0 <= k < A.length`\n# `A[i] & A[j] & A[k] == 0`, where `&` represents the bitwise-AND operator.\n# \n# \n# Example 1:\n# Input: [2,1,3]\n# Output: 12\n# Explanation: We could choose the following i, j, k triples:\n# (i=0, j=0, k=1) : 2 & 2 & 1\n# (i=0, j=1, k=0) : 2 & 1 & 2\n# (i=0, j=1, k=1) : 2 & 1 & 1\n# (i=0, j=1, k=2) : 2 & 1 & 3\n# (i=0, j=2, k=1) : 2 & 3 & 1\n# (i=1, j=0, k=0) : 1 & 2 & 2\n# (i=1, j=0, k=1) : 1 & 2 & 1\n# (i=1, j=0, k=2) : 1 & 2 & 3\n# (i=1, j=1, k=0) : 1 & 1 & 2\n# (i=1, j=2, k=0) : 1 & 3 & 2\n# (i=2, j=0, k=1) : 3 & 2 & 1\n# (i=2, j=1, k=0) : 3 & 1 & 2\n# Note:\n# `1 <= A.length <= 1000`\n# `0 <= A[i] < 2^16`\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n ", "entry_point": "countTriplets", "cannonical_solution": "", "test": ""}
{"task_id": "subarrays-with-k-different-integers", "prompt": "# Given an array `A` of positive integers, call a (contiguous, not necessarily distinct) subarray of `A` good if the number of different integers in that subarray is exactly `K`.\n# \n# (For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`.)\n# Return the number of good subarrays of `A`.\n# \n# \n# Example 1:\n# Input: A = [1,2,1,2,3], K = 2\n# Output: 7\n# Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].\n# \n# \n# Example 2:\n# Input: A = [1,2,1,3,4], K = 3\n# Output: 3\n# Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].\n# \n# Note:\n# `1 <= A.length <= 20000`\n# `1 <= A[i] <= A.length`\n# `1 <= K <= A.length`\nclass Solution:\n def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n ", "entry_point": "subarraysWithKDistinct", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-number-of-k-consecutive-bit-flips", "prompt": "# In an array `A` containing only 0s and 1s, a `K`-bit flip consists of choosing a (contiguous) subarray of length `K` and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.\n# \n# Return the minimum number of `K`-bit flips required so that there is no 0 in the array. If it is not possible, return `-1`.\n# \n# \n# Example 1:\n# Input: A = [0,1,0], K = 1\n# Output: 2\n# Explanation: Flip A[0], then flip A[2].\n# \n# \n# Example 2:\n# Input: A = [1,1,0], K = 2\n# Output: -1\n# Explanation: No matter how we flip subarrays of size 2, we can't make the array become [1,1,1].\n# \n# \n# Example 3:\n# Input: A = [0,0,0,1,0,1,1,0], K = 3\n# Output: 3\n# Explanation:\n# Flip A[0],A[1],A[2]: A becomes [1,1,1,1,0,1,1,0]\n# Flip A[4],A[5],A[6]: A becomes [1,1,1,1,1,0,0,0]\n# Flip A[5],A[6],A[7]: A becomes [1,1,1,1,1,1,1,1]\n# Note:\n# `1 <= A.length <= 30000`\n# `1 <= K <= A.length`\nclass Solution:\n def minKBitFlips(self, nums: List[int], k: int) -> int:\n ", "entry_point": "minKBitFlips", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-squareful-arrays", "prompt": "# Given an array `A` of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.\n# \n# Return the number of permutations of A that are squareful. Two permutations `A1` and `A2` differ if and only if there is some index `i` such that `A1[i] != A2[i]`.\n# \n# \n# Example 1:\n# Input: [1,17,8]\n# Output: 2\n# Explanation: \n# [1,8,17] and [17,8,1] are the valid permutations.\n# \n# \n# Example 2:\n# Input: [2,2,2]\n# Output: 1\n# Note:\n# `1 <= A.length <= 12`\n# `0 <= A[i] <= 1e9`\nclass Solution:\n def numSquarefulPerms(self, nums: List[int]) -> int:\n ", "entry_point": "numSquarefulPerms", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-cost-to-merge-stones", "prompt": "# There are `N` piles of stones arranged in a row. The `i`-th pile has `stones[i]` stones.\n# \n# A move consists of merging exactly `K` consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these `K` piles.\n# \n# Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return `-1`.\n# \n# \n# Example 1:\n# Input: stones = [3,2,4,1], K = 2\n# Output: 20\n# Explanation: \n# We start with [3, 2, 4, 1].\n# \n# We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].\n# \n# We merge [4, 1] for a cost of 5, and we are left with [5, 5].\n# \n# We merge [5, 5] for a cost of 10, and we are left with [10].\n# \n# The total cost was 20, and this is the minimum possible.\n# \n# \n# Example 2:\n# Input: stones = [3,2,4,1], K = 3\n# Output: -1\n# Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.\n# \n# \n# Example 3:\n# Input: stones = [3,5,1,2,6], K = 3\n# Output: 25\n# Explanation: \n# We start with [3, 5, 1, 2, 6].\n# \n# We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].\n# \n# We merge [3, 8, 6] for a cost of 17, and we are left with [17].\n# \n# The total cost was 25, and this is the minimum possible.\n# \n# Note:\n# `1 <= stones.length <= 30`\n# `2 <= K <= 30`\n# `1 <= stones[i] <= 100`\nclass Solution:\n def mergeStones(self, stones: List[int], k: int) -> int:\n ", "entry_point": "mergeStones", "cannonical_solution": "", "test": ""}
{"task_id": "grid-illumination", "prompt": "# You are given a `grid` of size `N x N`, and each cell of this grid has a lamp that is initially turned off.\n# \n# You are also given an array of lamp positions `lamps`, where `lamps[i] = [rowi, coli]` indicates that the lamp at `grid[rowi][coli]` is turned on. When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal.\n# \n# Finally, you are given a query array `queries`, where `queries[i] = [rowi, coli]`. For the `ith` query, determine whether `grid[rowi][coli]` is illuminated or not. After answering the `ith` query, turn off the lamp at `grid[rowi][coli]` and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with `grid[rowi][coli]`.\n# \n# Return an array of integers `ans`, where `ans[i]` should be `1` if the lamp in the `ith` query was illuminated, or `0` if the lamp was not.\n# \n# \n# Example 1:\n# Input: N = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]\n# Output: [1,0]\n# Explanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].\n# \n# The 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.\n# \n# The 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.\n# \n# \n# Example 2:\n# Input: N = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]\n# Output: [1,1]\n# \n# Example 3:\n# Input: N = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]\n# Output: [1,1,0]\n# \n# Constraints:\n# `1 <= N <= 109`\n# `0 <= lamps.length <= 20000`\n# `lamps[i].length == 2`\n# `0 <= lamps[i][j] < N`\n# `0 <= queries.length <= 20000`\n# `queries[i].length == 2`\n# `0 <= queries[i][j] < N`\nclass Solution:\n def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:\n ", "entry_point": "gridIllumination", "cannonical_solution": "", "test": ""}
{"task_id": "numbers-with-repeated-digits", "prompt": "# Given a positive integer `N`, return the number of positive integers less than or equal to `N` that have at least 1 repeated digit.\n# \n# \n# Example 1:\n# Input: 20\n# Output: 1\n# Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.\n# \n# \n# Example 2:\n# Input: 100\n# Output: 10\n# Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.\n# \n# \n# Example 3:\n# Input: 1000\n# Output: 262\n# Note:\n# `1 <= N <= 10^9`\nclass Solution:\n def numDupDigitsAtMostN(self, n: int) -> int:\n ", "entry_point": "numDupDigitsAtMostN", "cannonical_solution": "", "test": ""}
{"task_id": "stream-of-characters", "prompt": "# Implement the `StreamChecker` class as follows:\n# `StreamChecker(words)`: Constructor, init the data structure with the given words.\n# \n# `query(letter)`: returns true if and only if for some `k >= 1`, the last `k` characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list.\n# \n# \n# Example:\n# StreamChecker streamChecker = new StreamChecker([\"cd\",\"f\",\"kl\"]); // init the dictionary.\n# \n# streamChecker.query('a'); // return false\n# streamChecker.query('b'); // return false\n# streamChecker.query('c'); // return false\n# streamChecker.query('d'); // return true, because 'cd' is in the wordlist\n# streamChecker.query('e'); // return false\n# streamChecker.query('f'); // return true, because 'f' is in the wordlist\n# streamChecker.query('g'); // return false\n# streamChecker.query('h'); // return false\n# streamChecker.query('i'); // return false\n# streamChecker.query('j'); // return false\n# streamChecker.query('k'); // return false\n# streamChecker.query('l'); // return true, because 'kl' is in the wordlist\n# Note:\n# `1 <= words.length <= 2000`\n# `1 <= words[i].length <= 2000`\n# Words will only consist of lowercase English letters.\n# \n# Queries will only consist of lowercase English letters.\n# \n# The number of queries is at most 40000.\nclass StreamChecker:\n\n def __init__(self, words: List[str]):\n \n\n def query(self, letter: str) -> bool:\n \n\n\n# Your StreamChecker object will be instantiated and called as such:\n# obj = StreamChecker(words)\n# param_1 = obj.query(letter)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "escape-a-large-maze", "prompt": "# There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are `(x, y)`.\n# \n# We start at the `source = [sx, sy]` square and want to reach the `target = [tx, ty]` square. There is also an array of `blocked` squares, where each `blocked[i] = [xi, yi]` represents a blocked square with coordinates `(xi, yi)`.\n# \n# Each move, we can walk one square north, east, south, or west if the square is not in the array of `blocked` squares. We are also not allowed to walk outside of the grid.\n# \n# Return `true` if and only if it is possible to reach the `target` square from the `source` square through a sequence of valid moves.\n# \n# \n# Example 1:\n# Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]\n# Output: false\n# Explanation: The target square is inaccessible starting from the source square because we cannot move.\n# \n# We cannot move north or east because those squares are blocked.\n# \n# We cannot move south or west because we cannot go outside of the grid.\n# \n# \n# Example 2:\n# Input: blocked = [], source = [0,0], target = [999999,999999]\n# Output: true\n# Explanation: Because there are no blocked cells, it is possible to reach the target square.\n# \n# \n# Constraints:\n# `0 <= blocked.length <= 200`\n# `blocked[i].length == 2`\n# `0 <= xi, yi < 106`\n# `source.length == target.length == 2`\n# `0 <= sx, sy, tx, ty < 106`\n# `source != target`\n# It is guaranteed that `source` and `target` are not blocked.\nclass Solution:\n def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:\n ", "entry_point": "isEscapePossible", "cannonical_solution": "", "test": ""}
{"task_id": "longest-duplicate-substring", "prompt": "# Given a string `s`, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.\n# \n# Return any duplicated substring that has the longest possible length. If `s` does not have a duplicated substring, the answer is `\"\"`.\n# \n# \n# Example 1:\n# Input: s = \"banana\"\n# Output: \"ana\"\n# \n# Example 2:\n# Input: s = \"abcd\"\n# Output: \"\"\n# \n# Constraints:\n# `2 <= s.length <= 3 * 104`\n# `s` consists of lowercase English letters.\nclass Solution:\n def longestDupSubstring(self, s: str) -> str:\n ", "entry_point": "longestDupSubstring", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-submatrices-that-sum-to-target", "prompt": "# Given a `matrix` and a `target`, return the number of non-empty submatrices that sum to target.\n# \n# A submatrix `x1, y1, x2, y2` is the set of all cells `matrix[x][y]` with `x1 <= x <= x2` and `y1 <= y <= y2`.\n# \n# Two submatrices `(x1, y1, x2, y2)` and `(x1', y1', x2', y2')` are different if they have some coordinate that is different: for example, if `x1 != x1'`.\n# \n# \n# Example 1:\n# Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0\n# Output: 4\n# Explanation: The four 1x1 submatrices that only contain 0.\n# \n# \n# Example 2:\n# Input: matrix = [[1,-1],[-1,1]], target = 0\n# Output: 5\n# Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.\n# \n# \n# Example 3:\n# Input: matrix = [[904]], target = 0\n# Output: 0\n# \n# Constraints:\n# `1 <= matrix.length <= 100`\n# `1 <= matrix[0].length <= 100`\n# `-1000 <= matrix[i] <= 1000`\n# `-10^8 <= target <= 10^8`\nclass Solution:\n def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n ", "entry_point": "numSubmatrixSumTarget", "cannonical_solution": "", "test": ""}
{"task_id": "shortest-common-supersequence", "prompt": "# Given two strings `str1` and `str2`, return the shortest string that has both `str1` and `str2` as subsequences. If multiple answers exist, you may return any of them.\n# \n# (A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results in the string S.)\n# \n# Example 1:\n# Input: str1 = \"abac\", str2 = \"cab\"\n# Output: \"cabac\"\n# Explanation: \n# str1 = \"abac\" is a subsequence of \"cabac\" because we can delete the first \"c\".\n# \n# str2 = \"cab\" is a subsequence of \"cabac\" because we can delete the last \"ac\".\n# \n# The answer provided is the shortest such string that satisfies these properties.\n# \n# Note:\n# `1 <= str1.length, str2.length <= 1000`\n# `str1` and `str2` consist of lowercase English letters.\nclass Solution:\n def shortestCommonSupersequence(self, str1: str, str2: str) -> str:\n ", "entry_point": "shortestCommonSupersequence", "cannonical_solution": "", "test": ""}
{"task_id": "brace-expansion-ii", "prompt": "# Under a grammar given below, strings can represent a set of lowercase words. Let's use `R(expr)` to denote the set of words the expression represents.\n# \n# Grammar can best be understood through simple examples:\n# Single letters represent a singleton set containing that word.\n# \n# \t\n# `R(\"a\") = {\"a\"}`\n# `R(\"w\") = {\"w\"}`\n# When we take a comma delimited list of 2 or more expressions, we take the union of possibilities.\n# \n# \t\n# `R(\"{a,b,c}\") = {\"a\",\"b\",\"c\"}`\n# `R(\"{{a,b},{b,c}}\") = {\"a\",\"b\",\"c\"}` (notice the final set only contains each word at most once)\n# When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression.\n# \n# \t\n# `R(\"{a,b}{c,d}\") = {\"ac\",\"ad\",\"bc\",\"bd\"}`\n# `R(\"a{b,c}{d,e}f{g,h}\") = {\"abdfg\", \"abdfh\", \"abefg\", \"abefh\", \"acdfg\", \"acdfh\", \"acefg\", \"acefh\"}`\n# Formally, the 3 rules for our grammar:\n# For every lowercase letter `x`, we have `R(x) = {x}`\n# For expressions `e_1, e_2, ... , e_k` with `k >= 2`, we have `R({e_1,e_2,...}) = R(e_1) \u222a R(e_2) \u222a ...`\n# For expressions `e_1` and `e_2`, we have `R(e_1 + e_2) = {a + b for (a, b) in R(e_1) \u00d7 R(e_2)}`, where + denotes concatenation, and \u00d7 denotes the cartesian product.\n# \n# Given an `expression` representing a set of words under the given grammar, return the sorted list of words that the expression represents.\n# \n# \n# Example 1:\n# Input: \"{a,b}{c,{d,e}}\"\n# Output: [\"ac\",\"ad\",\"ae\",\"bc\",\"bd\",\"be\"]\n# \n# Example 2:\n# Input: \"{{a,z},a{b,c},{ab,z}}\"\n# Output: [\"a\",\"ab\",\"ac\",\"z\"]\n# Explanation: Each distinct word is written only once in the final answer.\n# \n# \n# Constraints:\n# `1 <= expression.length <= 60`\n# `expression[i]` consists of `'{'`, `'}'`, `','`or lowercase English letters.\n# \n# The given `expression` represents a set of words based on the grammar given in the description.\nclass Solution:\n def braceExpansionII(self, expression: str) -> List[str]:\n ", "entry_point": "braceExpansionII", "cannonical_solution": "", "test": ""}
{"task_id": "parsing-a-boolean-expression", "prompt": "# Return the result of evaluating a given boolean `expression`, represented as a string.\n# \n# An expression can either be:\n# `\"t\"`, evaluating to `True`;\n# `\"f\"`, evaluating to `False`;\n# `\"!(expr)\"`, evaluating to the logical NOT of the inner expression `expr`;\n# `\"&(expr1,expr2,...)\"`, evaluating to the logical AND of 2 or more inner expressions `expr1, expr2, ...`;\n# `\"|(expr1,expr2,...)\"`, evaluating to the logical OR of 2 or more inner expressions `expr1, expr2, ...`\n# \n# Example 1:\n# Input: expression = \"!(f)\"\n# Output: true\n# \n# Example 2:\n# Input: expression = \"|(f,t)\"\n# Output: true\n# \n# Example 3:\n# Input: expression = \"&(t,f)\"\n# Output: false\n# \n# Example 4:\n# Input: expression = \"|(&(t,f,t),!(t))\"\n# Output: false\n# \n# Constraints:\n# `1 <= expression.length <= 20000`\n# `expression[i]` consists of characters in `{'(', ')', '&', '|', '!', 't', 'f', ','}`.\n# \n# `expression` is a valid expression representing a boolean, as given in the description.\nclass Solution:\n def parseBoolExpr(self, expression: str) -> bool:\n ", "entry_point": "parseBoolExpr", "cannonical_solution": "", "test": ""}
{"task_id": "smallest-sufficient-team", "prompt": "# In a project, you have a list of required skills `req_skills`, and a list of people. The `ith` person `people[i]` contains a list of skills that the person has.\n# \n# Consider a sufficient team: a set of people such that for every required skill in `req_skills`, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.\n# \n# For example, `team = [0, 1, 3]` represents the people with skills `people[0]`, `people[1]`, and `people[3]`.\n# \n# Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.\n# \n# It is guaranteed an answer exists.\n# \n# \n# Example 1:\n# Input: req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]\n# Output: [0,2]\n# \n# Example 2:\n# Input: req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]\n# Output: [1,2]\n# \n# Constraints:\n# `1 <= req_skills.length <= 16`\n# `1 <= req_skills[i].length <= 16`\n# `req_skills[i]` consists of lowercase English letters.\n# \n# All the strings of `req_skills` are unique.\n# \n# `1 <= people.length <= 60`\n# `0 <= people[i].length <= 16`\n# `1 <= people[i][j].length <= 16`\n# `people[i][j]` consists of lowercase English letters.\n# \n# All the strings of `people[i]` are unique.\n# \n# Every skill in `people[i]` is a skill in `req_skills`.\n# \n# It is guaranteed a sufficient team exists.\nclass Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n ", "entry_point": "smallestSufficientTeam", "cannonical_solution": "", "test": ""}
{"task_id": "longest-chunked-palindrome-decomposition", "prompt": "# You are given a string `text`. You should split it to k substrings `(subtext1, subtext2, ..., subtextk)` such that:\n# `subtexti` is a non-empty string.\n# \n# The concatenation of all the substrings is equal to `text` (i.e., `subtext1 + subtext2 + ... + subtextk == text`).\n# \n# `subtexti == subtextk - i + 1` for all valid values of `i` (i.e., `1 <= i <= k`).\n# \n# Return the largest possible value of `k`.\n# \n# \n# Example 1:\n# Input: text = \"ghiabcdefhelloadamhelloabcdefghi\"\n# Output: 7\n# Explanation: We can split the string on \"(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)\".\n# \n# \n# Example 2:\n# Input: text = \"merchant\"\n# Output: 1\n# Explanation: We can split the string on \"(merchant)\".\n# \n# \n# Example 3:\n# Input: text = \"antaprezatepzapreanta\"\n# Output: 11\n# Explanation: We can split the string on \"(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)\".\n# \n# \n# Example 4:\n# Input: text = \"aaa\"\n# Output: 3\n# Explanation: We can split the string on \"(a)(a)(a)\".\n# \n# \n# Constraints:\n# `1 <= text.length <= 1000`\n# `text` consists only of lowercase English characters.\nclass Solution:\n def longestDecomposition(self, text: str) -> int:\n ", "entry_point": "longestDecomposition", "cannonical_solution": "", "test": ""}
{"task_id": "online-majority-element-in-subarray", "prompt": "# Implementing the class `MajorityChecker`, which has the following API:\n# `MajorityChecker(int[] arr)` constructs an instance of MajorityChecker with the given array `arr`;\n# `int query(int left, int right, int threshold)` has arguments such that:\n# \t\n# `0 <= left <= right < arr.length` representing a subarray of `arr`;\n# `2 * threshold > right - left + 1`, ie. the threshold is always a strict majority of the length of the subarray\n# Each `query(...)` returns the element in `arr[left], arr[left+1], ..., arr[right]` that occurs at least `threshold` times, or `-1` if no such element exists.\n# \n# \n# Example:\n# MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);\n# majorityChecker.query(0,5,4); // returns 1\n# majorityChecker.query(0,3,3); // returns -1\n# majorityChecker.query(2,3,2); // returns 2\n# \n# Constraints:\n# `1 <= arr.length <= 20000`\n# `1 <= arr[i] <= 20000`\n# For each query, `0 <= left <= right < len(arr)`\n# For each query, `2 * threshold > right - left + 1`\n# The number of queries is at most `10000`\nclass MajorityChecker:\n\n def __init__(self, arr: List[int]):\n \n\n def query(self, left: int, right: int, threshold: int) -> int:\n \n\n\n# Your MajorityChecker object will be instantiated and called as such:\n# obj = MajorityChecker(arr)\n# param_1 = obj.query(left,right,threshold)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "last-substring-in-lexicographical-order", "prompt": "# Given a string `s`, return the last substring of `s` in lexicographical order.\n# \n# \n# Example 1:\n# Input: s = \"abab\"\n# Output: \"bab\"\n# Explanation: The substrings are [\"a\", \"ab\", \"aba\", \"abab\", \"b\", \"ba\", \"bab\"]. The lexicographically maximum substring is \"bab\".\n# \n# \n# Example 2:\n# Input: s = \"leetcode\"\n# Output: \"tcode\"\n# \n# Constraints:\n# `1 <= s.length <= 4 * 105`\n# `s` contains only lowercase English letters.\nclass Solution:\n def lastSubstring(self, s: str) -> str:\n ", "entry_point": "lastSubstring", "cannonical_solution": "", "test": ""}
{"task_id": "dinner-plate-stacks", "prompt": "# You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum `capacity`.\n# \n# Implement the `DinnerPlates` class:\n# `DinnerPlates(int capacity)` Initializes the object with the maximum `capacity` of the stacks.\n# \n# `void push(int val)` Pushes the given positive integer `val` into the leftmost stack with size less than `capacity`.\n# \n# `int pop()` Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns `-1` if all stacks are empty.\n# \n# `int popAtStack(int index)` Returns the value at the top of the stack with the given `index` and removes it from that stack, and returns -1 if the stack with that given `index` is empty.\n# \n# \n# Example:\n# Input: \n# [\"DinnerPlates\",\"push\",\"push\",\"push\",\"push\",\"push\",\"popAtStack\",\"push\",\"push\",\"popAtStack\",\"popAtStack\",\"pop\",\"pop\",\"pop\",\"pop\",\"pop\"]\n# [[2],[1],[2],[3],[4],[5],[0],[20],[21],[0],[2],[],[],[],[],[]]\n# Output: \n# [null,null,null,null,null,null,2,null,null,20,21,5,4,3,1,-1]\n# Explanation: \n# DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2\n# D.push(1);\n# D.push(2);\n# D.push(3);\n# D.push(4);\n# D.push(5); // The stacks are now: 2 4\n# 1 3 5\n# ] ] ]\n# D.popAtStack(0); // Returns 2. The stacks are now: 4\n# 1 3 5\n# ] ] ]\n# D.push(20); // The stacks are now: 20 4\n# 1 3 5\n# ] ] ]\n# D.push(21); // The stacks are now: 20 4 21\n# 1 3 5\n# ] ] ]\n# D.popAtStack(0); // Returns 20. The stacks are now: 4 21\n# 1 3 5\n# ] ] ]\n# D.popAtStack(2); // Returns 21. The stacks are now: 4\n# 1 3 5\n# ] ] ] \n# D.pop() // Returns 5. The stacks are now: 4\n# 1 3 \n# ] ] \n# D.pop() // Returns 4. The stacks are now: 1 3 \n# ] ] \n# D.pop() // Returns 3. The stacks are now: 1 \n# ] \n# D.pop() // Returns 1. There are no stacks.\n# \n# D.pop() // Returns -1. There are still no stacks.\n# \n# \n# Constraints:\n# `1 <= capacity <= 20000`\n# `1 <= val <= 20000`\n# `0 <= index <= 100000`\n# At most `200000` calls will be made to `push`, `pop`, and `popAtStack`.\nclass DinnerPlates:\n\n def __init__(self, capacity: int):\n \n\n def push(self, val: int) -> None:\n \n\n def pop(self) -> int:\n \n\n def popAtStack(self, index: int) -> int:\n \n\n\n# Your DinnerPlates object will be instantiated and called as such:\n# obj = DinnerPlates(capacity)\n# obj.push(val)\n# param_2 = obj.pop()\n# param_3 = obj.popAtStack(index)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-valid-words-for-each-puzzle", "prompt": "# With respect to a given `puzzle` string, a `word` is valid if both the following conditions are satisfied:\n# `word` contains the first letter of `puzzle`.\n# \n# For each letter in `word`, that letter is in `puzzle`.\n# \n# \tFor example, if the puzzle is \"abcdefg\", then valid words are \"faced\", \"cabbage\", and \"baggage\"; while invalid words are \"beefed\" (doesn't include \"a\") and \"based\" (includes \"s\" which isn't in the puzzle).\n# \n# Return an array `answer`, where `answer[i]` is the number of words in the given word list `words` that are valid with respect to the puzzle `puzzles[i]`.\n# \n# \n# Example :\n# Input: \n# words = [\"aaaa\",\"asas\",\"able\",\"ability\",\"actt\",\"actor\",\"access\"], \n# puzzles = [\"aboveyz\",\"abrodyz\",\"abslute\",\"absoryz\",\"actresz\",\"gaswxyz\"]\n# Output: [1,1,3,2,4,0]\n# Explanation:\n# 1 valid word for \"aboveyz\" : \"aaaa\" \n# 1 valid word for \"abrodyz\" : \"aaaa\"\n# 3 valid words for \"abslute\" : \"aaaa\", \"asas\", \"able\"\n# 2 valid words for \"absoryz\" : \"aaaa\", \"asas\"\n# 4 valid words for \"actresz\" : \"aaaa\", \"asas\", \"actt\", \"access\"\n# There're no valid words for \"gaswxyz\" cause none of the words in the list contains letter 'g'.\n# \n# \n# Constraints:\n# `1 <= words.length <= 10^5`\n# `4 <= words[i].length <= 50`\n# `1 <= puzzles.length <= 10^4`\n# `puzzles[i].length == 7`\n# `words[i][j]`, `puzzles[i][j]` are English lowercase letters.\n# \n# Each `puzzles[i] `doesn't contain repeated characters.\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n ", "entry_point": "findNumOfValidWords", "cannonical_solution": "", "test": ""}
{"task_id": "make-array-strictly-increasing", "prompt": "# Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.\n# \n# In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.\n# \n# If there is no way to make `arr1` strictly increasing, return `-1`.\n# \n# \n# Example 1:\n# Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]\n# Output: 1\n# Explanation: Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.\n# \n# \n# Example 2:\n# Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1]\n# Output: 2\n# Explanation: Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.\n# \n# \n# Example 3:\n# Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]\n# Output: -1\n# Explanation: You can't make `arr1` strictly increasing.\n# \n# \n# Constraints:\n# `1 <= arr1.length, arr2.length <= 2000`\n# `0 <= arr1[i], arr2[i] <= 10^9`\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n ", "entry_point": "makeArrayIncreasing", "cannonical_solution": "", "test": ""}
{"task_id": "critical-connections-in-a-network", "prompt": "# There are `n` servers numbered from `0` to `n-1` connected by undirected server-to-server `connections` forming a network where `connections[i] = [a, b]` represents a connection between servers `a` and `b`. Any server can reach any other server directly or indirectly through the network.\n# \n# A critical connection is a connection that, if removed, will make some server unable to reach some other server.\n# \n# Return all critical connections in the network in any order.\n# \n# \n# Example 1:\n# Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]\n# Output: [[1,3]]\n# Explanation: [[3,1]] is also accepted.\n# \n# \n# Constraints:\n# `1 <= n <= 10^5`\n# `n-1 <= connections.length <= 10^5`\n# `connections[i][0] != connections[i][1]`\n# There are no repeated connections.\nclass Solution:\n def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n ", "entry_point": "criticalConnections", "cannonical_solution": "", "test": ""}
{"task_id": "sort-items-by-groups-respecting-dependencies", "prompt": "# There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`-th item belongs to and it's equal to `-1` if the `i`-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.\n# \n# Return a sorted list of the items such that:\n# The items that belong to the same group are next to each other in the sorted list.\n# \n# There are some relations between these items where `beforeItems[i]` is a list containing all the items that should come before the `i`-th item in the sorted array (to the left of the `i`-th item).\n# \n# Return any solution if there is more than one solution and return an empty list if there is no solution.\n# \n# \n# Example 1:\n# Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]\n# Output: [6,3,4,1,5,2,0,7]\n# \n# Example 2:\n# Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]\n# Output: []\n# Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.\n# \n# \n# Constraints:\n# `1 <= m <= n <= 3 * 104`\n# `group.length == beforeItems.length == n`\n# `-1 <= group[i] <= m - 1`\n# `0 <= beforeItems[i].length <= n - 1`\n# `0 <= beforeItems[i][j] <= n - 1`\n# `i != beforeItems[i][j]`\n# `beforeItems[i] `does not contain duplicates elements.\nclass Solution:\n def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:\n ", "entry_point": "sortItems", "cannonical_solution": "", "test": ""}
{"task_id": "design-skiplist", "prompt": "# Design a Skiplist without using any built-in libraries.\n# \n# A Skiplist is a data structure that takes O(log(n)) time to `add`, `erase` and `search`. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists are just simple linked lists.\n# \n# For example: we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way:\n# Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons\n# You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, `add` , `erase` and `search `can be faster than O(n). It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n).\n# \n# To be specific, your design should include these functions:\n# `bool search(int target)` : Return whether the `target` exists in the Skiplist or not.\n# \n# `void add(int num)`: Insert a value into the SkipList. \n# `bool erase(int num)`: Remove a value in the Skiplist. If `num` does not exist in the Skiplist, do nothing and return false. If there exists multiple `num` values, removing any one of them is fine.\n# \n# See more about Skiplist : https://en.wikipedia.org/wiki/Skip_list\n# Note that duplicates may exist in the Skiplist, your code needs to handle this situation.\n# \n# \n# Example:\n# Skiplist skiplist = new Skiplist();\n# skiplist.add(1);\n# skiplist.add(2);\n# skiplist.add(3);\n# skiplist.search(0); // return false.\n# \n# skiplist.add(4);\n# skiplist.search(1); // return true.\n# \n# skiplist.erase(0); // return false, 0 is not in skiplist.\n# \n# skiplist.erase(1); // return true.\n# \n# skiplist.search(1); // return false, 1 has already been erased.\n# \n# \n# Constraints:\n# `0 <= num, target <= 20000`\n# At most `50000` calls will be made to `search`, `add`, and `erase`.\nclass Skiplist:\n\n def __init__(self):\n \n\n def search(self, target: int) -> bool:\n \n\n def add(self, num: int) -> None:\n \n\n def erase(self, num: int) -> bool:\n \n\n\n# Your Skiplist object will be instantiated and called as such:\n# obj = Skiplist()\n# param_1 = obj.search(target)\n# obj.add(num)\n# param_3 = obj.erase(num)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-moves-to-reach-target-with-rotations", "prompt": "# In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.\n# \n# In one move the snake can:\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# \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# \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# \n# Return the minimum number of moves to reach the target.\n# \n# If there is no way to reach the target, return `-1`.\n# \n# \n# Example 1:\n# Input: grid = [[0,0,0,0,0,1],\n# [1,1,0,0,1,0],\n# [0,0,0,0,1,1],\n# [0,0,1,0,1,0],\n# [0,1,1,0,0,0],\n# [0,1,1,0,0,0]]\n# Output: 11\n# Explanation:\n# One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].\n# \n# \n# Example 2:\n# Input: grid = [[0,0,1,1,1,1],\n# [0,0,0,0,1,1],\n# [1,1,0,0,0,1],\n# [1,1,1,0,0,1],\n# [1,1,1,0,0,1],\n# [1,1,1,0,0,0]]\n# Output: 9\n# \n# Constraints:\n# `2 <= n <= 100`\n# `0 <= grid[i][j] <= 1`\n# It is guaranteed that the snake starts at empty cells.\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n ", "entry_point": "minimumMoves", "cannonical_solution": "", "test": ""}
{"task_id": "count-vowels-permutation", "prompt": "# Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules:\n# Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`)\n# Each vowel `'a'` may only be followed by an `'e'`.\n# \n# Each vowel `'e'` may only be followed by an `'a'` or an `'i'`.\n# \n# Each vowel `'i'` may not be followed by another `'i'`.\n# \n# Each vowel `'o'` may only be followed by an `'i'` or a `'u'`.\n# \n# Each vowel `'u'` may only be followed by an `'a'.`\n# Since the answer may be too large, return it modulo `10^9 + 7.`\n# \n# Example 1:\n# Input: n = 1\n# Output: 5\n# Explanation: All possible strings are: \"a\", \"e\", \"i\" , \"o\" and \"u\".\n# \n# \n# Example 2:\n# Input: n = 2\n# Output: 10\n# Explanation: All possible strings are: \"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\" and \"ua\".\n# \n# \n# Example 3: \n# Input: n = 5\n# Output: 68\n# \n# Constraints:\n# `1 <= n <= 2 * 10^4`\nclass Solution:\n def countVowelPermutation(self, n: int) -> int:\n ", "entry_point": "countVowelPermutation", "cannonical_solution": "", "test": ""}
{"task_id": "dice-roll-simulation", "prompt": "# A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number `i` more than `rollMax[i]` (1-indexed) consecutive times. \n# Given an array of integers `rollMax` and an integer `n`, return the number of distinct sequences that can be obtained with exact `n` rolls.\n# \n# Two sequences are considered different if at least one element differs from each other. Since the answer may be too large, return it modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: n = 2, rollMax = [1,1,2,2,2,3]\n# Output: 34\n# Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.\n# \n# \n# Example 2:\n# Input: n = 2, rollMax = [1,1,1,1,1,1]\n# Output: 30\n# \n# Example 3:\n# Input: n = 3, rollMax = [1,1,1,2,2,3]\n# Output: 181\n# \n# Constraints:\n# `1 <= n <= 5000`\n# `rollMax.length == 6`\n# `1 <= rollMax[i] <= 15`\nclass Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n ", "entry_point": "dieSimulator", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-equal-frequency", "prompt": "# Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.\n# \n# If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).\n# \n# \n# Example 1:\n# Input: nums = [2,2,1,1,5,3,3,5]\n# Output: 7\n# Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.\n# \n# \n# Example 2:\n# Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]\n# Output: 13\n# \n# Example 3:\n# Input: nums = [1,1,1,2,2,2]\n# Output: 5\n# \n# Example 4:\n# Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6]\n# Output: 8\n# \n# Constraints:\n# `2 <= nums.length <= 10^5`\n# `1 <= nums[i] <= 10^5`\nclass Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n ", "entry_point": "maxEqualFreq", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-profit-in-job-scheduling", "prompt": "# We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`.\n# \n# You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.\n# \n# If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`.\n# \n# \n# Example 1:\n# Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]\n# Output: 120\n# Explanation: The subset chosen is the first and fourth job. \n# Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.\n# \n# \n# Example 2:\n# Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]\n# Output: 150\n# Explanation: The subset chosen is the first, fourth and fifth job. \n# Profit obtained 150 = 20 + 70 + 60.\n# \n# \n# Example 3:\n# Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]\n# Output: 6\n# \n# Constraints:\n# `1 <= startTime.length == endTime.length == profit.length <= 5 * 104`\n# `1 <= startTime[i] < endTime[i] <= 109`\n# `1 <= profit[i] <= 104`\nclass Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n ", "entry_point": "jobScheduling", "cannonical_solution": "", "test": ""}
{"task_id": "tiling-a-rectangle-with-the-fewest-squares", "prompt": "# Given a rectangle of size `n` x `m`, find the minimum number of integer-sided squares that tile the rectangle.\n# \n# \n# Example 1:\n# Input: n = 2, m = 3\n# Output: 3\n# Explanation: `3` squares are necessary to cover the rectangle.\n# \n# `2` (squares of `1x1`)\n# `1` (square of `2x2`)\n# \n# Example 2:\n# Input: n = 5, m = 8\n# Output: 5\n# \n# Example 3:\n# Input: n = 11, m = 13\n# Output: 6\n# \n# Constraints:\n# `1 <= n <= 13`\n# `1 <= m <= 13`\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n ", "entry_point": "tilingRectangle", "cannonical_solution": "", "test": ""}
{"task_id": "check-if-it-is-a-good-array", "prompt": "# Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of `1` from the array by any possible subset and multiplicand.\n# \n# Return `True` if the array is good otherwise return `False`.\n# \n# \n# Example 1:\n# Input: nums = [12,5,7,23]\n# Output: true\n# Explanation: Pick numbers 5 and 7.\n# \n# 5*3 + 7*(-2) = 1\n# \n# Example 2:\n# Input: nums = [29,6,10]\n# Output: true\n# Explanation: Pick numbers 29, 6 and 10.\n# \n# 29*1 + 6*(-3) + 10*(-1) = 1\n# \n# Example 3:\n# Input: nums = [3,6]\n# Output: false\n# \n# Constraints:\n# `1 <= nums.length <= 10^5`\n# `1 <= nums[i] <= 10^9`\nclass Solution:\n def isGoodArray(self, nums: List[int]) -> bool:\n ", "entry_point": "isGoodArray", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-score-words-formed-by-letters", "prompt": "# Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character.\n# \n# Return the maximum score of any valid set of words formed by using the given letters (`words[i]` cannot be used two or more times).\n# \n# It is not necessary to use all characters in `letters` and each letter can only be used once. Score of letters `'a'`, `'b'`, `'c'`, ... ,`'z'` is given by `score[0]`, `score[1]`, ... , `score[25]` respectively.\n# \n# \n# Example 1:\n# Input: words = [\"dog\",\"cat\",\"dad\",\"good\"], letters = [\"a\",\"a\",\"c\",\"d\",\"d\",\"d\",\"g\",\"o\",\"o\"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]\n# Output: 23\n# Explanation:\n# Score a=1, c=9, d=5, g=3, o=2\n# Given letters, we can form the words \"dad\" (5+1+5) and \"good\" (3+2+2+5) with a score of 23.\n# \n# Words \"dad\" and \"dog\" only get a score of 21.\n# \n# \n# Example 2:\n# Input: words = [\"xxxz\",\"ax\",\"bx\",\"cx\"], letters = [\"z\",\"a\",\"b\",\"c\",\"x\",\"x\",\"x\"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]\n# Output: 27\n# Explanation:\n# Score a=4, b=4, c=4, x=5, z=10\n# Given letters, we can form the words \"ax\" (4+5), \"bx\" (4+5) and \"cx\" (4+5) with a score of 27.\n# \n# Word \"xxxz\" only get a score of 25.\n# \n# \n# Example 3:\n# Input: words = [\"leetcode\"], letters = [\"l\",\"e\",\"t\",\"c\",\"o\",\"d\"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]\n# Output: 0\n# Explanation:\n# Letter \"e\" can only be used once.\n# \n# \n# Constraints:\n# `1 <= words.length <= 14`\n# `1 <= words[i].length <= 15`\n# `1 <= letters.length <= 100`\n# `letters[i].length == 1`\n# `score.length == 26`\n# `0 <= score[i] <= 10`\n# `words[i]`, `letters[i]` contains only lower case English letters.\nclass Solution:\n def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n ", "entry_point": "maxScoreWords", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-moves-to-move-a-box-to-their-target-location", "prompt": "# Storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.\n# \n# The game is represented by a `grid` of size `m x n`, where each element is a wall, floor, or a box.\n# \n# Your task is move the box `'B'` to the target position `'T'` under the following rules:\n# Player is represented by character `'S'` and can move up, down, left, right in the `grid` if it is a floor (empy cell).\n# \n# Floor is represented by character `'.'` that means free cell to walk.\n# \n# Wall is represented by character `'#'` that means obstacle (impossible to walk there). \n# There is only one box `'B'` and one target cell `'T'` in the `grid`.\n# \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# \n# The player cannot walk through the box.\n# \n# Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return `-1`.\n# \n# \n# Example 1:\n# Input: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n# [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n# [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n# [\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n# [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n# [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\n# Output: 3\n# Explanation: We return only the number of times the box is pushed.\n# \n# \n# Example 2:\n# Input: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n# [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n# [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n# [\"#\",\"#\",\"#\",\"#\",\".\",\"#\"],\n# [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n# [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\n# Output: -1\n# \n# Example 3:\n# Input: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n# [\"#\",\"T\",\".\",\".\",\"#\",\"#\"],\n# [\"#\",\".\",\"#\",\"B\",\".\",\"#\"],\n# [\"#\",\".\",\".\",\".\",\".\",\"#\"],\n# [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n# [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\n# Output: 5\n# Explanation: push the box down, left, left, up and up.\n# \n# \n# Example 4:\n# Input: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n# [\"#\",\"S\",\"#\",\".\",\"B\",\"T\",\"#\"],\n# [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\n# Output: -1\n# \n# Constraints:\n# `m == grid.length`\n# `n == grid[i].length`\n# `1 <= m <= 20`\n# `1 <= n <= 20`\n# `grid` contains only characters `'.'`, `'#'`, `'S'` , `'T'`, or `'B'`.\n# \n# There is only one character `'S'`, `'B'` and `'T'` in the `grid`.\nclass Solution:\n def minPushBox(self, grid: List[List[str]]) -> int:\n ", "entry_point": "minPushBox", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-ways-to-stay-in-the-same-place-after-some-steps", "prompt": "# You have a pointer at index `0` in an array of size `arrLen`. At each step, you can move 1 position to the left, 1 position to the right in the array or stay in the same place (The pointer should not be placed outside the array at any time).\n# \n# Given two integers `steps` and `arrLen`, return the number of ways such that your pointer still at index `0` after exactly `steps` steps.\n# \n# Since the answer may be too large, return it modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: steps = 3, arrLen = 2\n# Output: 4\n# Explanation: There are 4 differents ways to stay at index 0 after 3 steps.\n# \n# Right, Left, Stay\n# Stay, Right, Left\n# Right, Stay, Left\n# Stay, Stay, Stay\n# \n# Example 2:\n# Input: steps = 2, arrLen = 4\n# Output: 2\n# Explanation: There are 2 differents ways to stay at index 0 after 2 steps\n# Right, Left\n# Stay, Stay\n# \n# Example 3:\n# Input: steps = 4, arrLen = 2\n# Output: 8\n# \n# Constraints:\n# `1 <= steps <= 500`\n# `1 <= arrLen <= 10^6`\nclass Solution:\n def numWays(self, steps: int, arrLen: int) -> int:\n ", "entry_point": "numWays", "cannonical_solution": "", "test": ""}
{"task_id": "palindrome-partitioning-iii", "prompt": "# You are given a string `s` containing lowercase letters and an integer `k`. You need to :\n# First, change some characters of `s` to other lowercase English letters.\n# \n# Then divide `s` into `k` non-empty disjoint substrings such that each substring is palindrome.\n# \n# Return the minimal number of characters that you need to change to divide the string.\n# \n# \n# Example 1:\n# Input: s = \"abc\", k = 2\n# Output: 1\n# Explanation: You can split the string into \"ab\" and \"c\", and change 1 character in \"ab\" to make it palindrome.\n# \n# \n# Example 2:\n# Input: s = \"aabbc\", k = 3\n# Output: 0\n# Explanation: You can split the string into \"aa\", \"bb\" and \"c\", all of them are palindrome.\n# \n# \n# Example 3:\n# Input: s = \"leetcode\", k = 8\n# Output: 0\n# \n# Constraints:\n# `1 <= k <= s.length <= 100`.\n# \n# `s` only contains lowercase English letters.\nclass Solution:\n def palindromePartition(self, s: str, k: int) -> int:\n ", "entry_point": "palindromePartition", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix", "prompt": "# Given a `m x n` binary matrix `mat`. In one step, you can choose one cell and flip it and all the four neighbours of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighboors if they share one edge.\n# \n# Return the minimum number of steps required to convert `mat` to a zero matrix or -1 if you cannot.\n# \n# Binary matrix is a matrix with all cells equal to 0 or 1 only.\n# \n# Zero matrix is a matrix with all cells equal to 0.\n# \n# \n# Example 1:\n# Input: mat = [[0,0],[0,1]]\n# Output: 3\n# Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.\n# \n# \n# Example 2:\n# Input: mat = [[0]]\n# Output: 0\n# Explanation: Given matrix is a zero matrix. We don't need to change it.\n# \n# \n# Example 3:\n# Input: mat = [[1,1,1],[1,0,1],[0,0,0]]\n# Output: 6\n# \n# Example 4:\n# Input: mat = [[1,0,0],[1,0,0]]\n# Output: -1\n# Explanation: Given matrix can't be a zero matrix\n# \n# Constraints:\n# `m == mat.length`\n# `n == mat[0].length`\n# `1 <= m <= 3`\n# `1 <= n <= 3`\n# `mat[i][j]` is 0 or 1.\nclass Solution:\n def minFlips(self, mat: List[List[int]]) -> int:\n ", "entry_point": "minFlips", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-falling-path-sum-ii", "prompt": "# Given a square grid of integers `arr`, a falling path with non-zero shifts is a choice of exactly one element from each row of `arr`, such that no two elements chosen in adjacent rows are in the same column.\n# \n# Return the minimum sum of a falling path with non-zero shifts.\n# \n# \n# Example 1:\n# Input: arr = [[1,2,3],[4,5,6],[7,8,9]]\n# Output: 13\n# Explanation: \n# The possible falling paths are:\n# [1,5,9], [1,5,7], [1,6,7], [1,6,8],\n# [2,4,8], [2,4,9], [2,6,7], [2,6,8],\n# [3,4,8], [3,4,9], [3,5,7], [3,5,9]\n# The falling path with the smallest sum is [1,5,7], so the answer is 13.\n# \n# \n# Constraints:\n# `1 <= arr.length == arr[i].length <= 200`\n# `-99 <= arr[i][j] <= 99`\nclass Solution:\n def minFallingPathSum(self, grid: List[List[int]]) -> int:\n ", "entry_point": "minFallingPathSum", "cannonical_solution": "", "test": ""}
{"task_id": "shortest-path-in-a-grid-with-obstacles-elimination", "prompt": "# Given a `m * n` grid, where each cell is either `0` (empty) or `1` (obstacle). In one step, you can move up, down, left or right from and to an empty cell.\n# \n# Return the minimum number of steps to walk from the upper left corner `(0, 0)` to the lower right corner `(m-1, n-1)` given that you can eliminate at most `k` obstacles. If it is not possible to find such walk return -1.\n# \n# \n# Example 1:\n# Input: \n# grid = \n# [[0,0,0],\n# [1,1,0],\n# [0,0,0],\n# [0,1,1],\n# [0,0,0]], \n# k = 1\n# Output: 6\n# Explanation: \n# The shortest path without eliminating any obstacle is 10. \n# The shortest path with one obstacle elimination at position (3,2) is 6. Such path is `(0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2)`.\n# \n# \n# Example 2:\n# Input: \n# grid = \n# [[0,1,1],\n# [1,1,1],\n# [1,0,0]], \n# k = 1\n# Output: -1\n# Explanation: \n# We need to eliminate at least two obstacles to find such a walk.\n# \n# \n# Constraints:\n# `grid.length == m`\n# `grid[0].length == n`\n# `1 <= m, n <= 40`\n# `1 <= k <= m*n`\n# `grid[i][j] == 0 or 1`\n# `grid[0][0] == grid[m-1][n-1] == 0`\nclass Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n ", "entry_point": "shortestPath", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-candies-you-can-get-from-boxes", "prompt": "# Given `n` boxes, each box is given in the format `[status, candies, keys, containedBoxes]` where:\n# `status[i]`: an integer which is 1 if `box[i]` is open and 0 if `box[i]` is closed.\n# \n# `candies[i]`: an integer representing the number of candies in `box[i]`.\n# \n# `keys[i]`: an array contains the indices of the boxes you can open with the key in `box[i]`.\n# \n# `containedBoxes[i]`: an array contains the indices of the boxes found in `box[i]`.\n# \n# You will start with some boxes given in `initialBoxes` array. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.\n# \n# Return the maximum number of candies you can get following the rules above.\n# \n# \n# Example 1:\n# Input: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]\n# Output: 16\n# Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2. Box 1 is closed and you don't have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.\n# \n# In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.\n# \n# Total number of candies collected = 7 + 4 + 5 = 16 candy.\n# \n# \n# Example 2:\n# Input: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]\n# Output: 6\n# Explanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys. The total number of candies will be 6.\n# \n# \n# Example 3:\n# Input: status = [1,1,1], candies = [100,1,100], keys = [[],[0,2],[]], containedBoxes = [[],[],[]], initialBoxes = [1]\n# Output: 1\n# \n# Example 4:\n# Input: status = [1], candies = [100], keys = [[]], containedBoxes = [[]], initialBoxes = []\n# Output: 0\n# \n# Example 5:\n# Input: status = [1,1,1], candies = [2,3,2], keys = [[],[],[]], containedBoxes = [[],[],[]], initialBoxes = [2,1,0]\n# Output: 7\n# \n# Constraints:\n# `1 <= status.length <= 1000`\n# `status.length == candies.length == keys.length == containedBoxes.length == n`\n# `status[i]` is `0` or `1`.\n# \n# `1 <= candies[i] <= 1000`\n# `0 <= keys[i].length <= status.length`\n# `0 <= keys[i][j] < status.length`\n# All values in `keys[i]` are unique.\n# \n# `0 <= containedBoxes[i].length <= status.length`\n# `0 <= containedBoxes[i][j] < status.length`\n# All values in `containedBoxes[i]` are unique.\n# \n# Each box is contained in one box at most.\n# \n# `0 <= initialBoxes.length <= status.length`\n# `0 <= initialBoxes[i] < status.length`\nclass Solution:\n def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:\n ", "entry_point": "maxCandies", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-paths-with-max-score", "prompt": "# You are given a square `board` of characters. You can move on the board starting at the bottom right square marked with the character `'S'`.\n# \n# You need to reach the top left square marked with the character `'E'`. The rest of the squares are labeled either with a numeric character `1, 2, ..., 9` or with an obstacle `'X'`. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.\n# \n# Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo `10^9 + 7`.\n# \n# In case there is no path, return `[0, 0]`.\n# \n# \n# Example 1:\n# Input: board = [\"E23\",\"2X2\",\"12S\"]\n# Output: [7,1]\n# \n# Example 2:\n# Input: board = [\"E12\",\"1X1\",\"21S\"]\n# Output: [4,2]\n# \n# Example 3:\n# Input: board = [\"E11\",\"XXX\",\"11S\"]\n# Output: [0,0]\n# \n# Constraints:\n# `2 <= board.length == board[i].length <= 100`\nclass Solution:\n def pathsWithMaxScore(self, board: List[str]) -> List[int]:\n ", "entry_point": "pathsWithMaxScore", "cannonical_solution": "", "test": ""}
{"task_id": "verbal-arithmetic-puzzle", "prompt": "# Given an equation, represented by `words` on left side and the `result` on right side.\n# \n# You need to check if the equation is solvable under the following rules:\n# Each character is decoded as one digit (0 - 9).\n# \n# Every pair of different characters they must map to different digits.\n# \n# Each `words[i]` and `result` are decoded as one number without leading zeros.\n# \n# Sum of numbers on left side (`words`) will equal to the number on right side (`result`). \n# Return `True` if the equation is solvable otherwise return `False`.\n# \n# \n# Example 1:\n# Input: words = [\"SEND\",\"MORE\"], result = \"MONEY\"\n# Output: true\n# Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'\n# Such that: \"SEND\" + \"MORE\" = \"MONEY\" , 9567 + 1085 = 10652\n# \n# Example 2:\n# Input: words = [\"SIX\",\"SEVEN\",\"SEVEN\"], result = \"TWENTY\"\n# Output: true\n# Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4\n# Such that: \"SIX\" + \"SEVEN\" + \"SEVEN\" = \"TWENTY\" , 650 + 68782 + 68782 = 138214\n# \n# Example 3:\n# Input: words = [\"THIS\",\"IS\",\"TOO\"], result = \"FUNNY\"\n# Output: true\n# \n# Example 4:\n# Input: words = [\"LEET\",\"CODE\"], result = \"POINT\"\n# Output: false\n# \n# Constraints:\n# `2 <= words.length <= 5`\n# `1 <= words[i].length, result.length <= 7`\n# `words[i], result` contain only uppercase English letters.\n# \n# The number of different characters used in the expression is at most `10`.\nclass Solution:\n def isSolvable(self, words: List[str], result: str) -> bool:\n ", "entry_point": "isSolvable", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-insertion-steps-to-make-a-string-palindrome", "prompt": "# Given a string `s`. In one step you can insert any character at any index of the string.\n# \n# Return the minimum number of steps to make `s` palindrome.\n# \n# A Palindrome String is one that reads the same backward as well as forward.\n# \n# \n# Example 1:\n# Input: s = \"zzazz\"\n# Output: 0\n# Explanation: The string \"zzazz\" is already palindrome we don't need any insertions.\n# \n# \n# Example 2:\n# Input: s = \"mbadm\"\n# Output: 2\n# Explanation: String can be \"mbdadbm\" or \"mdbabdm\".\n# \n# \n# Example 3:\n# Input: s = \"leetcode\"\n# Output: 5\n# Explanation: Inserting 5 characters the string becomes \"leetcodocteel\".\n# \n# \n# Example 4:\n# Input: s = \"g\"\n# Output: 0\n# \n# Example 5:\n# Input: s = \"no\"\n# Output: 1\n# \n# Constraints:\n# `1 <= s.length <= 500`\n# All characters of `s` are lower case English letters.\nclass Solution:\n def minInsertions(self, s: str) -> int:\n ", "entry_point": "minInsertions", "cannonical_solution": "", "test": ""}
{"task_id": "distinct-echo-substrings", "prompt": "# Return the number of distinct non-empty substrings of `text` that can be written as the concatenation of some string with itself (i.e. it can be written as `a + a` where `a` is some string).\n# \n# \n# Example 1:\n# Input: text = \"abcabcabc\"\n# Output: 3\n# Explanation: The 3 substrings are \"abcabc\", \"bcabca\" and \"cabcab\".\n# \n# \n# Example 2:\n# Input: text = \"leetcodeleetcode\"\n# Output: 2\n# Explanation: The 2 substrings are \"ee\" and \"leetcodeleetcode\".\n# \n# \n# Constraints:\n# `1 <= text.length <= 2000`\n# `text` has only lowercase English letters.\nclass Solution:\n def distinctEchoSubstrings(self, text: str) -> int:\n ", "entry_point": "distinctEchoSubstrings", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-distance-to-type-a-word-using-two-fingers", "prompt": "# You have a keyboard layout as shown above in the XY plane, where each English uppercase letter is located at some coordinate, for example, the letter A is located at coordinate (0,0), the letter B is located at coordinate (0,1), the letter P is located at coordinate (2,3) and the letter Z is located at coordinate (4,1).\n# \n# Given the string `word`, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1,y1) and (x2,y2) is |x1 - x2| + |y1 - y2|. \n# Note that the initial positions of your two fingers are considered free so don't count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.\n# \n# \n# Example 1:\n# Input: word = \"CAKE\"\n# Output: 3\n# Explanation: \n# Using two fingers, one optimal way to type \"CAKE\" is: \n# Finger 1 on letter 'C' -> cost = 0 \n# Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 \n# Finger 2 on letter 'K' -> cost = 0 \n# Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 \n# Total distance = 3\n# \n# Example 2:\n# Input: word = \"HAPPY\"\n# Output: 6\n# Explanation: \n# Using two fingers, one optimal way to type \"HAPPY\" is:\n# Finger 1 on letter 'H' -> cost = 0\n# Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2\n# Finger 2 on letter 'P' -> cost = 0\n# Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0\n# Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4\n# Total distance = 6\n# \n# Example 3:\n# Input: word = \"NEW\"\n# Output: 3\n# \n# Example 4:\n# Input: word = \"YEAR\"\n# Output: 7\n# \n# Constraints:\n# `2 <= word.length <= 300`\n# Each word[i]` is an English uppercase letter.\nclass Solution:\n def minimumDistance(self, word: str) -> int:\n ", "entry_point": "minimumDistance", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-number-of-taps-to-open-to-water-a-garden", "prompt": "# There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`).\n# \n# There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden.\n# \n# Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-indexed) means the `i-th` tap can water the area `[i - ranges[i], i + ranges[i]]` if it was open.\n# \n# Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.\n# \n# \n# Example 1:\n# Input: n = 5, ranges = [3,4,1,1,0,0]\n# Output: 1\n# Explanation: The tap at point 0 can cover the interval [-3,3]\n# The tap at point 1 can cover the interval [-3,5]\n# The tap at point 2 can cover the interval [1,3]\n# The tap at point 3 can cover the interval [2,4]\n# The tap at point 4 can cover the interval [4,4]\n# The tap at point 5 can cover the interval [5,5]\n# Opening Only the second tap will water the whole garden [0,5]\n# \n# Example 2:\n# Input: n = 3, ranges = [0,0,0,0]\n# Output: -1\n# Explanation: Even if you activate all the four taps you cannot water the whole garden.\n# \n# \n# Example 3:\n# Input: n = 7, ranges = [1,2,1,0,2,1,0,1]\n# Output: 3\n# \n# Example 4:\n# Input: n = 8, ranges = [4,0,0,0,0,0,0,0,4]\n# Output: 2\n# \n# Example 5:\n# Input: n = 8, ranges = [4,0,0,0,4,0,0,0,4]\n# Output: 1\n# \n# Constraints:\n# `1 <= n <= 10^4`\n# `ranges.length == n + 1`\n# `0 <= ranges[i] <= 100`\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n ", "entry_point": "minTaps", "cannonical_solution": "", "test": ""}
{"task_id": "reverse-subarray-to-maximize-array-value", "prompt": "# You are given an integer array `nums`. The value of this array is defined as the sum of `|nums[i]-nums[i+1]|` for all `0 <= i < nums.length-1`.\n# \n# You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.\n# \n# Find maximum possible value of the final array.\n# \n# \n# Example 1:\n# Input: nums = [2,3,1,5,4]\n# Output: 10\n# Explanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.\n# \n# \n# Example 2:\n# Input: nums = [2,4,9,24,2,1,10]\n# Output: 68\n# \n# Constraints:\n# `1 <= nums.length <= 3*10^4`\n# `-10^5 <= nums[i] <= 10^5`\nclass Solution:\n def maxValueAfterReverse(self, nums: List[int]) -> int:\n ", "entry_point": "maxValueAfterReverse", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-difficulty-of-a-job-schedule", "prompt": "# You want to schedule a list of jobs in `d` days. Jobs are dependent (i.e To work on the `i-th` job, you have to finish all the jobs `j` where `0 <= j < i`).\n# \n# You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the `d` days. The difficulty of a day is the maximum difficulty of a job done in that day.\n# \n# Given an array of integers `jobDifficulty` and an integer `d`. The difficulty of the `i-th` job is `jobDifficulty[i]`.\n# \n# Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.\n# \n# \n# Example 1:\n# Input: jobDifficulty = [6,5,4,3,2,1], d = 2\n# Output: 7\n# Explanation: First day you can finish the first 5 jobs, total difficulty = 6.\n# \n# Second day you can finish the last job, total difficulty = 1.\n# \n# The difficulty of the schedule = 6 + 1 = 7 \n# \n# Example 2:\n# Input: jobDifficulty = [9,9,9], d = 4\n# Output: -1\n# Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.\n# \n# \n# Example 3:\n# Input: jobDifficulty = [1,1,1], d = 3\n# Output: 3\n# Explanation: The schedule is one job per day. total difficulty will be 3.\n# \n# \n# Example 4:\n# Input: jobDifficulty = [7,1,7,1,7,1], d = 3\n# Output: 15\n# \n# Example 5:\n# Input: jobDifficulty = [11,111,22,222,33,333,44,444], d = 6\n# Output: 843\n# \n# Constraints:\n# `1 <= jobDifficulty.length <= 300`\n# `0 <= jobDifficulty[i] <= 1000`\n# `1 <= d <= 10`\nclass Solution:\n def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:\n ", "entry_point": "minDifficulty", "cannonical_solution": "", "test": ""}
{"task_id": "jump-game-v", "prompt": "# Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index:\n# `i + x` where: `i + x < arr.length` and ` 0 < x <= d`.\n# \n# `i - x` where: `i - x >= 0` and ` 0 < x <= d`.\n# \n# In addition, you can only jump from index `i` to index `j` if `arr[i] > arr[j]` and `arr[i] > arr[k]` for all indices `k` between `i` and `j` (More formally `min(i, j) < k < max(i, j)`).\n# \n# You can choose any index of the array and start jumping. Return the maximum number of indices you can visit.\n# \n# Notice that you can not jump outside of the array at any time.\n# \n# \n# Example 1:\n# Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2\n# Output: 4\n# Explanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.\n# \n# Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.\n# \n# Similarly You cannot jump from index 3 to index 2 or index 1.\n# \n# \n# Example 2:\n# Input: arr = [3,3,3,3,3], d = 3\n# Output: 1\n# Explanation: You can start at any index. You always cannot jump to any index.\n# \n# \n# Example 3:\n# Input: arr = [7,6,5,4,3,2,1], d = 1\n# Output: 7\n# Explanation: Start at index 0. You can visit all the indicies. \n# \n# Example 4:\n# Input: arr = [7,1,7,1,7,1], d = 2\n# Output: 2\n# \n# Example 5:\n# Input: arr = [66], d = 1\n# Output: 1\n# \n# Constraints:\n# `1 <= arr.length <= 1000`\n# `1 <= arr[i] <= 10^5`\n# `1 <= d <= arr.length`\nclass Solution:\n def maxJumps(self, arr: List[int], d: int) -> int:\n ", "entry_point": "maxJumps", "cannonical_solution": "", "test": ""}
{"task_id": "jump-game-iv", "prompt": "# Given an array of integers `arr`, you are initially positioned at the first index of the array.\n# \n# In one step you can jump from index `i` to index:\n# `i + 1` where: `i + 1 < arr.length`.\n# \n# `i - 1` where: `i - 1 >= 0`.\n# \n# `j` where: `arr[i] == arr[j]` and `i != j`.\n# \n# Return the minimum number of steps to reach the last index of the array.\n# \n# Notice that you can not jump outside of the array at any time.\n# \n# \n# Example 1:\n# Input: arr = [100,-23,-23,404,100,23,23,23,3,404]\n# Output: 3\n# Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.\n# \n# \n# Example 2:\n# Input: arr = [7]\n# Output: 0\n# Explanation: Start index is the last index. You don't need to jump.\n# \n# \n# Example 3:\n# Input: arr = [7,6,9,6,9,6,9,7]\n# Output: 1\n# Explanation: You can jump directly from index 0 to index 7 which is last index of the array.\n# \n# \n# Example 4:\n# Input: arr = [6,1,9]\n# Output: 2\n# \n# Example 5:\n# Input: arr = [11,22,7,7,7,7,7,7,7,22,13]\n# Output: 3\n# \n# Constraints:\n# `1 <= arr.length <= 5 * 104`\n# `-108 <= arr[i] <= 108`\nclass Solution:\n def minJumps(self, arr: List[int]) -> int:\n ", "entry_point": "minJumps", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-students-taking-exam", "prompt": "# Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character.\n# \n# Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible..\n# \n# Students must be placed in seats in good condition.\n# \n# \n# Example 1:\n# Input: seats = [[\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n# [\".\",\"#\",\"#\",\"#\",\"#\",\".\"],\n# [\"#\",\".\",\"#\",\"#\",\".\",\"#\"]]\n# Output: 4\n# Explanation: Teacher can place 4 students in available seats so they don't cheat on the exam. \n# \n# Example 2:\n# Input: seats = [[\".\",\"#\"],\n# [\"#\",\"#\"],\n# [\"#\",\".\"],\n# [\"#\",\"#\"],\n# [\".\",\"#\"]]\n# Output: 3\n# Explanation: Place all students in available seats. \n# \n# Example 3:\n# Input: seats = [[\"#\",\".\",\".\",\".\",\"#\"],\n# [\".\",\"#\",\".\",\"#\",\".\"],\n# [\".\",\".\",\"#\",\".\",\".\"],\n# [\".\",\"#\",\".\",\"#\",\".\"],\n# [\"#\",\".\",\".\",\".\",\"#\"]]\n# Output: 10\n# Explanation: Place students in available seats in column 1, 3 and 5.\n# \n# \n# Constraints:\n# `seats` contains only characters `'.' and``'#'.`\n# `m == seats.length`\n# `n == seats[i].length`\n# `1 <= m <= 8`\n# `1 <= n <= 8`\nclass Solution:\n def maxStudents(self, seats: List[List[str]]) -> int:\n ", "entry_point": "maxStudents", "cannonical_solution": "", "test": ""}
{"task_id": "construct-target-array-with-multiple-sums", "prompt": "# Given an array of integers `target`. From a starting array, `A` consisting of all 1's, you may perform the following procedure :\n# let `x` be the sum of all elements currently in your array.\n# \n# choose index `i`, such that `0 <= i < target.size` and set the value of `A` at index `i` to `x`.\n# \n# You may repeat this procedure as many times as needed.\n# \n# Return True if it is possible to construct the `target` array from `A` otherwise return False.\n# \n# \n# Example 1:\n# Input: target = [9,3,5]\n# Output: true\n# Explanation: Start with [1, 1, 1] \n# [1, 1, 1], sum = 3 choose index 1\n# [1, 3, 1], sum = 5 choose index 2\n# [1, 3, 5], sum = 9 choose index 0\n# [9, 3, 5] Done\n# \n# Example 2:\n# Input: target = [1,1,1,2]\n# Output: false\n# Explanation: Impossible to create target array from [1,1,1,1].\n# \n# \n# Example 3:\n# Input: target = [8,5]\n# Output: true\n# \n# Constraints:\n# `N == target.length`\n# `1 <= target.length <= 5 * 10^4`\n# `1 <= target[i] <= 10^9`\nclass Solution:\n def isPossible(self, target: List[int]) -> bool:\n ", "entry_point": "isPossible", "cannonical_solution": "", "test": ""}
{"task_id": "count-all-valid-pickup-and-delivery-options", "prompt": "# Given `n` orders, each order consist in pickup and delivery services. \n# Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). \n# Since the answer may be too large, return it modulo 10^9 + 7.\n# \n# \n# Example 1:\n# Input: n = 1\n# Output: 1\n# Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.\n# \n# \n# Example 2:\n# Input: n = 2\n# Output: 6\n# Explanation: All possible orders: \n# (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).\n# \n# This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.\n# \n# \n# Example 3:\n# Input: n = 3\n# Output: 90\n# \n# Constraints:\n# `1 <= n <= 500`\nclass Solution:\n def countOrders(self, n: int) -> int:\n ", "entry_point": "countOrders", "cannonical_solution": "", "test": ""}
{"task_id": "largest-multiple-of-three", "prompt": "# Given an integer array of `digits`, return the largest multiple of three that can be formed by concatenating some of the given digits in any order.\n# \n# Since the answer may not fit in an integer data type, return the answer as a string.\n# \n# If there is no answer return an empty string.\n# \n# \n# Example 1:\n# Input: digits = [8,1,9]\n# Output: \"981\"\n# \n# Example 2:\n# Input: digits = [8,6,7,1,0]\n# Output: \"8760\"\n# \n# Example 3:\n# Input: digits = [1]\n# Output: \"\"\n# \n# Example 4:\n# Input: digits = [0,0,0,0,0,0]\n# Output: \"0\"\n# \n# Constraints:\n# `1 <= digits.length <= 10^4`\n# `0 <= digits[i] <= 9`\n# The returning answer must not contain unnecessary leading zeros.\nclass Solution:\n def largestMultipleOfThree(self, digits: List[int]) -> str:\n ", "entry_point": "largestMultipleOfThree", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-cost-to-make-at-least-one-valid-path-in-a-grid", "prompt": "# Given a m x n `grid`. Each cell of the `grid` has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of `grid[i][j]` can be:\n# 1 which means go to the cell to the right. (i.e go from `grid[i][j]` to `grid[i][j + 1]`)\n# 2 which means go to the cell to the left. (i.e go from `grid[i][j]` to `grid[i][j - 1]`)\n# 3 which means go to the lower cell. (i.e go from `grid[i][j]` to `grid[i + 1][j]`)\n# 4 which means go to the upper cell. (i.e go from `grid[i][j]` to `grid[i - 1][j]`)\n# Notice that there could be some invalid signs on the cells of the `grid` which points outside the `grid`.\n# \n# You will initially start at the upper left cell `(0,0)`. A valid path in the grid is a path which starts from the upper left cell `(0,0)` and ends at the bottom-right cell `(m - 1, n - 1)` following the signs on the grid. The valid path doesn't have to be the shortest.\n# \n# You can modify the sign on a cell with `cost = 1`. You can modify the sign on a cell one time only.\n# \n# Return the minimum cost to make the grid have at least one valid path.\n# \n# \n# Example 1:\n# Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]\n# Output: 3\n# Explanation: You will start at point (0, 0).\n# \n# The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)\n# The total cost = 3.\n# \n# \n# Example 2:\n# Input: grid = [[1,1,3],[3,2,2],[1,1,4]]\n# Output: 0\n# Explanation: You can follow the path from (0, 0) to (2, 2).\n# \n# \n# Example 3:\n# Input: grid = [[1,2],[4,3]]\n# Output: 1\n# \n# Example 4:\n# Input: grid = [[2,2,2],[2,2,2]]\n# Output: 3\n# \n# Example 5:\n# Input: grid = [[4]]\n# Output: 0\n# \n# Constraints:\n# `m == grid.length`\n# `n == grid[i].length`\n# `1 <= m, n <= 100`\nclass Solution:\n def minCost(self, grid: List[List[int]]) -> int:\n ", "entry_point": "minCost", "cannonical_solution": "", "test": ""}
{"task_id": "frog-position-after-t-seconds", "prompt": "# Given an undirected tree consisting of `n` vertices numbered from `1` to `n`. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex.\n# \n# The edges of the undirected tree are given in the array `edges`, where `edges[i] = [ai, bi]` means that exists an edge connecting the vertices `ai` and `bi`.\n# \n# Return the probability that after `t` seconds the frog is on the vertex `target`.\n# \n# \n# Example 1:\n# Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4\n# Output: 0.16666666666666666 \n# Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. \n# \n# Example 2:\n# Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7\n# Output: 0.3333333333333333\n# Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1. \n# \n# Example 3:\n# Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 20, target = 6\n# Output: 0.16666666666666666\n# \n# Constraints:\n# `1 <= n <= 100`\n# `edges.length == n - 1`\n# `edges[i].length == 2`\n# `1 <= ai, bi <= n`\n# `1 <= t <= 50`\n# `1 <= target <= n`\n# Answers within `10-5` of the actual value will be accepted as correct.\nclass Solution:\n def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:\n ", "entry_point": "frogPosition", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-performance-of-a-team", "prompt": "# There are `n` engineers numbered from 1 to `n` and two arrays: `speed` and `efficiency`, where `speed[i]` and `efficiency[i]` represent the speed and efficiency for the i-th engineer respectively. Return the maximum performance of a team composed of at most `k` engineers, since the answer can be a huge number, return this modulo 10^9 + 7.\n# \n# The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. \n# \n# Example 1:\n# Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2\n# Output: 60\n# Explanation: \n# We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.\n# \n# \n# Example 2:\n# Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3\n# Output: 68\n# Explanation:\n# This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.\n# \n# \n# Example 3:\n# Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4\n# Output: 72\n# \n# Constraints:\n# `1 <= n <= 10^5`\n# `speed.length == n`\n# `efficiency.length == n`\n# `1 <= speed[i] <= 10^5`\n# `1 <= efficiency[i] <= 10^8`\n# `1 <= k <= n`\nclass Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n ", "entry_point": "maxPerformance", "cannonical_solution": "", "test": ""}
{"task_id": "pizza-with-3n-slices", "prompt": "# There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:\n# You will pick any pizza slice.\n# \n# Your friend Alice will pick next slice in anti clockwise direction of your pick. \n# Your friend Bob will pick next slice in clockwise direction of your pick.\n# \n# Repeat until there are no more slices of pizzas.\n# \n# Sizes of Pizza slices is represented by circular array `slices` in clockwise direction.\n# \n# Return the maximum possible sum of slice sizes which you can have.\n# \n# \n# Example 1:\n# Input: slices = [1,2,3,4,5,6]\n# Output: 10\n# Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.\n# \n# \n# Example 2:\n# Input: slices = [8,9,8,6,1,1]\n# Output: 16\n# Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.\n# \n# Example 3:\n# Input: slices = [4,1,2,5,8,3,1,9,7]\n# Output: 21\n# \n# Example 4:\n# Input: slices = [3,1,2]\n# Output: 3\n# \n# Constraints:\n# `1 <= slices.length <= 500`\n# `slices.length % 3 == 0`\n# `1 <= slices[i] <= 1000`\nclass Solution:\n def maxSizeSlices(self, slices: List[int]) -> int:\n ", "entry_point": "maxSizeSlices", "cannonical_solution": "", "test": ""}
{"task_id": "longest-happy-prefix", "prompt": "# A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).\n# \n# Given a string `s`. Return the longest happy prefix of `s` .\n# \n# Return an empty string if no such prefix exists.\n# \n# \n# Example 1:\n# Input: s = \"level\"\n# Output: \"l\"\n# Explanation: s contains 4 prefix excluding itself (\"l\", \"le\", \"lev\", \"leve\"), and suffix (\"l\", \"el\", \"vel\", \"evel\"). The largest prefix which is also suffix is given by \"l\".\n# \n# \n# Example 2:\n# Input: s = \"ababab\"\n# Output: \"abab\"\n# Explanation: \"abab\" is the largest prefix which is also suffix. They can overlap in the original string.\n# \n# \n# Example 3:\n# Input: s = \"leetcodeleet\"\n# Output: \"leet\"\n# \n# Example 4:\n# Input: s = \"a\"\n# Output: \"\"\n# \n# Constraints:\n# `1 <= s.length <= 10^5`\n# `s` contains only lowercase English letters.\nclass Solution:\n def longestPrefix(self, s: str) -> str:\n ", "entry_point": "longestPrefix", "cannonical_solution": "", "test": ""}
{"task_id": "find-all-good-strings", "prompt": "# Given the strings `s1` and `s2` of size `n`, and the string `evil`. Return the number of good strings.\n# \n# A good string has size `n`, it is alphabetically greater than or equal to `s1`, it is alphabetically smaller than or equal to `s2`, and it does not contain the string `evil` as a substring. Since the answer can be a huge number, return this modulo 10^9 + 7.\n# \n# \n# Example 1:\n# Input: n = 2, s1 = \"aa\", s2 = \"da\", evil = \"b\"\n# Output: 51 \n# Explanation: There are 25 good strings starting with 'a': \"aa\",\"ac\",\"ad\",...,\"az\". Then there are 25 good strings starting with 'c': \"ca\",\"cc\",\"cd\",...,\"cz\" and finally there is one good string starting with 'd': \"da\". \n# \n# Example 2:\n# Input: n = 8, s1 = \"leetcode\", s2 = \"leetgoes\", evil = \"leet\"\n# Output: 0 \n# Explanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix \"leet\", therefore, there is not any good string.\n# \n# \n# Example 3:\n# Input: n = 2, s1 = \"gx\", s2 = \"gz\", evil = \"x\"\n# Output: 2\n# \n# Constraints:\n# `s1.length == n`\n# `s2.length == n`\n# `s1 <= s2`\n# `1 <= n <= 500`\n# `1 <= evil.length <= 50`\n# All strings consist of lowercase English letters.\nclass Solution:\n def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:\n ", "entry_point": "findGoodStrings", "cannonical_solution": "", "test": ""}
{"task_id": "reducing-dishes", "prompt": "# A chef has collected data on the `satisfaction` level of his `n` dishes. Chef can cook any dish in 1 unit of time.\n# \n# Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. `time[i]`*`satisfaction[i]`\n# Return the maximum sum of Like-time coefficient that the chef can obtain after dishes preparation.\n# \n# Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.\n# \n# \n# Example 1:\n# Input: satisfaction = [-1,-8,0,5,-9]\n# Output: 14\n# Explanation: After Removing the second and last dish, the maximum total Like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14). Each dish is prepared in one unit of time.\n# \n# \n# Example 2:\n# Input: satisfaction = [4,3,2]\n# Output: 20\n# Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)\n# \n# Example 3:\n# Input: satisfaction = [-1,-4,-5]\n# Output: 0\n# Explanation: People don't like the dishes. No dish is prepared.\n# \n# \n# Example 4:\n# Input: satisfaction = [-2,5,-1,0,3,-3]\n# Output: 35\n# \n# Constraints:\n# `n == satisfaction.length`\n# `1 <= n <= 500`\n# `-10^3 <= satisfaction[i] <= 10^3`\nclass Solution:\n def maxSatisfaction(self, satisfaction: List[int]) -> int:\n ", "entry_point": "maxSatisfaction", "cannonical_solution": "", "test": ""}
{"task_id": "stone-game-iii", "prompt": "# Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array `stoneValue`.\n# \n# Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row.\n# \n# The score of each player is the sum of values of the stones taken. The score of each player is 0 initially.\n# \n# The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.\n# \n# Assume Alice and Bob play optimally.\n# \n# Return \"Alice\" if Alice will win, \"Bob\" if Bob will win or \"Tie\" if they end the game with the same score.\n# \n# \n# Example 1:\n# Input: values = [1,2,3,7]\n# Output: \"Bob\"\n# Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.\n# \n# \n# Example 2:\n# Input: values = [1,2,3,-9]\n# Output: \"Alice\"\n# Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score.\n# \n# If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose.\n# \n# If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose.\n# \n# Remember that both play optimally so here Alice will choose the scenario that makes her win.\n# \n# \n# Example 3:\n# Input: values = [1,2,3,6]\n# Output: \"Tie\"\n# Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.\n# \n# \n# Example 4:\n# Input: values = [1,2,3,-1,-2,-3,7]\n# Output: \"Alice\"\n# \n# Example 5:\n# Input: values = [-1,-2,-3]\n# Output: \"Tie\"\n# \n# Constraints:\n# `1 <= values.length <= 50000`\n# `-1000 <= values[i] <= 1000`\nclass Solution:\n def stoneGameIII(self, stoneValue: List[int]) -> str:\n ", "entry_point": "stoneGameIII", "cannonical_solution": "", "test": ""}
{"task_id": "restore-the-array", "prompt": "# A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits and all we know is that all integers in the array were in the range `[1, k]` and there are no leading zeros in the array.\n# \n# Given the string `s` and the integer `k`. There can be multiple ways to restore the array.\n# \n# Return the number of possible array that can be printed as a string `s` using the mentioned program.\n# \n# The number of ways could be very large so return it modulo `10^9 + 7`\n# \n# Example 1:\n# Input: s = \"1000\", k = 10000\n# Output: 1\n# Explanation: The only possible array is [1000]\n# \n# Example 2:\n# Input: s = \"1000\", k = 10\n# Output: 0\n# Explanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.\n# \n# \n# Example 3:\n# Input: s = \"1317\", k = 2000\n# Output: 8\n# Explanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]\n# \n# Example 4:\n# Input: s = \"2020\", k = 30\n# Output: 1\n# Explanation: The only possible array is [20,20]. [2020] is invalid because 2020 > 30. [2,020] is ivalid because 020 contains leading zeros.\n# \n# \n# Example 5:\n# Input: s = \"1234567890\", k = 90\n# Output: 34\n# \n# Constraints:\n# `1 <= s.length <= 10^5`.\n# \n# `s` consists of only digits and doesn't contain leading zeros.\n# \n# `1 <= k <= 10^9`.\nclass Solution:\n def numberOfArrays(self, s: str, k: int) -> int:\n ", "entry_point": "numberOfArrays", "cannonical_solution": "", "test": ""}
{"task_id": "build-array-where-you-can-find-the-maximum-exactly-k-comparisons", "prompt": "# Given three integers `n`, `m` and `k`. Consider the following algorithm to find the maximum element of an array of positive integers:\n# You should build the array arr which has the following properties:\n# `arr` has exactly `n` integers.\n# \n# `1 <= arr[i] <= m` where `(0 <= i < n)`.\n# \n# After applying the mentioned algorithm to `arr`, the value `search_cost` is equal to `k`.\n# \n# Return the number of ways to build the array `arr` under the mentioned conditions. As the answer may grow large, the answer must be computed modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: n = 2, m = 3, k = 1\n# Output: 6\n# Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]\n# \n# Example 2:\n# Input: n = 5, m = 2, k = 3\n# Output: 0\n# Explanation: There are no possible arrays that satisify the mentioned conditions.\n# \n# \n# Example 3:\n# Input: n = 9, m = 1, k = 1\n# Output: 1\n# Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]\n# \n# Example 4:\n# Input: n = 50, m = 100, k = 25\n# Output: 34549172\n# Explanation: Don't forget to compute the answer modulo 1000000007\n# \n# Example 5:\n# Input: n = 37, m = 17, k = 7\n# Output: 418930126\n# \n# Constraints:\n# `1 <= n <= 50`\n# `1 <= m <= 100`\n# `0 <= k <= n`\nclass Solution:\n def numOfArrays(self, n: int, m: int, k: int) -> int:\n ", "entry_point": "numOfArrays", "cannonical_solution": "", "test": ""}
{"task_id": "constrained-subsequence-sum", "prompt": "# Given an integer array `nums` and an integer `k`, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, `nums[i]` and `nums[j]`, where `i < j`, the condition `j - i <= k` is satisfied.\n# \n# A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.\n# \n# \n# Example 1:\n# Input: nums = [10,2,-10,5,20], k = 2\n# Output: 37\n# Explanation: The subsequence is [10, 2, 5, 20].\n# \n# \n# Example 2:\n# Input: nums = [-1,-2,-3], k = 1\n# Output: -1\n# Explanation: The subsequence must be non-empty, so we choose the largest number.\n# \n# \n# Example 3:\n# Input: nums = [10,-2,-10,-5,20], k = 2\n# Output: 23\n# Explanation: The subsequence is [10, -2, -5, 20].\n# \n# \n# Constraints:\n# `1 <= k <= nums.length <= 105`\n# `-104 <= nums[i] <= 104`\nclass Solution:\n def constrainedSubsetSum(self, nums: List[int], k: int) -> int:\n ", "entry_point": "constrainedSubsetSum", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-ways-to-wear-different-hats-to-each-other", "prompt": "# There are `n` people and 40 types of hats labeled from 1 to 40.\n# \n# Given a list of list of integers `hats`, where `hats[i]` is a list of all hats preferred by the i-th` person.\n# \n# Return the number of ways that the n people wear different hats to each other.\n# \n# Since the answer may be too large, return it modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: hats = [[3,4],[4,5],[5]]\n# Output: 1\n# Explanation: There is only one way to choose hats given the conditions. \n# First person choose hat 3, Second person choose hat 4 and last one hat 5.\n# \n# \n# Example 2:\n# Input: hats = [[3,5,1],[3,5]]\n# Output: 4\n# Explanation: There are 4 ways to choose hats\n# (3,5), (5,3), (1,3) and (1,5)\n# \n# Example 3:\n# Input: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]\n# Output: 24\n# Explanation: Each person can choose hats labeled from 1 to 4.\n# \n# Number of Permutations of (1,2,3,4) = 24.\n# \n# \n# Example 4:\n# Input: hats = [[1,2,3],[2,3,5,6],[1,3,7,9],[1,8,9],[2,5,7]]\n# Output: 111\n# \n# Constraints:\n# `n == hats.length`\n# `1 <= n <= 10`\n# `1 <= hats[i].length <= 40`\n# `1 <= hats[i][j] <= 40`\n# `hats[i]` contains a list of unique integers.\nclass Solution:\n def numberWays(self, hats: List[List[int]]) -> int:\n ", "entry_point": "numberWays", "cannonical_solution": "", "test": ""}
{"task_id": "find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows", "prompt": "# You are given an `m * n` matrix, `mat`, and an integer `k`, which has its rows sorted in non-decreasing order.\n# \n# You are allowed to choose exactly 1 element from each row to form an array. Return the Kth smallest array sum among all possible arrays.\n# \n# \n# Example 1:\n# Input: mat = [[1,3,11],[2,4,6]], k = 5\n# Output: 7\n# Explanation: Choosing one element from each row, the first k smallest sum are:\n# [1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7. \n# \n# Example 2:\n# Input: mat = [[1,3,11],[2,4,6]], k = 9\n# Output: 17\n# \n# Example 3:\n# Input: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7\n# Output: 9\n# Explanation: Choosing one element from each row, the first k smallest sum are:\n# [1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9. \n# \n# Example 4:\n# Input: mat = [[1,1,10],[2,2,9]], k = 7\n# Output: 12\n# \n# Constraints:\n# `m == mat.length`\n# `n == mat.length[i]`\n# `1 <= m, n <= 40`\n# `1 <= k <= min(200, n ^ m)`\n# `1 <= mat[i][j] <= 5000`\n# `mat[i]` is a non decreasing array.\nclass Solution:\n def kthSmallest(self, mat: List[List[int]], k: int) -> int:\n ", "entry_point": "kthSmallest", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-ways-of-cutting-a-pizza", "prompt": "# Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. \n# For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.\n# \n# Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.\n# \n# \n# Example 1:\n# Input: pizza = [\"A..\",\"AAA\",\"...\"], k = 3\n# Output: 3 \n# Explanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.\n# \n# \n# Example 2:\n# Input: pizza = [\"A..\",\"AA.\",\"...\"], k = 3\n# Output: 1\n# \n# Example 3:\n# Input: pizza = [\"A..\",\"A..\",\"...\"], k = 1\n# Output: 1\n# \n# Constraints:\n# `1 <= rows, cols <= 50`\n# `rows == pizza.length`\n# `cols == pizza[i].length`\n# `1 <= k <= 10`\n# `pizza` consists of characters `'A'` and `'.'` only.\nclass Solution:\n def ways(self, pizza: List[str], k: int) -> int:\n ", "entry_point": "ways", "cannonical_solution": "", "test": ""}
{"task_id": "form-largest-integer-with-digits-that-add-up-to-target", "prompt": "# Given an array of integers `cost` and an integer `target`. Return the maximum integer you can paint under the following rules:\n# The cost of painting a digit (i+1) is given by `cost[i]` (0 indexed).\n# \n# The total cost used must be equal to `target`.\n# \n# Integer does not have digits 0.\n# \n# Since the answer may be too large, return it as string.\n# \n# If there is no way to paint any integer given the condition, return \"0\".\n# \n# \n# Example 1:\n# Input: cost = [4,3,2,5,6,7,2,5,5], target = 9\n# Output: \"7772\"\n# Explanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost(\"7772\") = 2*3+ 3*1 = 9. You could also paint \"977\", but \"7772\" is the largest number.\n# \n# Digit cost\n# 1 -> 4\n# 2 -> 3\n# 3 -> 2\n# 4 -> 5\n# 5 -> 6\n# 6 -> 7\n# 7 -> 2\n# 8 -> 5\n# 9 -> 5\n# \n# Example 2:\n# Input: cost = [7,6,5,5,5,6,8,7,8], target = 12\n# Output: \"85\"\n# Explanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost(\"85\") = 7 + 5 = 12.\n# \n# \n# Example 3:\n# Input: cost = [2,4,6,2,4,6,4,4,4], target = 5\n# Output: \"0\"\n# Explanation: It's not possible to paint any integer with total cost equal to target.\n# \n# \n# Example 4:\n# Input: cost = [6,10,15,40,40,40,40,40,40], target = 47\n# Output: \"32211\"\n# \n# Constraints:\n# `cost.length == 9`\n# `1 <= cost[i] <= 5000`\n# `1 <= target <= 5000`\nclass Solution:\n def largestNumber(self, cost: List[int], target: int) -> str:\n ", "entry_point": "largestNumber", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-number-of-darts-inside-of-a-circular-dartboard", "prompt": "# You have a very large square wall and a circular dartboard placed on the wall. You have been challenged to throw darts into the board blindfolded. Darts thrown at the wall are represented as an array of `points` on a 2D plane. \n# Return the maximum number of points that are within or lie on any circular dartboard of radius `r`.\n# \n# \n# Example 1:\n# Input: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 2\n# Output: 4\n# Explanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.\n# \n# \n# Example 2:\n# Input: points = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5\n# Output: 5\n# Explanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).\n# \n# \n# Example 3:\n# Input: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 1\n# Output: 1\n# \n# Example 4:\n# Input: points = [[1,2],[3,5],[1,-1],[2,3],[4,1],[1,3]], r = 2\n# Output: 4\n# \n# Constraints:\n# `1 <= points.length <= 100`\n# `points[i].length == 2`\n# `-10^4 <= points[i][0], points[i][1] <= 10^4`\n# `1 <= r <= 5000`\nclass Solution:\n def numPoints(self, darts: List[List[int]], r: int) -> int:\n ", "entry_point": "numPoints", "cannonical_solution": "", "test": ""}
{"task_id": "max-dot-product-of-two-subsequences", "prompt": "# Given two arrays `nums1` and `nums2`.\n# \n# Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.\n# \n# A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, `[2,3,5]` is a subsequence of `[1,2,3,4,5]` while `[1,5,3]` is not).\n# \n# \n# Example 1:\n# Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]\n# Output: 18\n# Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\n# \n# Their dot product is (2*3 + (-2)*(-6)) = 18.\n# \n# \n# Example 2:\n# Input: nums1 = [3,-2], nums2 = [2,-6,7]\n# Output: 21\n# Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.\n# \n# Their dot product is (3*7) = 21.\n# \n# \n# Example 3:\n# Input: nums1 = [-1,-1], nums2 = [1,1]\n# Output: -1\n# Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.\n# \n# Their dot product is -1.\n# \n# \n# Constraints:\n# `1 <= nums1.length, nums2.length <= 500`\n# `-1000 <= nums1[i], nums2[i] <= 1000`\nclass Solution:\n def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:\n ", "entry_point": "maxDotProduct", "cannonical_solution": "", "test": ""}
{"task_id": "cherry-pickup-ii", "prompt": "# Given a `rows x cols` matrix `grid` representing a field of cherries. Each cell in `grid` represents the number of cherries that you can collect.\n# \n# You have two robots that can collect cherries for you, Robot #1 is located at the top-left corner (0,0) , and Robot #2 is located at the top-right corner (0, cols-1) of the grid.\n# \n# Return the maximum number of cherries collection using both robots by following the rules below:\n# From a cell (i,j), robots can move to cell (i+1, j-1) , (i+1, j) or (i+1, j+1).\n# \n# When any robot is passing through a cell, It picks it up all cherries, and the cell becomes an empty cell (0).\n# \n# When both robots stay on the same cell, only one of them takes the cherries.\n# \n# Both robots cannot move outside of the grid at any moment.\n# \n# Both robots should reach the bottom row in the `grid`.\n# \n# \n# Example 1:\n# Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]\n# Output: 24\n# Explanation: Path of robot #1 and #2 are described in color green and blue respectively.\n# \n# Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.\n# \n# Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.\n# \n# Total of cherries: 12 + 12 = 24.\n# \n# \n# Example 2:\n# Input: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]\n# Output: 28\n# Explanation: Path of robot #1 and #2 are described in color green and blue respectively.\n# \n# Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.\n# \n# Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.\n# \n# Total of cherries: 17 + 11 = 28.\n# \n# \n# Example 3:\n# Input: grid = [[1,0,0,3],[0,0,0,3],[0,0,3,3],[9,0,3,3]]\n# Output: 22\n# \n# Example 4:\n# Input: grid = [[1,1],[1,1]]\n# Output: 4\n# \n# Constraints:\n# `rows == grid.length`\n# `cols == grid[i].length`\n# `2 <= rows, cols <= 70`\n# `0 <= grid[i][j] <= 100 `\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n ", "entry_point": "cherryPickup", "cannonical_solution": "", "test": ""}
{"task_id": "probability-of-a-two-boxes-having-the-same-number-of-distinct-balls", "prompt": "# Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`. \n# All the balls will be shuffled uniformly at random, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please read the explanation of the second example carefully).\n# \n# Please note that the two boxes are considered different. For example, if we have two balls of colors `a` and `b`, and two boxes `[]` and `()`, then the distribution `[a] (b)` is considered different than the distribution `[b] (a) `(Please read the explanation of the first example carefully).\n# \n# We want to calculate the probability that the two boxes have the same number of distinct balls.\n# \n# \n# Example 1:\n# Input: balls = [1,1]\n# Output: 1.00000\n# Explanation: Only 2 ways to divide the balls equally:\n# - A ball of color 1 to box 1 and a ball of color 2 to box 2\n# - A ball of color 2 to box 1 and a ball of color 1 to box 2\n# In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1\n# \n# Example 2:\n# Input: balls = [2,1,1]\n# Output: 0.66667\n# Explanation: We have the set of balls [1, 1, 2, 3]\n# This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equale probability (i.e. 1/12):\n# [1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]\n# After that we add the first two balls to the first box and the second two balls to the second box.\n# \n# We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.\n# \n# Probability is 8/12 = 0.66667\n# \n# Example 3:\n# Input: balls = [1,2,1,2]\n# Output: 0.60000\n# Explanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.\n# \n# Probability = 108 / 180 = 0.6\n# \n# Example 4:\n# Input: balls = [3,2,1]\n# Output: 0.30000\n# Explanation: The set of balls is [1, 1, 1, 2, 2, 3]. It is hard to display all the 60 possible random shuffles of this set but it is easy to check that 18 of them will have the same number of distinct colors in each box.\n# \n# Probability = 18 / 60 = 0.3\n# \n# Example 5:\n# Input: balls = [6,6,6,6,6,6]\n# Output: 0.90327\n# \n# Constraints:\n# `1 <= balls.length <= 8`\n# `1 <= balls[i] <= 6`\n# `sum(balls)` is even.\n# \n# Answers within `10^-5` of the actual value will be accepted as correct.\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n ", "entry_point": "getProbability", "cannonical_solution": "", "test": ""}
{"task_id": "paint-house-iii", "prompt": "# There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again.\n# \n# A neighborhood is a maximal group of continuous houses that are painted with the same color.\n# \n# For example: `houses = [1,2,2,3,3,2,1,1]` contains `5` neighborhoods `[{1}, {2,2}, {3,3}, {2}, {1,1}]`.\n# \n# Given an array `houses`, an `m x n` matrix `cost` and an integer `target` where:\n# `houses[i]`: is the color of the house `i`, and `0` if the house is not painted yet.\n# \n# `cost[i][j]`: is the cost of paint the house `i` with the color `j + 1`.\n# \n# Return the minimum cost of painting all the remaining houses in such a way that there are exactly `target` neighborhoods. If it is not possible, return `-1`.\n# \n# \n# Example 1:\n# Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\n# Output: 9\n# Explanation: Paint houses of this way [1,2,2,1,1]\n# This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].\n# \n# Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.\n# \n# \n# Example 2:\n# Input: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\n# Output: 11\n# Explanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2]\n# This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. \n# Cost of paint the first and last house (10 + 1) = 11.\n# \n# \n# Example 3:\n# Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[1,10],[10,1],[1,10]], m = 5, n = 2, target = 5\n# Output: 5\n# \n# Example 4:\n# Input: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3\n# Output: -1\n# Explanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.\n# \n# \n# Constraints:\n# `m == houses.length == cost.length`\n# `n == cost[i].length`\n# `1 <= m <= 100`\n# `1 <= n <= 20`\n# `1 <= target <= m`\n# `0 <= houses[i] <= n`\n# `1 <= cost[i][j] <= 10^4`\nclass Solution:\n def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:\n ", "entry_point": "minCost", "cannonical_solution": "", "test": ""}
{"task_id": "allocate-mailboxes", "prompt": "# Given the array `houses` and an integer `k`. where `houses[i]` is the location of the ith house along a street, your task is to allocate `k` mailboxes in the street.\n# \n# Return the minimum total distance between each house and its nearest mailbox.\n# \n# The answer is guaranteed to fit in a 32-bit signed integer.\n# \n# \n# Example 1:\n# Input: houses = [1,4,8,10,20], k = 3\n# Output: 5\n# Explanation: Allocate mailboxes in position 3, 9 and 20.\n# \n# Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 \n# \n# Example 2:\n# Input: houses = [2,3,5,12,18], k = 2\n# Output: 9\n# Explanation: Allocate mailboxes in position 3 and 14.\n# \n# Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.\n# \n# \n# Example 3:\n# Input: houses = [7,4,6,1], k = 1\n# Output: 8\n# \n# Example 4:\n# Input: houses = [3,6,14,10], k = 4\n# Output: 0\n# \n# Constraints:\n# `n == houses.length`\n# `1 <= n <= 100`\n# `1 <= houses[i] <= 10^4`\n# `1 <= k <= n`\n# Array `houses` contain unique integers.\nclass Solution:\n def minDistance(self, houses: List[int], k: int) -> int:\n ", "entry_point": "minDistance", "cannonical_solution": "", "test": ""}
{"task_id": "kth-ancestor-of-a-tree-node", "prompt": "# You are given a tree with `n` nodes numbered from `0` to `n-1` in the form of a parent array where `parent[i]` is the parent of node `i`. The root of the tree is node `0`.\n# \n# Implement the function `getKthAncestor``(int node, int k)` to return the `k`-th ancestor of the given `node`. If there is no such ancestor, return `-1`.\n# \n# The k-th ancestor of a tree node is the `k`-th node in the path from that node to the root.\n# \n# \n# Example:\n# Input:\n# [\"TreeAncestor\",\"getKthAncestor\",\"getKthAncestor\",\"getKthAncestor\"]\n# [[7,[-1,0,0,1,1,2,2]],[3,1],[5,2],[6,3]]\n# Output:\n# [null,1,0,-1]\n# Explanation:\n# TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);\n# treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3\n# treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5\n# treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor\n# \n# Constraints:\n# `1 <= k <= n <= 5*10^4`\n# `parent[0] == -1` indicating that `0` is the root node.\n# \n# `0 <= parent[i] < n` for all `0 < i < n`\n# `0 <= node < n`\n# There will be at most `5*10^4` queries.\nclass TreeAncestor:\n\n def __init__(self, n: int, parent: List[int]):\n \n\n def getKthAncestor(self, node: int, k: int) -> int:\n \n\n\n# Your TreeAncestor object will be instantiated and called as such:\n# obj = TreeAncestor(n, parent)\n# param_1 = obj.getKthAncestor(node,k)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree", "prompt": "# Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.\n# \n# Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.\n# \n# Note that you can return the indices of the edges in any order.\n# \n# \n# Example 1:\n# Input: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]\n# Output: [[0,1],[2,3,4,5]]\n# Explanation: The figure above describes the graph.\n# \n# The following figure shows all the possible MSTs:\n# Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.\n# \n# The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.\n# \n# \n# Example 2:\n# Input: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]\n# Output: [[],[0,1,2,3]]\n# Explanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.\n# \n# \n# Constraints:\n# `2 <= n <= 100`\n# `1 <= edges.length <= min(200, n * (n - 1) / 2)`\n# `edges[i].length == 3`\n# `0 <= ai < bi < n`\n# `1 <= weighti <= 1000`\n# All pairs `(ai, bi)` are distinct.\nclass Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n ", "entry_point": "findCriticalAndPseudoCriticalEdges", "cannonical_solution": "", "test": ""}
{"task_id": "parallel-courses-ii", "prompt": "# Given the integer `n` representing the number of courses at some university labeled from `1` to `n`, and the array `dependencies` where `dependencies[i] = [xi, yi]` represents a prerequisite relationship, that is, the course `xi` must be taken before the course `yi`. Also, you are given the integer `k`.\n# \n# In one semester you can take at most `k` courses as long as you have taken all the prerequisites for the courses you are taking.\n# \n# Return the minimum number of semesters to take all courses. It is guaranteed that you can take all courses in some way.\n# \n# \n# Example 1:\n# Input: n = 4, dependencies = [[2,1],[3,1],[1,4]], k = 2\n# Output: 3 \n# Explanation: The figure above represents the given graph. In this case we can take courses 2 and 3 in the first semester, then take course 1 in the second semester and finally take course 4 in the third semester.\n# \n# \n# Example 2:\n# Input: n = 5, dependencies = [[2,1],[3,1],[4,1],[1,5]], k = 2\n# Output: 4 \n# Explanation: The figure above represents the given graph. In this case one optimal way to take all courses is: take courses 2 and 3 in the first semester and take course 4 in the second semester, then take course 1 in the third semester and finally take course 5 in the fourth semester.\n# \n# \n# Example 3:\n# Input: n = 11, dependencies = [], k = 2\n# Output: 6\n# \n# Constraints:\n# `1 <= n <= 15`\n# `1 <= k <= n`\n# `0 <= dependencies.length <= n * (n-1) / 2`\n# `dependencies[i].length == 2`\n# `1 <= xi, yi <= n`\n# `xi != yi`\n# All prerequisite relationships are distinct, that is, `dependencies[i] != dependencies[j]`.\n# \n# The given graph is a directed acyclic graph.\nclass Solution:\n def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int:\n ", "entry_point": "minNumberOfSemesters", "cannonical_solution": "", "test": ""}
{"task_id": "max-value-of-equation", "prompt": "# Given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.\n# \n# Find the maximum value of the equation `yi + yj + |xi - xj|` where `|xi - xj| <= k` and `1 <= i < j <= points.length`. It is guaranteed that there exists at least one pair of points that satisfy the constraint `|xi - xj| <= k`.\n# \n# \n# Example 1:\n# Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1\n# Output: 4\n# Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.\n# \n# No other pairs satisfy the condition, so we return the max of 4 and 1.\n# \n# \n# Example 2:\n# Input: points = [[0,0],[3,0],[9,2]], k = 3\n# Output: 3\n# Explanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.\n# \n# \n# Constraints:\n# `2 <= points.length <= 10^5`\n# `points[i].length == 2`\n# `-10^8 <= points[i][0], points[i][1] <= 10^8`\n# `0 <= k <= 2 * 10^8`\n# `points[i][0] < points[j][0]` for all `1 <= i < j <= points.length`\n# `xi` form a strictly increasing sequence.\nclass Solution:\n def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int:\n ", "entry_point": "findMaxValueOfEquation", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits", "prompt": "# Given a string `num` representing the digits of a very large integer and an integer `k`.\n# \n# You are allowed to swap any two adjacent digits of the integer at most `k` times.\n# \n# Return the minimum integer you can obtain also as a string.\n# \n# \n# Example 1:\n# Input: num = \"4321\", k = 4\n# Output: \"1342\"\n# Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.\n# \n# \n# Example 2:\n# Input: num = \"100\", k = 1\n# Output: \"010\"\n# Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.\n# \n# \n# Example 3:\n# Input: num = \"36789\", k = 1000\n# Output: \"36789\"\n# Explanation: We can keep the number without any swaps.\n# \n# \n# Example 4:\n# Input: num = \"22\", k = 22\n# Output: \"22\"\n# \n# Example 5:\n# Input: num = \"9438957234785635408\", k = 23\n# Output: \"0345989723478563548\"\n# \n# Constraints:\n# `1 <= num.length <= 30000`\n# `num` contains digits only and doesn't have leading zeros.\n# \n# `1 <= k <= 10^9`\nclass Solution:\n def minInteger(self, num: str, k: int) -> str:\n ", "entry_point": "minInteger", "cannonical_solution": "", "test": ""}
{"task_id": "stone-game-iv", "prompt": "# Alice and Bob take turns playing a game, with Alice starting first.\n# \n# Initially, there are `n` stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.\n# \n# Also, if a player cannot make a move, he/she loses the game.\n# \n# Given a positive integer `n`. Return `True` if and only if Alice wins the game otherwise return `False`, assuming both players play optimally.\n# \n# \n# Example 1:\n# Input: n = 1\n# Output: true\n# Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.\n# \n# \n# Example 2:\n# Input: n = 2\n# Output: false\n# Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).\n# \n# \n# Example 3:\n# Input: n = 4\n# Output: true\n# Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).\n# \n# \n# Example 4:\n# Input: n = 7\n# Output: false\n# Explanation: Alice can't win the game if Bob plays optimally.\n# \n# If Alice starts removing 4 stones, Bob will remove 1 stone then Alice should remove only 1 stone and finally Bob removes the last one (7 -> 3 -> 2 -> 1 -> 0). \n# If Alice starts removing 1 stone, Bob will remove 4 stones then Alice only can remove 1 stone and finally Bob removes the last one (7 -> 6 -> 2 -> 1 -> 0).\n# \n# \n# Example 5:\n# Input: n = 17\n# Output: false\n# Explanation: Alice can't win the game if Bob plays optimally.\n# \n# \n# Constraints:\n# `1 <= n <= 10^5`\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n ", "entry_point": "winnerSquareGame", "cannonical_solution": "", "test": ""}
{"task_id": "best-position-for-a-service-centre", "prompt": "# A delivery company wants to build a new service centre in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new centre in a position such that the sum of the euclidean distances to all customers is minimum.\n# \n# Given an array `positions` where `positions[i] = [xi, yi]` is the position of the `ith` customer on the map, return the minimum sum of the euclidean distances to all customers.\n# \n# In other words, you need to choose the position of the service centre `[xcentre, ycentre]` such that the following formula is minimized:\n# Answers within `10^-5` of the actual value will be accepted.\n# \n# \n# Example 1:\n# Input: positions = [[0,1],[1,0],[1,2],[2,1]]\n# Output: 4.00000\n# Explanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.\n# \n# \n# Example 2:\n# Input: positions = [[1,1],[3,3]]\n# Output: 2.82843\n# Explanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843\n# \n# Example 3:\n# Input: positions = [[1,1]]\n# Output: 0.00000\n# \n# Example 4:\n# Input: positions = [[1,1],[0,0],[2,0]]\n# Output: 2.73205\n# Explanation: At the first glance, you may think that locating the centre at [1, 0] will achieve the minimum sum, but locating it at [1, 0] will make the sum of distances = 3.\n# \n# Try to locate the centre at [1.0, 0.5773502711] you will see that the sum of distances is 2.73205.\n# \n# Be careful with the precision!\n# \n# Example 5:\n# Input: positions = [[0,1],[3,2],[4,5],[7,6],[8,9],[11,1],[2,12]]\n# Output: 32.94036\n# Explanation: You can use [4.3460852395, 4.9813795505] as the position of the centre.\n# \n# \n# Constraints:\n# `1 <= positions.length <= 50`\n# `positions[i].length == 2`\n# `0 <= positions[i][0], positions[i][1] <= 100`\nclass Solution:\n def getMinDistSum(self, positions: List[List[int]]) -> float:\n ", "entry_point": "getMinDistSum", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-number-of-non-overlapping-substrings", "prompt": "# Given a string `s` of lowercase letters, you need to find the maximum number of non-empty substrings of `s` that meet the following conditions:\n# The substrings do not overlap, that is for any two substrings `s[i..j]` and `s[k..l]`, either `j < k` or `i > l` is true.\n# \n# A substring that contains a certain character `c` must also contain all occurrences of `c`.\n# \n# Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length.\n# \n# Notice that you can return the substrings in any order.\n# \n# \n# Example 1:\n# Input: s = \"adefaddaccc\"\n# Output: [\"e\",\"f\",\"ccc\"]\n# Explanation: The following are all the possible substrings that meet the conditions:\n# [\n# \"adefaddaccc\"\n# \"adefadda\",\n# \"ef\",\n# \"e\",\n# \"f\",\n# \"ccc\",\n# ]\n# If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose \"adefadda\", we are left with \"ccc\" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose \"ef\" since it can be split into two. Therefore, the optimal way is to choose [\"e\",\"f\",\"ccc\"] which gives us 3 substrings. No other solution of the same number of substrings exist.\n# \n# \n# Example 2:\n# Input: s = \"abbaccd\"\n# Output: [\"d\",\"bb\",\"cc\"]\n# Explanation: Notice that while the set of substrings [\"d\",\"abba\",\"cc\"] also has length 3, it's considered incorrect since it has larger total length.\n# \n# \n# Constraints:\n# `1 <= s.length <= 10^5`\n# `s` contains only lowercase English letters.\nclass Solution:\n def maxNumOfSubstrings(self, s: str) -> List[str]:\n ", "entry_point": "maxNumOfSubstrings", "cannonical_solution": "", "test": ""}
{"task_id": "find-a-value-of-a-mysterious-function-closest-to-target", "prompt": "# Winston was given the above mysterious function `func`. He has an integer array `arr` and an integer `target` and he wants to find the values `l` and `r` that make the value `|func(arr, l, r) - target|` minimum possible.\n# \n# Return the minimum possible value of `|func(arr, l, r) - target|`.\n# \n# Notice that `func` should be called with the values `l` and `r` where `0 <= l, r < arr.length`.\n# \n# \n# Example 1:\n# Input: arr = [9,12,3,7,15], target = 5\n# Output: 2\n# Explanation: Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.\n# \n# \n# Example 2:\n# Input: arr = [1000000,1000000,1000000], target = 1\n# Output: 999999\n# Explanation: Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.\n# \n# \n# Example 3:\n# Input: arr = [1,2,4,8,16], target = 0\n# Output: 0\n# \n# Constraints:\n# `1 <= arr.length <= 105`\n# `1 <= arr[i] <= 106`\n# `0 <= target <= 107`\nclass Solution:\n def closestToTarget(self, arr: List[int], target: int) -> int:\n ", "entry_point": "closestToTarget", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-number-of-increments-on-subarrays-to-form-a-target-array", "prompt": "# Given an array of positive integers `target` and an array `initial` of same size with all zeros.\n# \n# Return the minimum number of operations to form a `target` array from `initial` if you are allowed to do the following operation:\n# Choose any subarray from `initial` and increment each value by one.\n# \n# The answer is guaranteed to fit within the range of a 32-bit signed integer.\n# \n# \n# Example 1:\n# Input: target = [1,2,3,2,1]\n# Output: 3\n# Explanation: We need at least 3 operations to form the target array from the initial array.\n# \n# [0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).\n# \n# [1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).\n# \n# [1,2,2,2,1] increment 1 at index 2.\n# \n# [1,2,3,2,1] target array is formed.\n# \n# \n# Example 2:\n# Input: target = [3,1,1,2]\n# Output: 4\n# Explanation: (initial)[0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2] (target).\n# \n# \n# Example 3:\n# Input: target = [3,1,5,4,2]\n# Output: 7\n# Explanation: (initial)[0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] \n# -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2] (target).\n# \n# \n# Example 4:\n# Input: target = [1,1,1,1]\n# Output: 1\n# \n# Constraints:\n# `1 <= target.length <= 10^5`\n# `1 <= target[i] <= 10^5`\nclass Solution:\n def minNumberOperations(self, target: List[int]) -> int:\n ", "entry_point": "minNumberOperations", "cannonical_solution": "", "test": ""}
{"task_id": "string-compression-ii", "prompt": "# Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string `\"aabccc\"` we replace `\"aa\"` by `\"a2\"` and replace `\"ccc\"` by `\"c3\"`. Thus the compressed string becomes `\"a2bc3\"`.\n# \n# Notice that in this problem, we are not adding `'1'` after single characters.\n# \n# Given a string `s` and an integer `k`. You need to delete at most `k` characters from `s` such that the run-length encoded version of `s` has minimum length.\n# \n# Find the minimum length of the run-length encoded version of `s` after deleting at most `k` characters.\n# \n# \n# Example 1:\n# Input: s = \"aaabcccd\", k = 2\n# Output: 4\n# Explanation: Compressing s without deleting anything will give us \"a3bc3d\" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = \"abcccd\" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be \"a3c3\" of length 4.\n# \n# \n# Example 2:\n# Input: s = \"aabbaa\", k = 2\n# Output: 2\n# Explanation: If we delete both 'b' characters, the resulting compressed string would be \"a4\" of length 2.\n# \n# \n# Example 3:\n# Input: s = \"aaaaaaaaaaa\", k = 0\n# Output: 3\n# Explanation: Since k is zero, we cannot delete anything. The compressed string is \"a11\" of length 3.\n# \n# \n# Constraints:\n# `1 <= s.length <= 100`\n# `0 <= k <= s.length`\n# `s` contains only lowercase English letters.\nclass Solution:\n def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n ", "entry_point": "getLengthOfOptimalCompression", "cannonical_solution": "", "test": ""}
{"task_id": "get-the-maximum-score", "prompt": "# You are given two sorted arrays of distinct integers `nums1` and `nums2.`\n# A valid path is defined as follows:\n# Choose array nums1 or nums2 to traverse (from index-0).\n# \n# Traverse the current array from left to right.\n# \n# If you are reading any value that is present in `nums1` and `nums2` you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).\n# \n# Score is defined as the sum of uniques values in a valid path.\n# \n# Return the maximum score you can obtain of all possible valid paths.\n# \n# Since the answer may be too large, return it modulo 10^9 + 7.\n# \n# \n# Example 1:\n# Input: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]\n# Output: 30\n# Explanation: Valid paths:\n# [2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)\n# [4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)\n# The maximum is obtained with the path in green [2,4,6,8,10].\n# \n# \n# Example 2:\n# Input: nums1 = [1,3,5,7,9], nums2 = [3,5,100]\n# Output: 109\n# Explanation: Maximum sum is obtained with the path [1,3,5,100].\n# \n# \n# Example 3:\n# Input: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]\n# Output: 40\n# Explanation: There are no common elements between nums1 and nums2.\n# \n# Maximum sum is obtained with the path [6,7,8,9,10].\n# \n# \n# Example 4:\n# Input: nums1 = [1,4,5,8,9,11,19], nums2 = [2,3,4,11,12]\n# Output: 61\n# \n# Constraints:\n# `1 <= nums1.length <= 10^5`\n# `1 <= nums2.length <= 10^5`\n# `1 <= nums1[i], nums2[i] <= 10^7`\n# `nums1` and `nums2` are strictly increasing.\nclass Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n ", "entry_point": "maxSum", "cannonical_solution": "", "test": ""}
{"task_id": "find-longest-awesome-substring", "prompt": "# Given a string `s`. An awesome substring is a non-empty substring of `s` such that we can make any number of swaps in order to make it palindrome.\n# \n# Return the length of the maximum length awesome substring of `s`.\n# \n# \n# Example 1:\n# Input: s = \"3242415\"\n# Output: 5\n# Explanation: \"24241\" is the longest awesome substring, we can form the palindrome \"24142\" with some swaps.\n# \n# \n# Example 2:\n# Input: s = \"12345678\"\n# Output: 1\n# \n# Example 3:\n# Input: s = \"213123\"\n# Output: 6\n# Explanation: \"213123\" is the longest awesome substring, we can form the palindrome \"231132\" with some swaps.\n# \n# \n# Example 4:\n# Input: s = \"00\"\n# Output: 2\n# \n# Constraints:\n# `1 <= s.length <= 10^5`\n# `s` consists only of digits.\nclass Solution:\n def longestAwesome(self, s: str) -> int:\n ", "entry_point": "longestAwesome", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-cost-to-cut-a-stick", "prompt": "# Given a wooden stick of length `n` units. The stick is labelled from `0` to `n`. For example, a stick of length 6 is labelled as follows:\n# Given an integer array `cuts` where `cuts[i]` denotes a position you should perform a cut at.\n# \n# You should perform the cuts in order, you can change the order of the cuts as you wish.\n# \n# The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.\n# \n# Return the minimum total cost of the cuts.\n# \n# \n# Example 1:\n# Input: n = 7, cuts = [1,3,4,5]\n# Output: 16\n# Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:\n# The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.\n# \n# Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).\n# \n# \n# Example 2:\n# Input: n = 9, cuts = [5,6,1,4,2]\n# Output: 22\n# Explanation: If you try the given cuts ordering the cost will be 25.\n# \n# There are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.\n# \n# \n# Constraints:\n# `2 <= n <= 10^6`\n# `1 <= cuts.length <= min(n - 1, 100)`\n# `1 <= cuts[i] <= n - 1`\n# All the integers in `cuts` array are distinct.\nclass Solution:\n def minCost(self, n: int, cuts: List[int]) -> int:\n ", "entry_point": "minCost", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-number-of-days-to-eat-n-oranges", "prompt": "# There are `n` oranges in the kitchen and you decided to eat some of these oranges every day as follows:\n# Eat one orange.\n# \n# If the number of remaining oranges (`n`) is divisible by 2 then you can eat n/2 oranges.\n# \n# If the number of remaining oranges (`n`) is divisible by 3 then you can eat 2*(n/3) oranges.\n# \n# You can only choose one of the actions per day.\n# \n# Return the minimum number of days to eat `n` oranges.\n# \n# \n# Example 1:\n# Input: n = 10\n# Output: 4\n# Explanation: You have 10 oranges.\n# \n# Day 1: Eat 1 orange, 10 - 1 = 9. \n# Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)\n# Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. \n# Day 4: Eat the last orange 1 - 1 = 0.\n# \n# You need at least 4 days to eat the 10 oranges.\n# \n# \n# Example 2:\n# Input: n = 6\n# Output: 3\n# Explanation: You have 6 oranges.\n# \n# Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).\n# \n# Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)\n# Day 3: Eat the last orange 1 - 1 = 0.\n# \n# You need at least 3 days to eat the 6 oranges.\n# \n# \n# Example 3:\n# Input: n = 1\n# Output: 1\n# \n# Example 4:\n# Input: n = 56\n# Output: 6\n# \n# Constraints:\n# `1 <= n <= 2*10^9`\nclass Solution:\n def minDays(self, n: int) -> int:\n ", "entry_point": "minDays", "cannonical_solution": "", "test": ""}
{"task_id": "detect-cycles-in-2d-grid", "prompt": "# Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the same value in `grid`.\n# \n# A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.\n# \n# Also, you cannot move to the cell that you visited in your last move. For example, the cycle `(1, 1) -> (1, 2) -> (1, 1)` is invalid because from `(1, 2)` we visited `(1, 1)` which was the last visited cell.\n# \n# Return `true` if any cycle of the same value exists in `grid`, otherwise, return `false`.\n# \n# \n# Example 1:\n# Input: grid = [[\"a\",\"a\",\"a\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"a\",\"a\",\"a\"]]\n# Output: true\n# Explanation: There are two valid cycles shown in different colors in the image below:\n# \n# Example 2:\n# Input: grid = [[\"c\",\"c\",\"c\",\"a\"],[\"c\",\"d\",\"c\",\"c\"],[\"c\",\"c\",\"e\",\"c\"],[\"f\",\"c\",\"c\",\"c\"]]\n# Output: true\n# Explanation: There is only one valid cycle highlighted in the image below:\n# \n# Example 3:\n# Input: grid = [[\"a\",\"b\",\"b\"],[\"b\",\"z\",\"b\"],[\"b\",\"b\",\"a\"]]\n# Output: false\n# \n# Constraints:\n# `m == grid.length`\n# `n == grid[i].length`\n# `1 <= m <= 500`\n# `1 <= n <= 500`\n# `grid` consists only of lowercase English letters.\nclass Solution:\n def containsCycle(self, grid: List[List[str]]) -> bool:\n ", "entry_point": "containsCycle", "cannonical_solution": "", "test": ""}
{"task_id": "stone-game-v", "prompt": "# There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array `stoneValue`.\n# \n# In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.\n# \n# The game ends when there is only one stone remaining. Alice's is initially zero.\n# \n# Return the maximum score that Alice can obtain.\n# \n# \n# Example 1:\n# Input: stoneValue = [6,2,3,4,5,5]\n# Output: 18\n# Explanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.\n# \n# In the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).\n# \n# The last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.\n# \n# \n# Example 2:\n# Input: stoneValue = [7,7,7,7,7,7,7]\n# Output: 28\n# \n# Example 3:\n# Input: stoneValue = [4]\n# Output: 0\n# \n# Constraints:\n# `1 <= stoneValue.length <= 500`\n# `1 <= stoneValue[i] <= 10^6`\nclass Solution:\n def stoneGameV(self, stoneValue: List[int]) -> int:\n ", "entry_point": "stoneGameV", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-number-of-days-to-disconnect-island", "prompt": "# Given a 2D `grid` consisting of `1`s (land) and `0`s (water). An island is a maximal 4-directionally (horizontal or vertical) connected group of `1`s.\n# \n# The grid is said to be connected if we have exactly one island, otherwise is said disconnected.\n# \n# In one day, we are allowed to change any single land cell `(1)` into a water cell `(0)`.\n# \n# Return the minimum number of days to disconnect the grid.\n# \n# \n# Example 1:\n# Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]\n# Output: 2\n# Explanation: We need at least 2 days to get a disconnected grid.\n# \n# Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island.\n# \n# \n# Example 2:\n# Input: grid = [[1,1]]\n# Output: 2\n# Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.\n# \n# \n# Example 3:\n# Input: grid = [[1,0,1,0]]\n# Output: 0\n# \n# Example 4:\n# Input: grid = [[1,1,0,1,1],\n# [1,1,1,1,1],\n# [1,1,0,1,1],\n# [1,1,0,1,1]]\n# Output: 1\n# \n# Example 5:\n# Input: grid = [[1,1,0,1,1],\n# [1,1,1,1,1],\n# [1,1,0,1,1],\n# [1,1,1,1,1]]\n# Output: 2\n# \n# Constraints:\n# `1 <= grid.length, grid[i].length <= 30`\n# `grid[i][j]` is `0` or `1`.\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n ", "entry_point": "minDays", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-ways-to-reorder-array-to-get-same-bst", "prompt": "# Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from the original array `nums`.\n# \n# For example, given `nums = [2,1,3]`, we will have 2 as the root, 1 as a left child, and 3 as a right child. The array `[2,3,1]` also yields the same BST but `[3,2,1]` yields a different BST.\n# \n# Return the number of ways to reorder `nums` such that the BST formed is identical to the original BST formed from `nums`.\n# \n# Since the answer may be very large, return it modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: nums = [2,1,3]\n# Output: 1\n# Explanation: We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.\n# \n# \n# Example 2:\n# Input: nums = [3,4,5,1,2]\n# Output: 5\n# Explanation: The following 5 arrays will yield the same BST: \n# [3,1,2,4,5]\n# [3,1,4,2,5]\n# [3,1,4,5,2]\n# [3,4,1,2,5]\n# [3,4,1,5,2]\n# \n# Example 3:\n# Input: nums = [1,2,3]\n# Output: 0\n# Explanation: There are no other orderings of nums that will yield the same BST.\n# \n# \n# Example 4:\n# Input: nums = [3,1,2,5,4,6]\n# Output: 19\n# \n# Example 5:\n# Input: nums = [9,4,2,1,3,6,5,7,8,14,11,10,12,13,16,15,17,18]\n# Output: 216212978\n# Explanation: The number of ways to reorder nums to get the same BST is 3216212999. Taking this number modulo 10^9 + 7 gives 216212978.\n# \n# \n# Constraints:\n# `1 <= nums.length <= 1000`\n# `1 <= nums[i] <= nums.length`\n# All integers in `nums` are distinct.\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n ", "entry_point": "numOfWays", "cannonical_solution": "", "test": ""}
{"task_id": "count-all-possible-routes", "prompt": "# You are given an array of distinct positive integers locations where `locations[i]` represents the position of city `i`. You are also given integers `start`, `finish` and `fuel` representing the starting city, ending city, and the initial amount of fuel you have, respectively.\n# \n# At each step, if you are at city `i`, you can pick any city `j` such that `j != i` and `0 <= j < locations.length` and move to city `j`. Moving from city `i` to city `j` reduces the amount of fuel you have by `|locations[i] - locations[j]|`. Please notice that `|x|` denotes the absolute value of `x`.\n# \n# Notice that `fuel` cannot become negative at any point in time, and that you are allowed to visit any city more than once (including `start` and `finish`).\n# \n# Return the count of all possible routes from `start` to `finish`.\n# \n# Since the answer may be too large, return it modulo `10^9 + 7`.\n# \n# \n# Example 1:\n# Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5\n# Output: 4\n# Explanation: The following are all possible routes, each uses 5 units of fuel:\n# 1 -> 3\n# 1 -> 2 -> 3\n# 1 -> 4 -> 3\n# 1 -> 4 -> 2 -> 3\n# \n# Example 2:\n# Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6\n# Output: 5\n# Explanation: The following are all possible routes:\n# 1 -> 0, used fuel = 1\n# 1 -> 2 -> 0, used fuel = 5\n# 1 -> 2 -> 1 -> 0, used fuel = 5\n# 1 -> 0 -> 1 -> 0, used fuel = 3\n# 1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5\n# \n# Example 3:\n# Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3\n# Output: 0\n# Explanation: It's impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.\n# \n# \n# Example 4:\n# Input: locations = [2,1,5], start = 0, finish = 0, fuel = 3\n# Output: 2\n# Explanation: There are two possible routes, 0 and 0 -> 1 -> 0.\n# \n# \n# Example 5:\n# Input: locations = [1,2,3], start = 0, finish = 2, fuel = 40\n# Output: 615088286\n# Explanation: The total number of possible routes is 2615088300. Taking this number modulo 10^9 + 7 gives us 615088286.\n# \n# \n# Constraints:\n# `2 <= locations.length <= 100`\n# `1 <= locations[i] <= 10^9`\n# All integers in `locations` are distinct.\n# \n# `0 <= start, finish < locations.length`\n# `1 <= fuel <= 200`\nclass Solution:\n def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:\n ", "entry_point": "countRoutes", "cannonical_solution": "", "test": ""}
{"task_id": "remove-max-number-of-edges-to-keep-graph-fully-traversable", "prompt": "# Alice and Bob have an undirected graph of `n` nodes and 3 types of edges:\n# Type 1: Can be traversed by Alice only.\n# \n# Type 2: Can be traversed by Bob only.\n# \n# Type 3: Can by traversed by both Alice and Bob.\n# \n# Given an array `edges` where `edges[i] = [typei, ui, vi]` represents a bidirectional edge of type `typei` between nodes `ui` and `vi`, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.\n# \n# Return the maximum number of edges you can remove, or return `-1` if it's impossible for the graph to be fully traversed by Alice and Bob.\n# \n# \n# Example 1:\n# Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]\n# Output: 2\n# Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.\n# \n# \n# Example 2:\n# Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]\n# Output: 0\n# Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.\n# \n# \n# Example 3:\n# Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]\n# Output: -1\n# Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.\n# \n# \n# Constraints:\n# `1 <= n <= 10^5`\n# `1 <= edges.length <= min(10^5, 3 * n * (n-1) / 2)`\n# `edges[i].length == 3`\n# `1 <= edges[i][0] <= 3`\n# `1 <= edges[i][1] < edges[i][2] <= n`\n# All tuples `(typei, ui, vi)` are distinct.\nclass Solution:\n def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n ", "entry_point": "maxNumEdgesToRemove", "cannonical_solution": "", "test": ""}
{"task_id": "check-if-string-is-transformable-with-substring-sort-operations", "prompt": "# Given two strings `s` and `t`, you want to transform string `s` into string `t` using the following operation any number of times:\n# Choose a non-empty substring in `s` and sort it in-place so the characters are in ascending order.\n# \n# For example, applying the operation on the underlined substring in `\"14234\"` results in `\"12344\"`.\n# \n# Return `true` if it is possible to transform string `s` into string `t`. Otherwise, return `false`.\n# \n# A substring is a contiguous sequence of characters within a string.\n# \n# \n# Example 1:\n# Input: s = \"84532\", t = \"34852\"\n# Output: true\n# Explanation: You can transform s into t using the following sort operations:\n# \"84532\" (from index 2 to 3) -> \"84352\"\n# \"84352\" (from index 0 to 2) -> \"34852\"\n# \n# Example 2:\n# Input: s = \"34521\", t = \"23415\"\n# Output: true\n# Explanation: You can transform s into t using the following sort operations:\n# \"34521\" -> \"23451\"\n# \"23451\" -> \"23415\"\n# \n# Example 3:\n# Input: s = \"12345\", t = \"12435\"\n# Output: false\n# \n# Example 4:\n# Input: s = \"1\", t = \"2\"\n# Output: false\n# \n# Constraints:\n# `s.length == t.length`\n# `1 <= s.length <= 105`\n# `s` and `t` only contain digits from `'0'` to `'9'`.\nclass Solution:\n def isTransformable(self, s: str, t: str) -> bool:\n ", "entry_point": "isTransformable", "cannonical_solution": "", "test": ""}
{"task_id": "strange-printer-ii", "prompt": "# There is a strange printer with the following two special requirements:\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# \n# Once the printer has used a color for the above operation, the same color cannot be used again.\n# \n# You are given a `m x n` matrix `targetGrid`, where `targetGrid[row][col]` is the color in the position `(row, col)` of the grid.\n# \n# Return `true` if it is possible to print the matrix `targetGrid`, otherwise, return `false`.\n# \n# \n# Example 1:\n# Input: targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]\n# Output: true\n# \n# Example 2:\n# Input: targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]\n# Output: true\n# \n# Example 3:\n# Input: targetGrid = [[1,2,1],[2,1,2],[1,2,1]]\n# Output: false\n# Explanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns.\n# \n# \n# Example 4:\n# Input: targetGrid = [[1,1,1],[3,1,3]]\n# Output: false\n# \n# Constraints:\n# `m == targetGrid.length`\n# `n == targetGrid[i].length`\n# `1 <= m, n <= 60`\n# `1 <= targetGrid[row][col] <= 60`\nclass Solution:\n def isPrintable(self, targetGrid: List[List[int]]) -> bool:\n ", "entry_point": "isPrintable", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-cost-to-connect-two-groups-of-points", "prompt": "# You are given two groups of points where the first group has `size1` points, the second group has `size2` points, and `size1 >= size2`.\n# \n# The `cost` of the connection between any two points are given in an `size1 x size2` matrix where `cost[i][j]` is the cost of connecting point `i` of the first group and point `j` of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.\n# \n# Return the minimum cost it takes to connect the two groups.\n# \n# \n# Example 1:\n# Input: cost = [[15, 96], [36, 2]]\n# Output: 17\n# Explanation: The optimal way of connecting the groups is:\n# 1--A\n# 2--B\n# This results in a total cost of 17.\n# \n# \n# Example 2:\n# Input: cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]\n# Output: 4\n# Explanation: The optimal way of connecting the groups is:\n# 1--A\n# 2--B\n# 2--C\n# 3--A\n# This results in a total cost of 4.\n# \n# Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.\n# \n# \n# Example 3:\n# Input: cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]\n# Output: 10\n# \n# Constraints:\n# `size1 == cost.length`\n# `size2 == cost[i].length`\n# `1 <= size1, size2 <= 12`\n# `size1 >= size2`\n# `0 <= cost[i][j] <= 100`\nclass Solution:\n def connectTwoGroups(self, cost: List[List[int]]) -> int:\n ", "entry_point": "connectTwoGroups", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-number-of-achievable-transfer-requests", "prompt": "# We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.\n# \n# You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`.\n# \n# All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`.\n# \n# Return the maximum number of achievable requests.\n# \n# \n# Example 1:\n# Input: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]\n# Output: 5\n# Explantion: Let's see the requests:\n# From building 0 we have employees x and y and both want to move to building 1.\n# \n# From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.\n# \n# From building 2 we have employee z and they want to move to building 0.\n# \n# From building 3 we have employee c and they want to move to building 4.\n# \n# From building 4 we don't have any requests.\n# \n# We can achieve the requests of users x and b by swapping their places.\n# \n# We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.\n# \n# \n# Example 2:\n# Input: n = 3, requests = [[0,0],[1,2],[2,1]]\n# Output: 3\n# Explantion: Let's see the requests:\n# From building 0 we have employee x and they want to stay in the same building 0.\n# \n# From building 1 we have employee y and they want to move to building 2.\n# \n# From building 2 we have employee z and they want to move to building 1.\n# \n# We can achieve all the requests. \n# \n# Example 3:\n# Input: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]\n# Output: 4\n# \n# Constraints:\n# `1 <= n <= 20`\n# `1 <= requests.length <= 16`\n# `requests[i].length == 2`\n# `0 <= fromi, toi < n`\nclass Solution:\n def maximumRequests(self, n: int, requests: List[List[int]]) -> int:\n ", "entry_point": "maximumRequests", "cannonical_solution": "", "test": ""}
{"task_id": "find-servers-that-handled-most-number-of-requests", "prompt": "# You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm:\n# The `ith` (0-indexed) request arrives.\n# \n# If all servers are busy, the request is dropped (not handled at all).\n# \n# If the `(i % k)th` server is available, assign the request to that server.\n# \n# Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the `ith` server is busy, try to assign the request to the `(i+1)th` server, then the `(i+2)th` server, and so on.\n# \n# You are given a strictly increasing array `arrival` of positive integers, where `arrival[i]` represents the arrival time of the `ith` request, and another array `load`, where `load[i]` represents the load of the `ith` request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers.\n# \n# Return a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order.\n# \n# \n# Example 1:\n# Input: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] \n# Output: [1] \n# Explanation:\n# All of the servers start out available.\n# \n# The first 3 requests are handled by the first 3 servers in order.\n# \n# Request 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.\n# \n# Request 4 comes in. It cannot be handled since all servers are busy, so it is dropped.\n# \n# Servers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.\n# \n# \n# Example 2:\n# Input: k = 3, arrival = [1,2,3,4], load = [1,2,1,2]\n# Output: [0]\n# Explanation:\n# The first 3 requests are handled by first 3 servers.\n# \n# Request 3 comes in. It is handled by server 0 since the server is available.\n# \n# Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.\n# \n# \n# Example 3:\n# Input: k = 3, arrival = [1,2,3], load = [10,12,11]\n# Output: [0,1,2]\n# Explanation: Each server handles a single request, so they are all considered the busiest.\n# \n# \n# Example 4:\n# Input: k = 3, arrival = [1,2,3,4,8,9,10], load = [5,2,10,3,1,2,2]\n# Output: [1]\n# \n# Example 5:\n# Input: k = 1, arrival = [1], load = [1]\n# Output: [0]\n# \n# Constraints:\n# `1 <= k <= 105`\n# `1 <= arrival.length, load.length <= 105`\n# `arrival.length == load.length`\n# `1 <= arrival[i], load[i] <= 109`\n# `arrival` is strictly increasing.\nclass Solution:\n def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:\n ", "entry_point": "busiestServers", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-number-of-visible-points", "prompt": "# You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote integral coordinates on the X-Y plane.\n# \n# Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, `posx` and `posy` cannot be changed. Your field of view in degrees is represented by `angle`, determining how wide you can see from any given view direction. Let `d` be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles `[d - angle/2, d + angle/2]`.\n# \n# Your browser does not support the video tag or this video format.\n# \n# You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view.\n# \n# There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.\n# \n# Return the maximum number of points you can see.\n# \n# \n# Example 1:\n# Input: points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]\n# Output: 3\n# Explanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.\n# \n# \n# Example 2:\n# Input: points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]\n# Output: 4\n# Explanation: All points can be made visible in your field of view, including the one at your location.\n# \n# \n# Example 3:\n# Input: points = [[1,0],[2,1]], angle = 13, location = [1,1]\n# Output: 1\n# Explanation: You can only see one of the two points, as shown above.\n# \n# \n# Constraints:\n# `1 <= points.length <= 105`\n# `points[i].length == 2`\n# `location.length == 2`\n# `0 <= angle < 360`\n# `0 <= posx, posy, xi, yi <= 100`\nclass Solution:\n def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int:\n ", "entry_point": "visiblePoints", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-one-bit-operations-to-make-integers-zero", "prompt": "# Given an integer `n`, you must transform it into `0` using the following operations any number of times:\n# Change the rightmost (`0th`) bit in the binary representation of `n`.\n# \n# Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.\n# \n# Return the minimum number of operations to transform `n` into `0`.\n# \n# \n# Example 1:\n# Input: n = 0\n# Output: 0\n# \n# Example 2:\n# Input: n = 3\n# Output: 2\n# Explanation: The binary representation of 3 is \"11\".\n# \n# \"11\" -> \"01\" with the 2nd operation since the 0th bit is 1.\n# \n# \"01\" -> \"00\" with the 1st operation.\n# \n# \n# Example 3:\n# Input: n = 6\n# Output: 4\n# Explanation: The binary representation of 6 is \"110\".\n# \n# \"110\" -> \"010\" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.\n# \n# \"010\" -> \"011\" with the 1st operation.\n# \n# \"011\" -> \"001\" with the 2nd operation since the 0th bit is 1.\n# \n# \"001\" -> \"000\" with the 1st operation.\n# \n# \n# Example 4:\n# Input: n = 9\n# Output: 14\n# \n# Example 5:\n# Input: n = 333\n# Output: 393\n# \n# Constraints:\n# `0 <= n <= 109`\nclass Solution:\n def minimumOneBitOperations(self, n: int) -> int:\n ", "entry_point": "minimumOneBitOperations", "cannonical_solution": "", "test": ""}
{"task_id": "count-subtrees-with-max-distance-between-cities", "prompt": "# There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a tree.\n# \n# A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other.\n# \n# For each `d` from `1` to `n-1`, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to `d`.\n# \n# Return an array of size `n-1` where the `dth` element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to `d`.\n# \n# Notice that the distance between the two cities is the number of edges in the path between them.\n# \n# \n# Example 1:\n# Input: n = 4, edges = [[1,2],[2,3],[2,4]]\n# Output: [3,4,0]\n# Explanation:\n# The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.\n# \n# The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.\n# \n# No subtree has two nodes where the max distance between them is 3.\n# \n# \n# Example 2:\n# Input: n = 2, edges = [[1,2]]\n# Output: [1]\n# \n# Example 3:\n# Input: n = 3, edges = [[1,2],[2,3]]\n# Output: [2,1]\n# \n# Constraints:\n# `2 <= n <= 15`\n# `edges.length == n-1`\n# `edges[i].length == 2`\n# `1 <= ui, vi <= n`\n# All pairs `(ui, vi)` are distinct.\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n ", "entry_point": "countSubgraphsForEachDiameter", "cannonical_solution": "", "test": ""}
{"task_id": "fancy-sequence", "prompt": "# Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations.\n# \n# Implement the `Fancy` class:\n# `Fancy()` Initializes the object with an empty sequence.\n# \n# `void append(val)` Appends an integer `val` to the end of the sequence.\n# \n# `void addAll(inc)` Increments all existing values in the sequence by an integer `inc`.\n# \n# `void multAll(m)` Multiplies all existing values in the sequence by an integer `m`.\n# \n# `int getIndex(idx)` Gets the current value at index `idx` (0-indexed) of the sequence modulo `109 + 7`. If the index is greater or equal than the length of the sequence, return `-1`.\n# \n# \n# Example 1:\n# Input\n# [\"Fancy\", \"append\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"getIndex\", \"getIndex\"]\n# [[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]\n# Output\n# [null, null, null, null, null, 10, null, null, null, 26, 34, 20]\n# Explanation\n# Fancy fancy = new Fancy();\n# fancy.append(2); // fancy sequence: [2]\n# fancy.addAll(3); // fancy sequence: [2+3] -> [5]\n# fancy.append(7); // fancy sequence: [5, 7]\n# fancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14]\n# fancy.getIndex(0); // return 10\n# fancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17]\n# fancy.append(10); // fancy sequence: [13, 17, 10]\n# fancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]\n# fancy.getIndex(0); // return 26\n# fancy.getIndex(1); // return 34\n# fancy.getIndex(2); // return 20\n# \n# Constraints:\n# `1 <= val, inc, m <= 100`\n# `0 <= idx <= 105`\n# At most `105` calls total will be made to `append`, `addAll`, `multAll`, and `getIndex`.\nclass Fancy:\n\n def __init__(self):\n \n\n def append(self, val: int) -> None:\n \n\n def addAll(self, inc: int) -> None:\n \n\n def multAll(self, m: int) -> None:\n \n\n def getIndex(self, idx: int) -> int:\n \n\n\n# Your Fancy object will be instantiated and called as such:\n# obj = Fancy()\n# obj.append(val)\n# obj.addAll(inc)\n# obj.multAll(m)\n# param_4 = obj.getIndex(idx)", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "graph-connectivity-with-threshold", "prompt": "# We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor strictly greater than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an integer `z` such that all of the following are true:\n# `x % z == 0`,\n# `y % z == 0`, and\n# `z > threshold`.\n# \n# Given the two integers, `n` and `threshold`, and an array of `queries`, you must determine for each `queries[i] = [ai, bi]` if cities `ai` and `bi` are connected directly or indirectly. (i.e. there is some path between them).\n# \n# Return an array `answer`, where `answer.length == queries.length` and `answer[i]` is `true` if for the `ith` query, there is a path between `ai` and `bi`, or `answer[i]` is `false` if there is no path.\n# \n# \n# Example 1:\n# Input: n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]\n# Output: [false,false,true]\n# Explanation: The divisors for each number:\n# 1: 1\n# 2: 1, 2\n# 3: 1, 3\n# 4: 1, 2, 4\n# 5: 1, 5\n# 6: 1, 2, 3, 6\n# Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the\n# only ones directly connected. The result of each query:\n# [1,4] 1 is not connected to 4\n# [2,5] 2 is not connected to 5\n# [3,6] 3 is connected to 6 through path 3--6\n# \n# Example 2:\n# Input: n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]\n# Output: [true,true,true,true,true]\n# Explanation: The divisors for each number are the same as the previous example. However, since the threshold is 0,\n# all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.\n# \n# \n# Example 3:\n# Input: n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]\n# Output: [false,false,false,false,false]\n# Explanation: Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.\n# \n# Please notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].\n# \n# \n# Constraints:\n# `2 <= n <= 104`\n# `0 <= threshold <= n`\n# `1 <= queries.length <= 105`\n# `queries[i].length == 2`\n# `1 <= ai, bi <= cities`\n# `ai != bi`\nclass Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n ", "entry_point": "areConnected", "cannonical_solution": "", "test": ""}
{"task_id": "rank-transform-of-a-matrix", "prompt": "# Given an `m x n` `matrix`, return a new matrix `answer` where `answer[row][col]` is the rank of `matrix[row][col]`.\n# \n# The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules:\n# The rank is an integer starting from `1`.\n# \n# If two elements `p` and `q` are in the same row or column, then:\n# \t\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# \n# It is guaranteed that `answer` is unique under the given rules.\n# \n# \n# Example 1:\n# Input: matrix = [[1,2],[3,4]]\n# Output: [[1,2],[2,3]]\n# Explanation:\n# The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.\n# \n# The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.\n# \n# The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.\n# \n# The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.\n# \n# \n# Example 2:\n# Input: matrix = [[7,7],[7,7]]\n# Output: [[1,1],[1,1]]\n# \n# Example 3:\n# Input: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]\n# Output: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]\n# \n# Example 4:\n# Input: matrix = [[7,3,6],[1,4,5],[9,8,2]]\n# Output: [[5,1,4],[1,2,3],[6,3,1]]\n# \n# Constraints:\n# `m == matrix.length`\n# `n == matrix[i].length`\n# `1 <= m, n <= 500`\n# `-109 <= matrix[row][col] <= 109`\nclass Solution:\n def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]:\n ", "entry_point": "matrixRankTransform", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-ways-to-form-a-target-string-given-a-dictionary", "prompt": "# You are given a list of strings of the same length `words` and a string `target`.\n# \n# Your task is to form `target` using the given `words` under the following rules:\n# `target` should be formed from left to right.\n# \n# To form the `ith` character (0-indexed) of `target`, you can choose the `kth` character of the `jth` string in `words` if `target[i] = words[j][k]`.\n# \n# Once you use the `kth` character of the `jth` string of `words`, you can no longer use the `xth` character of any string in `words` where `x <= k`. In other words, all characters to the left of or at index `k` become unusuable for every string.\n# \n# Repeat the process until you form the string `target`.\n# \n# Notice that you can use multiple characters from the same string in `words` provided the conditions above are met.\n# \n# Return the number of ways to form `target` from `words`. Since the answer may be too large, return it modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: words = [\"acca\",\"bbbb\",\"caca\"], target = \"aba\"\n# Output: 6\n# Explanation: There are 6 ways to form target.\n# \n# \"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"caca\")\n# \"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"caca\")\n# \"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"acca\")\n# \"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n# \"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n# \"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"caca\")\n# \n# Example 2:\n# Input: words = [\"abba\",\"baab\"], target = \"bab\"\n# Output: 4\n# Explanation: There are 4 ways to form target.\n# \n# \"bab\" -> index 0 (\"baab\"), index 1 (\"baab\"), index 2 (\"abba\")\n# \"bab\" -> index 0 (\"baab\"), index 1 (\"baab\"), index 3 (\"baab\")\n# \"bab\" -> index 0 (\"baab\"), index 2 (\"baab\"), index 3 (\"baab\")\n# \"bab\" -> index 1 (\"abba\"), index 2 (\"baab\"), index 3 (\"baab\")\n# \n# Example 3:\n# Input: words = [\"abcd\"], target = \"abcd\"\n# Output: 1\n# \n# Example 4:\n# Input: words = [\"abab\",\"baba\",\"abba\",\"baab\"], target = \"abba\"\n# Output: 16\n# \n# Constraints:\n# `1 <= words.length <= 1000`\n# `1 <= words[i].length <= 1000`\n# All strings in `words` have the same length.\n# \n# `1 <= target.length <= 1000`\n# `words[i]` and `target` contain only lowercase English letters.\nclass Solution:\n def numWays(self, words: List[str], target: str) -> int:\n ", "entry_point": "numWays", "cannonical_solution": "", "test": ""}
{"task_id": "kth-smallest-instructions", "prompt": "# Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel right and down. You are going to help Bob by providing instructions for him to reach `destination`.\n# \n# The instructions are represented as a string, where each character is either:\n# `'H'`, meaning move horizontally (go right), or\n# `'V'`, meaning move vertically (go down).\n# \n# Multiple instructions will lead Bob to `destination`. For example, if `destination` is `(2, 3)`, both `\"HHHVV\"` and `\"HVHVH\"` are valid instructions.\n# \n# However, Bob is very picky. Bob has a lucky number `k`, and he wants the `kth` lexicographically smallest instructions that will lead him to `destination`. `k` is 1-indexed.\n# \n# Given an integer array `destination` and an integer `k`, return the `kth` lexicographically smallest instructions that will take Bob to `destination`.\n# \n# \n# Example 1:\n# Input: destination = [2,3], k = 1\n# Output: \"HHHVV\"\n# Explanation: All the instructions that reach (2, 3) in lexicographic order are as follows:\n# [\"HHHVV\", \"HHVHV\", \"HHVVH\", \"HVHHV\", \"HVHVH\", \"HVVHH\", \"VHHHV\", \"VHHVH\", \"VHVHH\", \"VVHHH\"].\n# \n# \n# Example 2:\n# Input: destination = [2,3], k = 2\n# Output: \"HHVHV\"\n# \n# Example 3:\n# Input: destination = [2,3], k = 3\n# Output: \"HHVVH\"\n# \n# Constraints:\n# `destination.length == 2`\n# `1 <= row, column <= 15`\n# `1 <= k <= nCr(row + column, row)`, where `nCr(a, b)` denotes `a` choose `b`\u200b\u200b\u200b\u200b\u200b.\nclass Solution:\n def kthSmallestPath(self, destination: List[int], k: int) -> str:\n ", "entry_point": "kthSmallestPath", "cannonical_solution": "", "test": ""}
{"task_id": "create-sorted-array-through-instructions", "prompt": "# Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from left to right in `instructions`, insert it into `nums`. The cost of each insertion is the minimum of the following:\n# The number of elements currently in `nums` that are strictly less than `instructions[i]`.\n# \n# The number of elements currently in `nums` that are strictly greater than `instructions[i]`.\n# \n# For example, if inserting element `3` into `nums = [1,2,3,5]`, the cost of insertion is `min(2, 1)` (elements `1` and `2` are less than `3`, element `5` is greater than `3`) and `nums` will become `[1,2,3,3,5]`.\n# \n# Return the total cost to insert all elements from `instructions` into `nums`. Since the answer may be large, return it modulo `109 + 7`\n# \n# Example 1:\n# Input: instructions = [1,5,6,2]\n# Output: 1\n# Explanation: Begin with nums = [].\n# \n# Insert 1 with cost min(0, 0) = 0, now nums = [1].\n# \n# Insert 5 with cost min(1, 0) = 0, now nums = [1,5].\n# \n# Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6].\n# \n# Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].\n# \n# The total cost is 0 + 0 + 0 + 1 = 1.\n# \n# \n# Example 2:\n# Input: instructions = [1,2,3,6,5,4]\n# Output: 3\n# Explanation: Begin with nums = [].\n# \n# Insert 1 with cost min(0, 0) = 0, now nums = [1].\n# \n# Insert 2 with cost min(1, 0) = 0, now nums = [1,2].\n# \n# Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3].\n# \n# Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].\n# \n# Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].\n# \n# Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].\n# \n# The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.\n# \n# \n# Example 3:\n# Input: instructions = [1,3,3,3,2,4,2,1,2]\n# Output: 4\n# Explanation: Begin with nums = [].\n# \n# Insert 1 with cost min(0, 0) = 0, now nums = [1].\n# \n# Insert 3 with cost min(1, 0) = 0, now nums = [1,3].\n# \n# Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3].\n# \n# Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].\n# \n# Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].\n# \n# Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].\n# \n# \u200b\u200b\u200b\u200b\u200b\u200b\u200bInsert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].\n# \n# \u200b\u200b\u200b\u200b\u200b\u200b\u200bInsert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].\n# \n# \u200b\u200b\u200b\u200b\u200b\u200b\u200bInsert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].\n# \n# The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.\n# \n# \n# Constraints:\n# `1 <= instructions.length <= 105`\n# `1 <= instructions[i] <= 105`\nclass Solution:\n def createSortedArray(self, instructions: List[int]) -> int:\n ", "entry_point": "createSortedArray", "cannonical_solution": "", "test": ""}
{"task_id": "distribute-repeating-integers", "prompt": "# You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that:\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# \n# Return `true` if it is possible to distribute `nums` according to the above conditions.\n# \n# \n# Example 1:\n# Input: nums = [1,2,3,4], quantity = [2]\n# Output: false\n# Explanation: The 0th customer cannot be given two different integers.\n# \n# \n# Example 2:\n# Input: nums = [1,2,3,3], quantity = [2]\n# Output: true\n# Explanation: The 0th customer is given [3,3]. The integers [1,2] are not used.\n# \n# \n# Example 3:\n# Input: nums = [1,1,2,2], quantity = [2,2]\n# Output: true\n# Explanation: The 0th customer is given [1,1], and the 1st customer is given [2,2].\n# \n# \n# Example 4:\n# Input: nums = [1,1,2,3], quantity = [2,2]\n# Output: false\n# Explanation: Although the 0th customer could be given [1,1], the 1st customer cannot be satisfied.\n# \n# \n# Example 5:\n# Input: nums = [1,1,1,1,1], quantity = [2,3]\n# Output: true\n# Explanation: The 0th customer is given [1,1], and the 1st customer is given [1,1,1].\n# \n# \n# Constraints:\n# `n == nums.length`\n# `1 <= n <= 105`\n# `1 <= nums[i] <= 1000`\n# `m == quantity.length`\n# `1 <= m <= 10`\n# `1 <= quantity[i] <= 105`\n# There are at most `50` unique values in `nums`.\nclass Solution:\n def canDistribute(self, nums: List[int], quantity: List[int]) -> bool:\n ", "entry_point": "canDistribute", "cannonical_solution": "", "test": ""}
{"task_id": "maximize-grid-happiness", "prompt": "# You are given four integers, `m`, `n`, `introvertsCount`, and `extrovertsCount`. You have an `m x n` grid, and there are two types of people: introverts and extroverts. There are `introvertsCount` introverts and `extrovertsCount` extroverts.\n# \n# You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid.\n# \n# The happiness of each person is calculated as follows:\n# Introverts start with `120` happiness and lose `30` happiness for each neighbor (introvert or extrovert).\n# \n# Extroverts start with `40` happiness and gain `20` happiness for each neighbor (introvert or extrovert).\n# \n# Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell.\n# \n# The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness.\n# \n# \n# Example 1:\n# Input: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2\n# Output: 240\n# Explanation: Assume the grid is 1-indexed with coordinates (row, column).\n# \n# We can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).\n# \n# - Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120\n# - Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\n# - Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\n# The grid happiness is 120 + 60 + 60 = 240.\n# \n# The above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.\n# \n# \n# Example 2:\n# Input: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1\n# Output: 260\n# Explanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).\n# \n# - Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\n# - Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80\n# - Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\n# The grid happiness is 90 + 80 + 90 = 260.\n# \n# \n# Example 3:\n# Input: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0\n# Output: 240\n# \n# Constraints:\n# `1 <= m, n <= 5`\n# `0 <= introvertsCount, extrovertsCount <= min(m * n, 6)`\nclass Solution:\n def getMaxGridHappiness(self, m: int, n: int, introvertsCount: int, extrovertsCount: int) -> int:\n ", "entry_point": "getMaxGridHappiness", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-initial-energy-to-finish-tasks", "prompt": "# You are given an array `tasks` where `tasks[i] = [actuali, minimumi]`:\n# `actuali` is the actual amount of energy you spend to finish the `ith` task.\n# \n# `minimumi` is the minimum amount of energy you require to begin the `ith` task.\n# \n# For example, if the task is `[10, 12]` and your current energy is `11`, you cannot start this task. However, if your current energy is `13`, you can complete this task, and your energy will be `3` after finishing it.\n# \n# You can finish the tasks in any order you like.\n# \n# Return the minimum initial amount of energy you will need to finish all the tasks.\n# \n# \n# Example 1:\n# Input: tasks = [[1,2],[2,4],[4,8]]\n# Output: 8\n# Explanation:\n# Starting with 8 energy, we finish the tasks in the following order:\n# - 3rd task. Now energy = 8 - 4 = 4.\n# \n# - 2nd task. Now energy = 4 - 2 = 2.\n# \n# - 1st task. Now energy = 2 - 1 = 1.\n# \n# Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.\n# \n# \n# Example 2:\n# Input: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]\n# Output: 32\n# Explanation:\n# Starting with 32 energy, we finish the tasks in the following order:\n# - 1st task. Now energy = 32 - 1 = 31.\n# \n# - 2nd task. Now energy = 31 - 2 = 29.\n# \n# - 3rd task. Now energy = 29 - 10 = 19.\n# \n# - 4th task. Now energy = 19 - 10 = 9.\n# \n# - 5th task. Now energy = 9 - 8 = 1.\n# \n# \n# Example 3:\n# Input: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]\n# Output: 27\n# Explanation:\n# Starting with 27 energy, we finish the tasks in the following order:\n# - 5th task. Now energy = 27 - 5 = 22.\n# \n# - 2nd task. Now energy = 22 - 2 = 20.\n# \n# - 3rd task. Now energy = 20 - 3 = 17.\n# \n# - 1st task. Now energy = 17 - 1 = 16.\n# \n# - 4th task. Now energy = 16 - 4 = 12.\n# \n# - 6th task. Now energy = 12 - 6 = 6.\n# \n# \n# Constraints:\n# `1 <= tasks.length <= 105`\n# `1 <= actual\u200bi <= minimumi <= 104`\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n ", "entry_point": "minimumEffort", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-number-of-removals-to-make-mountain-array", "prompt": "# You may recall that an array `arr` is a mountain array if and only if:\n# `arr.length >= 3`\n# There exists some index `i` (0-indexed) with `0 < i < arr.length - 1` such that:\n# \t\n# `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`\n# `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`\n# Given an integer array `nums`\u200b\u200b\u200b, return the minimum number of elements to remove to make `nums\u200b\u200b\u200b` a mountain array.\n# \n# \n# Example 1:\n# Input: nums = [1,3,1]\n# Output: 0\n# Explanation: The array itself is a mountain array so we do not need to remove any elements.\n# \n# \n# Example 2:\n# Input: nums = [2,1,1,5,6,2,3,1]\n# Output: 3\n# Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].\n# \n# \n# Example 3:\n# Input: nums = [4,3,2,1,1,2,3,1]\n# Output: 4\n# \n# Example 4:\n# Input: nums = [1,2,3,4,4,3,2,1]\n# Output: 1\n# \n# Constraints:\n# `3 <= nums.length <= 1000`\n# `1 <= nums[i] <= 109`\n# It is guaranteed that you can make a mountain array out of `nums`.\nclass Solution:\n def minimumMountainRemovals(self, nums: List[int]) -> int:\n ", "entry_point": "minimumMountainRemovals", "cannonical_solution": "", "test": ""}
{"task_id": "minimize-deviation-in-array", "prompt": "# You are given an array `nums` of `n` positive integers.\n# \n# You can perform two types of operations on any element of the array any number of times:\n# If the element is even, divide it by `2`.\n# \n# \t\n# For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].`\n# If the element is odd, multiply it by `2`.\n# \n# \t\n# For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].`\n# The deviation of the array is the maximum difference between any two elements in the array.\n# \n# Return the minimum deviation the array can have after performing some number of operations.\n# \n# \n# Example 1:\n# Input: nums = [1,2,3,4]\n# Output: 1\n# Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.\n# \n# \n# Example 2:\n# Input: nums = [4,1,5,20,3]\n# Output: 3\n# Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.\n# \n# \n# Example 3:\n# Input: nums = [2,10,8]\n# Output: 3\n# \n# Constraints:\n# `n == nums.length`\n# `2 <= n <= 105`\n# `1 <= nums[i] <= 109`\nclass Solution:\n def minimumDeviation(self, nums: List[int]) -> int:\n ", "entry_point": "minimumDeviation", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-incompatibility", "prompt": "# You are given an integer array `nums`\u200b\u200b\u200b and an integer `k`. You are asked to distribute this array into `k` subsets of equal size such that there are no two equal elements in the same subset.\n# \n# A subset's incompatibility is the difference between the maximum and minimum elements in that array.\n# \n# Return the minimum possible sum of incompatibilities of the `k` subsets after distributing the array optimally, or return `-1` if it is not possible.\n# \n# A subset is a group integers that appear in the array with no particular order.\n# \n# \n# Example 1:\n# Input: nums = [1,2,1,4], k = 2\n# Output: 4\n# Explanation: The optimal distribution of subsets is [1,2] and [1,4].\n# \n# The incompatibility is (2-1) + (4-1) = 4.\n# \n# Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.\n# \n# \n# Example 2:\n# Input: nums = [6,3,8,1,3,1,2,2], k = 4\n# Output: 6\n# Explanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].\n# \n# The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.\n# \n# \n# Example 3:\n# Input: nums = [5,3,3,6,3,3], k = 3\n# Output: -1\n# Explanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.\n# \n# \n# Constraints:\n# `1 <= k <= nums.length <= 16`\n# `nums.length` is divisible by `k`\n# `1 <= nums[i] <= nums.length`\nclass Solution:\n def minimumIncompatibility(self, nums: List[int], k: int) -> int:\n ", "entry_point": "minimumIncompatibility", "cannonical_solution": "", "test": ""}
{"task_id": "delivering-boxes-from-storage-to-ports", "prompt": "# You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry.\n# \n# You are given an array `boxes`, where `boxes[i] = [ports\u200b\u200bi\u200b, weighti]`, and three 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# \n# `portsCount` is the number of ports.\n# \n# `maxBoxes` and `maxWeight` are the respective box and weight limits of the ship.\n# \n# The boxes need to be delivered in the order they are given. The ship will follow these steps:\n# The ship will take some number of boxes from the `boxes` queue, not violating the `maxBoxes` and `maxWeight` constraints.\n# \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# \n# The ship then makes a return trip to storage to take more boxes from the queue.\n# \n# The ship must end at storage after all the boxes have been delivered.\n# \n# Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.\n# \n# \n# Example 1:\n# Input: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3\n# Output: 4\n# Explanation: The optimal strategy is as follows: \n# - The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.\n# \n# So the total number of trips is 4.\n# \n# Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).\n# \n# \n# Example 2:\n# Input: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6\n# Output: 6\n# Explanation: The optimal strategy is as follows: \n# - The ship takes the first box, goes to port 1, then returns to storage. 2 trips.\n# \n# - The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.\n# \n# - The ship takes the fifth box, goes to port 3, then returns to storage. 2 trips.\n# \n# So the total number of trips is 2 + 2 + 2 = 6.\n# \n# \n# Example 3:\n# Input: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7\n# Output: 6\n# Explanation: The optimal strategy is as follows:\n# - The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.\n# \n# - The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.\n# \n# - The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.\n# \n# So the total number of trips is 2 + 2 + 2 = 6.\n# \n# \n# Example 4:\n# Input: boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]], portsCount = 5, maxBoxes = 5, maxWeight = 7\n# Output: 14\n# Explanation: The optimal strategy is as follows:\n# - The ship takes the first box, goes to port 2, then storage. 2 trips.\n# \n# - The ship takes the second box, goes to port 2, then storage. 2 trips.\n# \n# - The ship takes the third and fourth boxes, goes to port 3, then storage. 2 trips.\n# \n# - The ship takes the fifth box, goes to port 3, then storage. 2 trips.\n# \n# - The ship takes the sixth and seventh boxes, goes to port 3, then port 4, then storage. 3 trips. \n# - The ship takes the eighth and ninth boxes, goes to port 1, then port 5, then storage. 3 trips.\n# \n# So the total number of trips is 2 + 2 + 2 + 2 + 3 + 3 = 14.\n# \n# \n# Constraints:\n# `1 <= boxes.length <= 105`\n# `1 <= portsCount, maxBoxes, maxWeight <= 105`\n# `1 <= ports\u200b\u200bi <= portsCount`\n# `1 <= weightsi <= maxWeight`\nclass Solution:\n def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int:\n ", "entry_point": "boxDelivering", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-height-by-stacking-cuboids", "prompt": "# Given `n` `cuboids` where the dimensions of the `ith` cuboid is `cuboids[i] = [widthi, lengthi, heighti]` (0-indexed). Choose a subset of `cuboids` and place them on each other.\n# \n# You can place cuboid `i` on cuboid `j` if `widthi <= widthj` and `lengthi <= lengthj` and `heighti <= heightj`. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid.\n# \n# Return the maximum height of the stacked `cuboids`.\n# \n# \n# Example 1:\n# Input: cuboids = [[50,45,20],[95,37,53],[45,23,12]]\n# Output: 190\n# Explanation:\n# Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.\n# \n# Cuboid 0 is placed next with the 45x20 side facing down with height 50.\n# \n# Cuboid 2 is placed next with the 23x12 side facing down with height 45.\n# \n# The total height is 95 + 50 + 45 = 190.\n# \n# \n# Example 2:\n# Input: cuboids = [[38,25,45],[76,35,3]]\n# Output: 76\n# Explanation:\n# You can't place any of the cuboids on the other.\n# \n# We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.\n# \n# \n# Example 3:\n# Input: cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]\n# Output: 102\n# Explanation:\n# After rearranging the cuboids, you can see that all cuboids have the same dimension.\n# \n# You can place the 11x7 side down on all cuboids so their heights are 17.\n# \n# The maximum height of stacked cuboids is 6 * 17 = 102.\n# \n# \n# Constraints:\n# `n == cuboids.length`\n# `1 <= n <= 100`\n# `1 <= widthi, lengthi, heighti <= 100`\nclass Solution:\n def maxHeight(self, cuboids: List[List[int]]) -> int:\n ", "entry_point": "maxHeight", "cannonical_solution": "", "test": ""}
{"task_id": "checking-existence-of-edge-length-limited-paths", "prompt": "# An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be multiple edges between two nodes.\n# \n# Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for each `queries[j]` whether there is a path between `pj` and `qj` such that each edge on the path has a distance strictly less than `limitj` .\n# \n# Return a boolean array `answer`, where `answer.length == queries.length` and the `jth` value of `answer` is `true` if there is a path for `queries[j]` is `true`, and `false` otherwise.\n# \n# \n# Example 1:\n# Input: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]\n# Output: [false,true]\n# Explanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.\n# \n# For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.\n# \n# For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.\n# \n# \n# Example 2:\n# Input: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]\n# Output: [true,false]\n# Exaplanation: The above figure shows the given graph.\n# \n# \n# Constraints:\n# `2 <= n <= 105`\n# `1 <= edgeList.length, queries.length <= 105`\n# `edgeList[i].length == 3`\n# `queries[j].length == 3`\n# `0 <= ui, vi, pj, qj <= n - 1`\n# `ui != vi`\n# `pj != qj`\n# `1 <= disi, limitj <= 109`\n# There may be multiple edges between two nodes.\nclass Solution:\n def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:\n ", "entry_point": "distanceLimitedPathsExist", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-adjacent-swaps-for-k-consecutive-ones", "prompt": "# You are given an integer array, `nums`, and an integer `k`. `nums` comprises of only `0`'s and `1`'s. In one move, you can choose two adjacent indices and swap their values.\n# \n# Return the minimum number of moves required so that `nums` has `k` consecutive `1`'s.\n# \n# \n# Example 1:\n# Input: nums = [1,0,0,1,0,1], k = 2\n# Output: 1\n# Explanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.\n# \n# \n# Example 2:\n# Input: nums = [1,0,0,0,0,0,1,1], k = 3\n# Output: 5\n# Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].\n# \n# \n# Example 3:\n# Input: nums = [1,1,0,1], k = 2\n# Output: 0\n# Explanation: nums already has 2 consecutive 1's.\n# \n# \n# Constraints:\n# `1 <= nums.length <= 105`\n# `nums[i]` is `0` or `1`.\n# \n# `1 <= k <= sum(nums)`\nclass Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n ", "entry_point": "minMoves", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-xor-with-an-element-from-array", "prompt": "# You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`.\n# \n# The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for all `j` such that `nums[j] <= mi`. If all elements in `nums` are larger than `mi`, then the answer is `-1`.\n# \n# Return an integer array `answer` where `answer.length == queries.length` and `answer[i]` is the answer to the `ith` query.\n# \n# \n# Example 1:\n# Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]\n# Output: [3,3,7]\n# Explanation:\n# 1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.\n# \n# 2) 1 XOR 2 = 3.\n# \n# 3) 5 XOR 2 = 7.\n# \n# \n# Example 2:\n# Input: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]\n# Output: [15,-1,5]\n# \n# Constraints:\n# `1 <= nums.length, queries.length <= 105`\n# `queries[i].length == 2`\n# `0 <= nums[j], xi, mi <= 109`\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n ", "entry_point": "maximizeXor", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-operations-to-make-a-subsequence", "prompt": "# You are given an array `target` that consists of distinct integers and another integer array `arr` that can have duplicates.\n# \n# In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array.\n# \n# Return the minimum number of operations needed to make `target` a subsequence of `arr`.\n# \n# A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not.\n# \n# \n# Example 1:\n# Input: target = [5,1,3], `arr` = [9,4,2,3,4]\n# Output: 2\n# Explanation: You can add 5 and 1 in such a way that makes `arr` = [5,9,4,1,2,3,4], then target will be a subsequence of `arr`.\n# \n# \n# Example 2:\n# Input: target = [6,4,8,1,3,2], `arr` = [4,7,6,2,3,8,6,1]\n# Output: 3\n# \n# Constraints:\n# `1 <= target.length, arr.length <= 105`\n# `1 <= target[i], arr[i] <= 109`\n# `target` contains no duplicates.\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n ", "entry_point": "minOperations", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-ways-to-reconstruct-a-tree", "prompt": "# You are given an array `pairs`, where `pairs[i] = [xi, yi]`, and:\n# There are no duplicates.\n# \n# `xi < yi`\n# Let `ways` be the number of rooted trees that satisfy the following conditions:\n# The tree consists of nodes whose values appeared in `pairs`.\n# \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# \n# Note: the tree does not have to be a binary tree.\n# \n# Two ways are considered to be different if there is at least one node that has different parents in both ways.\n# \n# Return:\n# `0` if `ways == 0`\n# `1` if `ways == 1`\n# `2` if `ways > 1`\n# A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root.\n# \n# An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.\n# \n# \n# Example 1:\n# Input: pairs = [[1,2],[2,3]]\n# Output: 1\n# Explanation: There is exactly one valid rooted tree, which is shown in the above figure.\n# \n# \n# Example 2:\n# Input: pairs = [[1,2],[2,3],[1,3]]\n# Output: 2\n# Explanation: There are multiple valid rooted trees. Three of them are shown in the above figures.\n# \n# \n# Example 3:\n# Input: pairs = [[1,2],[2,3],[2,4],[1,5]]\n# Output: 0\n# Explanation: There are no valid rooted trees.\n# \n# \n# Constraints:\n# `1 <= pairs.length <= 105`\n# `1 <= xi < yi <= 500`\n# The elements in `pairs` are unique.\nclass Solution:\n def checkWays(self, pairs: List[List[int]]) -> int:\n ", "entry_point": "checkWays", "cannonical_solution": "", "test": ""}
{"task_id": "find-minimum-time-to-finish-all-jobs", "prompt": "# You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job.\n# \n# There are `k` workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized.\n# \n# Return the minimum possible maximum working time of any assignment. \n# \n# Example 1:\n# Input: jobs = [3,2,3], k = 3\n# Output: 3\n# Explanation: By assigning each person one job, the maximum time is 3.\n# \n# \n# Example 2:\n# Input: jobs = [1,2,4,7,8], k = 2\n# Output: 11\n# Explanation: Assign the jobs the following way:\n# Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\n# Worker 2: 4, 7 (working time = 4 + 7 = 11)\n# The maximum working time is 11.\n# \n# \n# Constraints:\n# `1 <= k <= jobs.length <= 12`\n# `1 <= jobs[i] <= 107`\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n ", "entry_point": "minimumTimeRequired", "cannonical_solution": "", "test": ""}
{"task_id": "cat-and-mouse-ii", "prompt": "# A game is played by a cat and a mouse named Cat and Mouse.\n# \n# The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food.\n# \n# Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse).\n# \n# Floors are represented by the character `'.'` and can be walked on.\n# \n# Walls are represented by the character `'#'` and cannot be walked on.\n# \n# Food is represented by the character `'F'` and can be walked on.\n# \n# There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.\n# \n# Mouse and Cat play according to the following rules:\n# Mouse moves first, then they take turns to move.\n# \n# During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`.\n# \n# `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.\n# \n# Staying in the same position is allowed.\n# \n# Mouse can jump over Cat.\n# \n# The game can end in 4 ways:\n# If Cat occupies the same position as Mouse, Cat wins.\n# \n# If Cat reaches the food first, Cat wins.\n# \n# If Mouse reaches the food first, Mouse wins.\n# \n# If Mouse cannot get to the food within 1000 turns, Cat wins.\n# \n# Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` if Mouse can win the game if both Cat and Mouse play optimally, otherwise return `false`.\n# \n# \n# Example 1:\n# Input: grid = [\"####F\",\"#C...\",\"M....\"], catJump = 1, mouseJump = 2\n# Output: true\n# Explanation: Cat cannot catch Mouse on its turn nor can it get the food before Mouse.\n# \n# \n# Example 2:\n# Input: grid = [\"M.C...F\"], catJump = 1, mouseJump = 4\n# Output: true\n# \n# Example 3:\n# Input: grid = [\"M.C...F\"], catJump = 1, mouseJump = 3\n# Output: false\n# \n# Example 4:\n# Input: grid = [\"C...#\",\"...#F\",\"....#\",\"M....\"], catJump = 2, mouseJump = 5\n# Output: false\n# \n# Example 5:\n# Input: grid = [\".M...\",\"..#..\",\"#..#.\",\"C#.#.\",\"...#F\"], catJump = 3, mouseJump = 1\n# Output: true\n# \n# Constraints:\n# `rows == grid.length`\n# `cols = grid[i].length`\n# `1 <= rows, cols <= 8`\n# `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`.\n# \n# There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.\n# \n# `1 <= catJump, mouseJump <= 8`\nclass Solution:\n def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:\n ", "entry_point": "canMouseWin", "cannonical_solution": "", "test": ""}
{"task_id": "count-ways-to-make-array-with-product", "prompt": "# You are given a 2D integer array, `queries`. For each `queries[i]`, where `queries[i] = [ni, ki]`, find the number of different ways you can place positive integers into an array of size `ni` such that the product of the integers is `ki`. As the number of ways may be too large, the answer to the `ith` query is the number of ways modulo `109 + 7`.\n# \n# Return an integer array `answer` where `answer.length == queries.length`, and `answer[i]` is the answer to the `ith` query.\n# \n# \n# Example 1:\n# Input: queries = [[2,6],[5,1],[73,660]]\n# Output: [4,1,50734910]\n# Explanation: Each query is independent.\n# \n# [2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].\n# \n# [5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].\n# \n# [73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910.\n# \n# \n# Example 2:\n# Input: queries = [[1,1],[2,2],[3,3],[4,4],[5,5]]\n# Output: [1,2,3,10,5]\n# \n# Constraints:\n# `1 <= queries.length <= 104 `\n# `1 <= ni, ki <= 104`\nclass Solution:\n def waysToFillArray(self, queries: List[List[int]]) -> List[int]:\n ", "entry_point": "waysToFillArray", "cannonical_solution": "", "test": ""}
{"task_id": "building-boxes", "prompt": "# You have a cubic storeroom where the width, length, and height of the room are all equal to `n` units. You are asked to place `n` boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:\n# You can place the boxes anywhere on the floor.\n# \n# If box `x` is placed on top of the box `y`, then each side of the four vertical sides of the box `y` must either be adjacent to another box or to a wall.\n# \n# Given an integer `n`, return the minimum possible number of boxes touching the floor.\n# \n# \n# Example 1:\n# Input: n = 3\n# Output: 3\n# Explanation: The figure above is for the placement of the three boxes.\n# \n# These boxes are placed in the corner of the room, where the corner is on the left side.\n# \n# \n# Example 2:\n# Input: n = 4\n# Output: 3\n# Explanation: The figure above is for the placement of the four boxes.\n# \n# These boxes are placed in the corner of the room, where the corner is on the left side.\n# \n# \n# Example 3:\n# Input: n = 10\n# Output: 6\n# Explanation: The figure above is for the placement of the ten boxes.\n# \n# These boxes are placed in the corner of the room, where the corner is on the back side.\n# \n# \n# Constraints:\n# `1 <= n <= 109`\nclass Solution:\n def minimumBoxes(self, n: int) -> int:\n ", "entry_point": "minimumBoxes", "cannonical_solution": "", "test": ""}
{"task_id": "palindrome-partitioning-iv", "prompt": "# Given a string `s`, return `true` if it is possible to split the string `s` into three non-empty palindromic substrings. Otherwise, return `false`.\u200b\u200b\u200b\u200b\u200b\n# A string is said to be palindrome if it the same string when reversed.\n# \n# \n# Example 1:\n# Input: s = \"abcbdd\"\n# Output: true\n# Explanation: \"abcbdd\" = \"a\" + \"bcb\" + \"dd\", and all three substrings are palindromes.\n# \n# \n# Example 2:\n# Input: s = \"bcbddxy\"\n# Output: false\n# Explanation: s cannot be split into 3 palindromes.\n# \n# \n# Constraints:\n# `3 <= s.length <= 2000`\n# `s`\u200b\u200b\u200b\u200b\u200b\u200b consists only of lowercase English letters.\nclass Solution:\n def checkPartitioning(self, s: str) -> bool:\n ", "entry_point": "checkPartitioning", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-number-of-events-that-can-be-attended-ii", "prompt": "# You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend.\n# \n# You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.\n# \n# Return the maximum sum of values that you can receive by attending events.\n# \n# \n# Example 1:\n# Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2\n# Output: 7\n# Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.\n# \n# \n# Example 2:\n# Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2\n# Output: 10\n# Explanation: Choose event 2 for a total value of 10.\n# \n# Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events.\n# \n# \n# Example 3:\n# Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3\n# Output: 9\n# Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.\n# \n# \n# Constraints:\n# `1 <= k <= events.length`\n# `1 <= k * events.length <= 106`\n# `1 <= startDayi <= endDayi <= 109`\n# `1 <= valuei <= 106`\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n ", "entry_point": "maxValue", "cannonical_solution": "", "test": ""}
{"task_id": "closest-subsequence-sum", "prompt": "# You are given an integer array `nums` and an integer `goal`.\n# \n# You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to minimize the absolute difference `abs(sum - goal)`.\n# \n# Return the minimum possible value of `abs(sum - goal)`.\n# \n# Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.\n# \n# \n# Example 1:\n# Input: nums = [5,-7,3,5], goal = 6\n# Output: 0\n# Explanation: Choose the whole array as a subsequence, with a sum of 6.\n# \n# This is equal to the goal, so the absolute difference is 0.\n# \n# \n# Example 2:\n# Input: nums = [7,-9,15,-2], goal = -5\n# Output: 1\n# Explanation: Choose the subsequence [7,-9,-2], with a sum of -4.\n# \n# The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.\n# \n# \n# Example 3:\n# Input: nums = [1,2,3], goal = -7\n# Output: 7\n# \n# Constraints:\n# `1 <= nums.length <= 40`\n# `-107 <= nums[i] <= 107`\n# `-109 <= goal <= 109`\nclass Solution:\n def minAbsDifference(self, nums: List[int], goal: int) -> int:\n ", "entry_point": "minAbsDifference", "cannonical_solution": "", "test": ""}
{"task_id": "minimum-degree-of-a-connected-trio-in-a-graph", "prompt": "# You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.\n# \n# A connected trio is a set of three nodes where there is an edge between every pair of them.\n# \n# The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not.\n# \n# Return the minimum degree of a connected trio in the graph, or `-1` if the graph has no connected trios.\n# \n# \n# Example 1:\n# Input: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]\n# Output: 3\n# Explanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above.\n# \n# \n# Example 2:\n# Input: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]\n# Output: 0\n# Explanation: There are exactly three trios:\n# 1) [1,4,3] with degree 0.\n# \n# 2) [2,5,6] with degree 2.\n# \n# 3) [5,6,7] with degree 2.\n# \n# \n# Constraints:\n# `2 <= n <= 400`\n# `edges[i].length == 2`\n# `1 <= edges.length <= n * (n-1) / 2`\n# `1 <= ui, vi <= n`\n# `ui != vi`\n# There are no repeated edges.\nclass Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n ", "entry_point": "minTrioDegree", "cannonical_solution": "", "test": ""}
{"task_id": "tree-of-coprimes", "prompt": "# There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` edges. Each node has a value associated with it, and the root of the tree is node `0`.\n# \n# To represent this tree, you are given an integer array `nums` and a 2D array `edges`. Each `nums[i]` represents the `ith` node's value, and each `edges[j] = [uj, vj]` represents an edge between nodes `uj` and `vj` in the tree.\n# \n# Two values `x` and `y` are coprime if `gcd(x, y) == 1` where `gcd(x, y)` is the greatest common divisor of `x` and `y`.\n# \n# An ancestor of a node `i` is any other node on the shortest path from node `i` to the root. A node is not considered an ancestor of itself.\n# \n# Return an array `ans` of size `n`, where `ans[i]` is the closest ancestor to node `i` such that `nums[i]` and `nums[ans[i]]` are coprime, or `-1` if there is no such ancestor.\n# \n# \n# Example 1:\n# Input: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]\n# Output: [-1,0,0,1]\n# Explanation: In the above figure, each node's value is in parentheses.\n# \n# - Node 0 has no coprime ancestors.\n# \n# - Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).\n# \n# - Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's\n# value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.\n# \n# - Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its\n# closest valid ancestor.\n# \n# \n# Example 2:\n# Input: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]\n# Output: [-1,0,-1,0,0,0,-1]\n# \n# Constraints:\n# `nums.length == n`\n# `1 <= nums[i] <= 50`\n# `1 <= n <= 105`\n# `edges.length == n - 1`\n# `edges[j].length == 2`\n# `0 <= uj, vj < n`\n# `uj != vj`\nclass Solution:\n def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]:\n ", "entry_point": "getCoprimes", "cannonical_solution": "", "test": ""}
{"task_id": "maximize-palindrome-length-from-subsequences", "prompt": "# You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:\n# Choose some non-empty subsequence `subsequence1` from `word1`.\n# \n# Choose some non-empty subsequence `subsequence2` from `word2`.\n# \n# Concatenate the subsequences: `subsequence1 + subsequence2`, to make the string.\n# \n# Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return `0`.\n# \n# A subsequence of a string `s` is a string that can be made by deleting some (possibly none) characters from `s` without changing the order of the remaining characters.\n# \n# A palindrome is a string that reads the same forward as well as backward.\n# \n# \n# Example 1:\n# Input: word1 = \"cacb\", word2 = \"cbba\"\n# Output: 5\n# Explanation: Choose \"ab\" from word1 and \"cba\" from word2 to make \"abcba\", which is a palindrome.\n# \n# \n# Example 2:\n# Input: word1 = \"ab\", word2 = \"ab\"\n# Output: 3\n# Explanation: Choose \"ab\" from word1 and \"a\" from word2 to make \"aba\", which is a palindrome.\n# \n# \n# Example 3:\n# Input: word1 = \"aa\", word2 = \"bb\"\n# Output: 0\n# Explanation: You cannot construct a palindrome from the described method, so return 0.\n# \n# \n# Constraints:\n# `1 <= word1.length, word2.length <= 1000`\n# `word1` and `word2` consist of lowercase English letters.\nclass Solution:\n def longestPalindrome(self, word1: str, word2: str) -> int:\n ", "entry_point": "longestPalindrome", "cannonical_solution": "", "test": ""}
{"task_id": "car-fleet-ii", "prompt": "# There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where `cars[i] = [positioni, speedi]` represents:\n# `positioni` is the distance between the `ith` car and the beginning of the road in meters. It is guaranteed that `positioni < positioni+1`.\n# \n# `speedi` is the initial speed of the `ith` car in meters per second.\n# \n# For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet.\n# \n# Return an array `answer`, where `answer[i]` is the time, in seconds, at which the `ith` car collides with the next car, or `-1` if the car does not collide with the next car. Answers within `10-5` of the actual answers are accepted.\n# \n# \n# Example 1:\n# Input: cars = [[1,2],[2,1],[4,3],[7,2]]\n# Output: [1.00000,-1.00000,3.00000,-1.00000]\n# Explanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.\n# \n# \n# Example 2:\n# Input: cars = [[3,4],[5,4],[6,3],[9,1]]\n# Output: [2.00000,1.00000,1.50000,-1.00000]\n# \n# Constraints:\n# `1 <= cars.length <= 105`\n# `1 <= positioni, speedi <= 106`\n# `positioni < positioni+1`\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n ", "entry_point": "getCollisionTimes", "cannonical_solution": "", "test": ""}
{"task_id": "count-pairs-of-nodes", "prompt": "# You are given an undirected graph represented by an integer `n`, which is the number of nodes, and `edges`, where `edges[i] = [ui, vi]` which indicates that there is an undirected edge between `ui` and `vi`. You are also given an integer array `queries`.\n# \n# The answer to the `jth` query is the number of pairs of nodes `(a, b)` that satisfy the following conditions:\n# `a < b`\n# `cnt` is strictly greater than `queries[j]`, where `cnt` is the number of edges incident to `a` or `b`.\n# \n# Return an array `answers` such that `answers.length == queries.length` and `answers[j]` is the answer of the `jth` query.\n# \n# Note that there can be repeated edges.\n# \n# \n# Example 1:\n# Input: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]\n# Output: [6,5]\n# Explanation: The number of edges incident to at least one of each pair is shown above.\n# \n# \n# Example 2:\n# Input: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]\n# Output: [10,10,9,8,6]\n# \n# Constraints:\n# `2 <= n <= 2 * 104`\n# `1 <= edges.length <= 105`\n# `1 <= ui, vi <= n`\n# `ui != vi`\n# `1 <= queries.length <= 20`\n# `0 <= queries[j] < edges.length`\nclass Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n ", "entry_point": "countPairs", "cannonical_solution": "", "test": ""}
{"task_id": "make-the-xor-of-all-segments-equal-to-zero", "prompt": "# You are given an array `nums`\u200b\u200b\u200b and an integer `k`\u200b\u200b\u200b\u200b\u200b. The XOR of a segment `[left, right]` where `left <= right` is the `XOR` of all the elements with indices between `left` and `right`, inclusive: `nums[left] XOR nums[left+1] XOR ... XOR nums[right]`.\n# \n# Return the minimum number of elements to change in the array such that the `XOR` of all segments of size `k`\u200b\u200b\u200b\u200b\u200b\u200b is equal to zero.\n# \n# \n# Example 1:\n# Input: nums = [1,2,0,3,0], k = 1\n# Output: 3\n# Explanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0].\n# \n# \n# Example 2:\n# Input: nums = [3,4,5,2,1,7,3,4,7], k = 3\n# Output: 3\n# Explanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7].\n# \n# \n# Example 3:\n# Input: nums = [1,2,4,1,2,5,1,2,6], k = 3\n# Output: 3\n# Explanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].\n# \n# \n# Constraints:\n# `1 <= k <= nums.length <= 2000`\n# `\u200b\u200b\u200b\u200b\u200b\u200b0 <= nums[i] < 210`\nclass Solution:\n def minChanges(self, nums: List[int], k: int) -> int:\n ", "entry_point": "minChanges", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-score-of-a-good-subarray", "prompt": "# You are given an array of integers `nums` (0-indexed) and an integer `k`.\n# \n# The score of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A good subarray is a subarray where `i <= k <= j`.\n# \n# Return the maximum possible score of a good subarray.\n# \n# \n# Example 1:\n# Input: nums = [1,4,3,7,4,5], k = 3\n# Output: 15\n# Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. \n# \n# Example 2:\n# Input: nums = [5,5,4,5,4,1,1,1], k = 0\n# Output: 20\n# Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.\n# \n# \n# Constraints:\n# `1 <= nums.length <= 105`\n# `1 <= nums[i] <= 2 * 104`\n# `0 <= k < nums.length`\nclass Solution:\n def maximumScore(self, nums: List[int], k: int) -> int:\n ", "entry_point": "maximumScore", "cannonical_solution": "", "test": ""}
{"task_id": "maximize-score-after-n-operations", "prompt": "# You are given `nums`, an array of positive integers of size `2 * n`. You must perform `n` operations on this array.\n# \n# In the `ith` operation (1-indexed), you will:\n# Choose two elements, `x` and `y`.\n# \n# Receive a score of `i * gcd(x, y)`.\n# \n# Remove `x` and `y` from `nums`.\n# \n# Return the maximum score you can receive after performing `n` operations.\n# \n# The function `gcd(x, y)` is the greatest common divisor of `x` and `y`.\n# \n# \n# Example 1:\n# Input: nums = [1,2]\n# Output: 1\n# Explanation: The optimal choice of operations is:\n# (1 * gcd(1, 2)) = 1\n# \n# Example 2:\n# Input: nums = [3,4,6,8]\n# Output: 11\n# Explanation: The optimal choice of operations is:\n# (1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11\n# \n# Example 3:\n# Input: nums = [1,2,3,4,5,6]\n# Output: 14\n# Explanation: The optimal choice of operations is:\n# (1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14\n# \n# Constraints:\n# `1 <= n <= 7`\n# `nums.length == 2 * n`\n# `1 <= nums[i] <= 106`\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n ", "entry_point": "maxScore", "cannonical_solution": "", "test": ""}
{"task_id": "count-pairs-with-xor-in-a-range", "prompt": "# Given a (0-indexed) integer array `nums` and two integers `low` and `high`, return the number of nice pairs.\n# \n# A nice pair is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`.\n# \n# \n# Example 1:\n# Input: nums = [1,4,2,7], low = 2, high = 6\n# Output: 6\n# Explanation: All nice pairs (i, j) are as follows:\n# - (0, 1): nums[0] XOR nums[1] = 5 \n# - (0, 2): nums[0] XOR nums[2] = 3\n# - (0, 3): nums[0] XOR nums[3] = 6\n# - (1, 2): nums[1] XOR nums[2] = 6\n# - (1, 3): nums[1] XOR nums[3] = 3\n# - (2, 3): nums[2] XOR nums[3] = 5\n# \n# Example 2:\n# Input: nums = [9,8,4,2,1], low = 5, high = 14\n# Output: 8\n# Explanation: All nice pairs (i, j) are as follows:\n# \u200b\u200b\u200b\u200b\u200b - (0, 2): nums[0] XOR nums[2] = 13\n# - (0, 3): nums[0] XOR nums[3] = 11\n# - (0, 4): nums[0] XOR nums[4] = 8\n# - (1, 2): nums[1] XOR nums[2] = 12\n# - (1, 3): nums[1] XOR nums[3] = 10\n# - (1, 4): nums[1] XOR nums[4] = 9\n# - (2, 3): nums[2] XOR nums[3] = 6\n# - (2, 4): nums[2] XOR nums[4] = 5\n# \n# Constraints:\n# `1 <= nums.length <= 2 * 104`\n# `1 <= nums[i] <= 2 * 104`\n# `1 <= low <= high <= 2 * 104`\nclass Solution:\n def countPairs(self, nums: List[int], low: int, high: int) -> int:\n ", "entry_point": "countPairs", "cannonical_solution": "", "test": ""}
{"task_id": "maximize-number-of-nice-divisors", "prompt": "# You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions:\n# The number of prime factors of `n` (not necessarily distinct) is at most `primeFactors`.\n# \n# The number of nice divisors of `n` is maximized. Note that a divisor of `n` is nice if it is divisible by every prime factor of `n`. For example, if `n = 12`, then its prime factors are `[2,2,3]`, then `6` and `12` are nice divisors, while `3` and `4` are not.\n# \n# Return the number of nice divisors of `n`. Since that number can be too large, return it modulo `109 + 7`.\n# \n# Note that a prime number is a natural number greater than `1` that is not a product of two smaller natural numbers. The prime factors of a number `n` is a list of prime numbers such that their product equals `n`.\n# \n# \n# Example 1:\n# Input: primeFactors = 5\n# Output: 6\n# Explanation: 200 is a valid value of n.\n# \n# It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].\n# \n# There is not other value of n that has at most 5 prime factors and more nice divisors.\n# \n# \n# Example 2:\n# Input: primeFactors = 8\n# Output: 18\n# \n# Constraints:\n# `1 <= primeFactors <= 109`\nclass Solution:\n def maxNiceDivisors(self, primeFactors: int) -> int:\n ", "entry_point": "maxNiceDivisors", "cannonical_solution": "", "test": ""}
{"task_id": "maximum-number-of-groups-getting-fresh-donuts", "prompt": "# There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` customers that will visit the shop. Each customer will get exactly one donut.\n# \n# When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.\n# \n# You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.\n# \n# \n# Example 1:\n# Input: batchSize = 3, groups = [1,2,3,4,5,6]\n# Output: 4\n# Explanation: You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy.\n# \n# \n# Example 2:\n# Input: batchSize = 4, groups = [1,3,2,5,2,2,1,6]\n# Output: 4\n# \n# Constraints:\n# `1 <= batchSize <= 9`\n# `1 <= groups.length <= 30`\n# `1 <= groups[i] <= 109`\nclass Solution:\n def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int:\n ", "entry_point": "maxHappyGroups", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-different-subsequences-gcds", "prompt": "# You are given an array `nums` that consists of positive integers.\n# \n# The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly.\n# \n# For example, the GCD of the sequence `[4,6,16]` is `2`.\n# \n# A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.\n# \n# For example, `[2,5,10]` is a subsequence of `[1,2,1,2,4,1,5,10]`.\n# \n# Return the number of different GCDs among all non-empty subsequences of `nums`.\n# \n# \n# Example 1:\n# Input: nums = [6,10,3]\n# Output: 5\n# Explanation: The figure shows all the non-empty subsequences and their GCDs.\n# \n# The different GCDs are 6, 10, 3, 2, and 1.\n# \n# \n# Example 2:\n# Input: nums = [5,15,40,5,6]\n# Output: 7\n# \n# Constraints:\n# `1 <= nums.length <= 105`\n# `1 <= nums[i] <= 2 * 105`\nclass Solution:\n def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int:\n ", "entry_point": "countDifferentSubsequenceGCDs", "cannonical_solution": "", "test": ""}
{"task_id": "finding-mk-average", "prompt": "# You are given two integers, `m` and `k`, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream.\n# \n# The MKAverage can be calculated using these steps:\n# If the number of the elements in the stream is less than `m` you should consider the MKAverage to be `-1`. Otherwise, copy the last `m` elements of the stream to a separate container.\n# \n# Remove the smallest `k` elements and the largest `k` elements from the container.\n# \n# Calculate the average value for the rest of the elements rounded down to the nearest integer.\n# \n# Implement the `MKAverage` class:\n# `MKAverage(int m, int k)` Initializes the MKAverage object with an empty stream and the two integers `m` and `k`.\n# \n# `void addElement(int num)` Inserts a new element `num` into the stream.\n# \n# `int calculateMKAverage()` Calculates and returns the MKAverage for the current stream rounded down to the nearest integer.\n# \n# \n# Example 1:\n# Input\n# [\"MKAverage\", \"addElement\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"addElement\", \"addElement\", \"calculateMKAverage\"]\n# [[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]\n# Output\n# [null, null, null, -1, null, 3, null, null, null, 5]\n# Explanation\n# MKAverage obj = new MKAverage(3, 1); \n# obj.addElement(3); // current elements are [3]\n# obj.addElement(1); // current elements are [3,1]\n# obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.\n# \n# obj.addElement(10); // current elements are [3,1,10]\n# obj.calculateMKAverage(); // The last 3 elements are [3,1,10].\n# \n# // After removing smallest and largest 1 element the container will be `[3].\n# \n# // The average of [3] equals 3/1 = 3, return 3\n# obj.addElement(5); // current elements are [3,1,10,5]\n# obj.addElement(5); // current elements are [3,1,10,5,5]\n# obj.addElement(5); // current elements are [3,1,10,5,5,5]\n# obj.calculateMKAverage(); // The last 3 elements are [5,5,5].\n# \n# // After removing smallest and largest 1 element the container will be `[5].\n# \n# // The average of [5] equals 5/1 = 5, return 5\n# ``\n# \n# Constraints:\n# `3 <= m <= 105`\n# `1 <= k*2 < m`\n# `1 <= num <= 105`\n# At most `105` calls will be made to `addElement` and `calculateMKAverage`.\nclass MKAverage:\n\n def __init__(self, m: int, k: int):\n \n\n def addElement(self, num: int) -> None:\n \n\n def calculateMKAverage(self) -> int:\n \n\n\n# Your MKAverage object will be instantiated and called as such:\n# obj = MKAverage(m, k)\n# obj.addElement(num)\n# param_2 = obj.calculateMKAverage()", "entry_point": "__init__", "cannonical_solution": "", "test": ""}
{"task_id": "arithmetic-slices-ii-subsequence", "prompt": "# A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.\n# \n# For example, these are arithmetic sequences:\n# 1, 3, 5, 7, 9\n# 7, 7, 7, 7\n# 3, -1, -5, -9\n# The following sequence is not arithmetic.\n# \n# 1, 1, 2, 5, 7\n# A zero-indexed array A consisting of N numbers is given. A subsequence slice of that array is any sequence of integers (P0, P1, ..., Pk) such that 0 \u2264 P0 < P1 < ... < Pk < N.\n# \n# A subsequence slice (P0, P1, ..., Pk) of array A is called arithmetic if the sequence A[P0], A[P1], ..., A[Pk-1], A[Pk] is arithmetic. In particular, this means that k \u2265 2.\n# \n# The function should return the number of arithmetic subsequence slices in the array A.\n# \n# The input contains N integers. Every integer is in the range of -231 and 231-1 and 0 \u2264 N \u2264 1000. The output is guaranteed to be less than 231-1.\n# \n# \n# Example:\n# Input: [2, 4, 6, 8, 10]\n# Output: 7\n# Explanation:\n# All arithmetic subsequence slices are:\n# [2,4,6]\n# [4,6,8]\n# [6,8,10]\n# [2,4,6,8]\n# [4,6,8,10]\n# [2,4,6,8,10]\n# [2,6,10]\nclass Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n ", "entry_point": "numberOfArithmeticSlices", "cannonical_solution": "", "test": ""}
{"task_id": "number-of-ways-to-paint-n-3-grid", "prompt": "# You have a `grid` of size `n x 3` and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).\n# \n# Given `n` the number of rows of the grid, return the number of ways you can paint this `grid`. As the answer may grow large, the answer must be computed modulo `109 + 7`.\n# \n# \n# Example 1:\n# Input: n = 1\n# Output: 12\n# Explanation: There are 12 possible way to paint the grid as shown.\n# \n# \n# Example 2:\n# Input: n = 2\n# Output: 54\n# \n# Example 3:\n# Input: n = 3\n# Output: 246\n# \n# Example 4:\n# Input: n = 7\n# Output: 106494\n# \n# Example 5:\n# Input: n = 5000\n# Output: 30228214\n# \n# Constraints:\n# `n == grid.length`\n# `grid[i].length == 3`\n# `1 <= n <= 5000`\nclass Solution:\n def numOfWays(self, n: int) -> int:\n ", "entry_point": "numOfWays", "cannonical_solution": "", "test": ""}

Loading…
Cancel
Save